pku 3041 Asteroids

来源:互联网 发布:迪杰斯特拉算法 严蔚敏 编辑:程序博客网 时间:2024/05/23 00:09

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 41 11 32 23 2

Sample Output

2

Hint

INPUT DETAILS:
The following diagram represents the data, where "X" is an asteroid and "." is empty space:
X.X
.X.
.X.


OUTPUT DETAILS:
Bessie may fire across row 1 to destroy the asteroids at (1,1) and (1,3), and then she may fire down column 2 to destroy the asteroids at (2,2) and (3,2).
 
KEY:
这题貌似好早学长们布置的题目……当时也有人讲了……貌似还是不会……今天看二分图匹配,     突然想去做,居然神奇的AC了。
 
这题用的是二分图匹配的匈牙利算法。
 
  1. Source Code 
  2. #include<iostream>
  3. #define N 500
  4. using namespace std;
  5. int a[N+1][N+1];
  6. int n,m;
  7. int match[N+1];
  8. int check[N+1];
  9. int dfs(int p)
  10. {
  11.     int i,t;
  12.     for(i=1;i<=n;i++)
  13.         if(a[i][p]&&!check[i])
  14.         {
  15.             check[i]=1;
  16.             t=match[i];
  17.             match[i]=p;
  18.             if(t==0||dfs(t)) return 1;
  19.             match[i]=t;
  20.         }
  21.     return 0;
  22. }
  23. void input()
  24. {
  25.     scanf("%d %d",&n,&m);
  26.     int i;
  27.     int x,y;
  28.     for(i=1;i<=m;i++)
  29.     {
  30.         scanf("%d %d",&x,&y);
  31.         a[x][y]=1;
  32.     }
  33. }
  34. int main()
  35. {
  36. //  freopen("pku_3041.in","r",stdin);
  37.     input();
  38.     int i,max=0;
  39.     for(i=1;i<=n;i++)
  40.     {
  41.         memset(check,0,sizeof(check));
  42.         if(dfs(i)) max++;
  43.     }
  44.     printf("%d/n",max);
  45.     return 0;
  46. }
 
 
原创粉丝点击