Asteroids
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 28 Accepted Submission(s) : 5
Problem 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 12 21 33 2
Sample Output
2这题BFS+KMPAC代码:#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<cmath> #include<queue> #include<stack> #include<iomanip> #include<algorithm> const int MAX=2500; const int Max=100000; int Map[MAX][MAX]; int p[MAX]; int start; int end; int n; using namespace std; int BFS() { int que[Max],base,top,i,j,x; base=0; top=0; memset(p,0,sizeof(p)); que[top]=start; top+=1; p[start]=0; while(base<top) { x=que[base]; base+=1; for(i=1;i<=2*n+1;i++) { if(p[i]==0&&Map[x][i]) { p[i]=x; que[top]=i; top+=1; if(i==end) { break; } } } if(i!=2*n+2) { break; } } if(p[end]==0) { return 0; } return 1; } int KMP() { int i,j,k,sum,t,pp; sum=0; while(true) { k=BFS(); if(k==0) break; sum+=1; for(t=end;t!=start;t=p[t]) { pp=p[t]; Map[pp][t]=0; Map[t][pp]=1; } } return sum; } int main() { int i,j,k,Count,x,y; cin>>n>>k; start=0; end=2*n+1; memset(Map,0,sizeof(Map)); for(i=1;i<=k;i++) { cin>>x>>y; Map[0][x]=1; Map[n+y][2*n+1]=1; Map[x][n+y]=1; } Count=KMP(); cout<<Count<<endl; return 0; }