G – Asteroids
Bessie wants to navigate her spaceship through adangerous 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 convenientlylocated at the lattice points of the grid.
Fortunately, Bessie has a powerful weapon that can vaporize all the asteroidsin any given row or column of the grid with a single shot.This weapon is quiteexpensive, so she wishes to use it sparingly.Given the location of all theasteroids in the field, find
the minimum number of shots Bessie needs to fireto eliminate all of the asteroids.
Input
* Line 1: Two integers N and K, separated by a singlespace.
* 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 oftimes Bessie must shoot.
Sample Input
3 4
1 1
1 3
2 2
3 2
Sample Output
2
Hint
INPUT DETAILS:
The following diagram represents the data, where "X" is an asteroidand "." 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), andthen she may fire down column 2 to destroy the asteroids at (2,2) and (3,2).
#include<stdio.h>
#include<string.h>
int a[1000][1000],s[1000],b[1000];
int m,n;
int dfs(int x)
{
int i;
for(i=1;i<=n;i++)
{
if(b[i]==0&&a[x][i]==1)
{
b[i]=1;
if(s[i]==-1||dfs(s[i]))
{
s[i]=x;
return 1;
}
}
}
return 0;
}
int main()
{
int i,j,k,t1,t2,sum;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(a,0,sizeof(a));
memset(s,-1,sizeof(s));
for(i=1;i<=m;i++)
{
scanf("%d%d",&t1,&t2);
a[t1][t2]=1;
}
sum=0;
for(i=1;i<=n;i++)
{
memset(b,0,sizeof(b));
if(dfs(i))
sum++;
}
printf("%d\n",sum);
}
return 0;
}