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
1 1
1 3
2 2
3 2
INPUT DETAILS:
The following diagram represents the data, where "X" is an
asteroid and "." is empty space:
X.X
.X.
.X.
Sample Output
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).
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #define mem(a,p) memset(a,p,sizeof(a)) 5 const int N=2205,inf=0x3f3f3f3f; 6 struct node{int ne,to,w;}e[600000]; 7 int first[N],cur[N],n,k,tot=1,t,d[N],q[N]; 8 using std::min; 9 int read(){ 10 int ans=0,f=1;char c=getchar(); 11 while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();} 12 while(c>='0'&&c<='9'){ans=ans*10+c-48;c=getchar();} 13 return ans*f; 14 } 15 void ins(int u,int v,int w){ 16 e[++tot]=(node){first[u],v,w};first[u]=tot; 17 } 18 void insert(int u,int v,int w){ins(u,v,w);ins(v,u,0);} 19 bool bfs(){ 20 mem(d,-1); 21 int h=0,tail=1;q[0]=0;d[0]=1; 22 while(h!=tail){ 23 int x=q[h];h++;if(h>=1200)h=0; 24 for(int i=first[x];i;i=e[i].ne){ 25 int to=e[i].to; 26 if(d[to]==-1&&e[i].w>0){ 27 d[to]=d[x]+1; 28 q[tail]=to;tail++;if(tail>=1200)tail=0; 29 } 30 } 31 } 32 return d[t]!=-1; 33 } 34 int dfs(int x,int a){ 35 if(x==t||a==0)return a; 36 int flow=0,f; 37 for(int&i=cur[x];i;i=e[i].ne){ 38 int to=e[i].to; 39 if(d[to]==d[x]+1&&(f=dfs(to,min(a,e[i].w)))>0){ 40 e[i].w-=f; 41 e[i^1].w+=f; 42 a-=f; 43 flow+=f; 44 if(!a)break; 45 } 46 } 47 return flow; 48 } 49 int main(){ 50 n=read();k=read();t=n*2+1; 51 for(int i=1;i<=n;i++)insert(0,i,1),insert(n+i,t,1); 52 for(int i=1,a,b;i<=k;i++){ 53 a=read();b=read(); 54 insert(a,n+b,inf); 55 } 56 int ans=0; 57 while(bfs()){ 58 for(int i=0;i<=t;i++)cur[i]=first[i]; 59 ans+=dfs(0,inf); 60 } 61 printf("%d ",ans); 62 return 0; 63 }