poj 3041 Asteroids 初级-》二分图最大匹配

来源:互联网 发布:天津seo搜索排名优化 编辑:程序博客网 时间:2024/04/28 15:40

                                                                      Asteroids
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10880 Accepted: 5893

Description

Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N grid (1 <= N <= 500). The grid contains K asteroids (1 <= K <= 10,000), which are conveniently located at the lattice points of the grid.

Fortunately, Bessie has a powerful weapon that can vaporize all the asteroids in any given row or column of the grid with a single shot.This weapon is quite expensive, so she wishes to use it sparingly.Given the location of all the asteroids in the field, find the minimum number of shots Bessie needs to fire to eliminate all of the asteroids.
Input

* Line 1: Two integers N and K, separated by a single space.
* Lines 2..K+1: Each line contains two space-separated integers R and C (1 <= R, C <= N) denoting the row and column coordinates of an asteroid, respectively.
Output

* Line 1: The integer representing the minimum number of times Bessie must shoot.
Sample Input

3 4
1 1
1 3
2 2
3 2

Sample Output

2

 

题目类型:图论、最大二分匹配、匈牙利算法。

 

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<string>#include<stack>#include<queue>using namespace std;int n,k;int graph[501][501],link[501];bool vist[501];bool dfs(int u){    int v;    for(v=1;v<=n;v++)    if(graph[u][v]&&!vist[v])    {      vist[v]=true;      if(link[v]==0||dfs(link[v]))      {        link[v]=u;        return true;      }    }    return false;}int matchnum(){    int sum=0;    int u;    memset(link,0,sizeof(link));    for(u=1;u<=n;u++)    {      memset(vist,false,sizeof(vist));      if(dfs(u))      sum++;    }    return sum;}int main(){    int i,r,c;    cin>>n>>k;    memset(graph,0,sizeof(graph));    for(i=1;i<=k;i++)    {        cin>>r>>c;        graph[r][c]=1;    }    cout<<matchnum()<<endl;    return 0;}