---
id: 558
lang: en
translation_of: index.md
source_sha256: 105066ab66adeeb6ad4cf4dc4a7396344081cd6f7fb05f4446cdd045d81699d4
title: "POJ3041: [USACO2006NOV] Asteriod — Solution"
description: "We can solve this with bipartite matching: map each asteroid's x- and y-coordinates onto a bipartite graph and find the maximum matching."
tags: ["OI","Bipartite Matching","Bipartite Graph","Hungarian Algorithm"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The title keeps the author's spelling Asteriod verbatim, as the Chinese archive does."
---

## Idea

We can solve this problem with bipartite matching. We map the x- and y-coordinates of each asteroid onto a bipartite graph, then just find the maximum matching.

## Code

```cpp
// POJ3041.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAX_N = 510;
int n, k, head[MAX_N], current, tmpx, tmpy, dfn[MAX_N], match[MAX_N], ans;
struct edge
{
    int to, nxt;
} edges[21000];
void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}
bool dfs(int u, int tm)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
    {
        int to = edges[i].to;
        if (dfn[to] != tm)
        {
            dfn[to] = tm;
            if ((!match[to]) || dfs(match[to], tm))
            {
                match[to] = u;
                return true;
            }
        }
    }
    return false;
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &k);
    for (int i = 1; i <= k; i++)
        scanf("%d%d", &tmpx, &tmpy), addpath(tmpx, tmpy);
    for (int i = 1; i <= n; i++)
        if (dfs(i, i))
            ans++;
    printf("%d", ans);
    return 0;
}
```
