---
id: 558
title: "POJ3041:「USACO2006NOV」Asteriod 题解"
slug: poj3041-usaco2006nov-asteroid
lang: zh
date: 2019-01-29T19:23:12
date_gmt: 2019-01-29T11:23:12
modified: 2023-11-11T14:50:47
status: publish
password_protected: false
category: { name: Olympiad in Informatics, slug: oi }
tags: [OI, 二分图匹配, 二分图, 匈牙利算法]
original_url: https://kalorona.com/oi/poj3041usaco2006novasteriod-题解/
archived: 2026-11-27
editor: classic
media: []
archive_notes:
  - "Body headings were <h1> in the original; demoted to level 2 so the page title is the only h1."
  - "The attachment Asteroid.jpg was only the theme's featured image (post thumbnail), not part of the post body, so it was not copied."
  - "The slug uses the correct spelling asteroid; the title keeps the author's spelling Asteriod verbatim."
comments: []
---

## 思路

我们可以使用二分图匹配来做这个题目。我们把每一个小行星的横坐标和纵坐标映射到二分图上，找最大匹配即可。

## 代码

```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;
}
```
