http://acm.hdu.edu.cn/showproblem.php?pid=3529
题目大意:最少需要几个炸弹(先后放)能够把所有的墙炸掉。
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <cmath> #include <queue> using namespace std; template <class T> void checkmin(T &t,T x) {if(x < t) t = x;} template <class T> void checkmax(T &t,T x) {if(x > t) t = x;} template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;} template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;} typedef pair <int,int> PII; typedef pair <double,double> PDD; typedef long long ll; #define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++) const int N = 200 , V = 1020; int U[V] , D[V] , L[V] , R[V] , C[V]; int H[N] , S[N] , visit[17][17]; int size , n , m , ak; int rr , cc; // 代表0-1矩阵的行和列 char mp[17][17]; void Link(int r,int c) { S[c] ++; C[size] = c; U[size] = U[c]; D[U[c]] = size; D[size] = c; U[c] = size; if(H[r] == -1) H[r]=L[size]=R[size]=size; else { L[size]=L[H[r]];R[L[H[r]]]=size; R[size]=H[r];L[H[r]]=size; } size ++; } void remove(int c) { //delete column int i; for(i=D[c];i!=c;i=D[i]) L[R[i]]=L[i],R[L[i]]=R[i]; } void resume(int c) { int i; for(i=U[c];i!=c;i=U[i]) L[R[i]] = R[L[i]] = i; } int h() { int i,j,k,count = 0; bool hash[N]; memset(hash,0,sizeof(hash)); for(i=R[0];i;i=R[i]) { if(hash[i]) continue; hash[i] = 1; count ++; for(j=D[i];j!=i;j=D[j]) for(k=R[j];k!=j;k=R[k]) hash[C[k]] = 1; } return count; } void Dance(int k) { int i , j ,Min , c; if(h()+k >= ak) return; if(!R[0]) { checkmin(ak , k); return; } for(Min=N,i=R[0];i;i=R[i]) if(S[i] < Min) Min = S[i] , c = i; for(i=D[c];i!=c;i=D[i]) { remove(i); for(j=R[i];j!=i;j=R[j]) remove(j); Dance(k+1); for(j=L[i];j!=i;j=L[j]) resume(j); resume(i); } } int main() { while(~scanf("%d%d",&n,&m)) { cc = 0; memset(visit,0,sizeof(visit)); for(int i=0;i<n;i++) scanf("%s",mp[i]); for(int i=0;i<n;i++) for(int j=0;j<m;j++) if(mp[i][j] == '#') visit[i][j] = ++cc; for(int i=0;i<=cc;i++) { S[i] = 0; D[i] = U[i] = i; L[i+1] = i; R[i] = i+1; } R[cc] = 0; size = cc + 1; memset(H,-1,sizeof(H)); rr = 0; for(int i=1;i<n-1;i++) { for(int j=1;j<m-1;j++) { if(mp[i][j] == '.') { rr ++; int k1 , k2; k1 = i-1;k2 = j; while(mp[k1][k2]=='.') k1--; if(mp[k1][k2]=='#') Link(rr,visit[k1][k2]); k1 = i+1;k2 = j; while(mp[k1][k2]=='.') k1++; if(mp[k1][k2]=='#') Link(rr,visit[k1][k2]); k1 = i;k2 = j-1; while(mp[k1][k2]=='.') k2--; if(mp[k1][k2]=='#') Link(rr,visit[k1][k2]); k1 = i;k2 = j+1; while(mp[k1][k2]=='.') k2++; if(mp[k1][k2]=='#') Link(rr,visit[k1][k2]); } } } ak = N; Dance(0); printf("%d\n" , ak); } return 0; }