Time Limit: 2000/1000 MS
(Java/Others) Memory Limit: 65536/32768 K
(Java/Others)
Total Submission(s): 410 Accepted
Submission(s): 143
1 #include<iostream> 2 #include<stdio.h> 3 #include<cstring> 4 #include<cstdlib> 5 #include<queue> 6 using namespace std; 7 8 int n,m,MAX; 9 char tom[20][20]; 10 int a[20][20]; 11 int to[4][2]={{1,0},{0,1},{0,-1},{-1,0}}; 12 bool hash[20][20]; 13 bool use[20][20]; 14 struct node 15 { 16 friend bool operator< (node n1,node n2) 17 { 18 if(n1.val>n2.val)return false;//no return true; 19 else if(n1.val==n2.val) 20 { 21 if(n1.x<n2.x)return false; 22 else if(n1.x==n2.x && n1.y<n2.y) return false; 23 } 24 return true; 25 } 26 int x,y,val; 27 }; 28 struct st 29 { 30 int x,y; 31 }; 32 priority_queue<node>Q; 33 34 int bfs(int x,int y,int num) 35 { 36 int i,cout=1; 37 queue<st>S; 38 st t,cur; 39 t.x=x; 40 t.y=y; 41 hash[x][y]=true; 42 S.push(t); 43 44 while(!S.empty()) 45 { 46 cur=S.front(); 47 S.pop(); 48 for(i=0;i<4;i++) 49 { 50 t=cur; 51 t.x=t.x+to[i][0]; 52 t.y=t.y+to[i][1]; 53 if(t.x>=0&&t.x<n &&t.y>=0&&t.y<m && !hash[t.x][t.y] && a[t.x][t.y]==num){ 54 hash[t.x][t.y]=true; 55 cout++; 56 S.push(t); 57 } 58 } 59 } 60 return cout; 61 } 62 void change(node &t) 63 { 64 int i,j,k; 65 int qq[20][20]; 66 memset(qq,0,sizeof(qq)); 67 memset(hash,false,sizeof(hash)); 68 k = bfs(t.x,t.y,a[t.x][t.y]); 69 for(i=0;i<n;i++) 70 for(j=0;j<m;j++) 71 if(hash[i][j]) a[i][j]=0; 72 for(i=0;i<m;i++){ 73 for(j=n-1,k=n-1;j>=0;j--) 74 if(a[j][i]) qq[k--][i] = a[j][i]; 75 } 76 memset(a,0,sizeof(a)); 77 for(i=0,k=0;i<m;i++){ 78 for(j=0;j<n;j++) if(qq[j][i]!=0)break; 79 if(j==n)continue; 80 for(j=n-1;j>=0;j--) 81 a[j][k]=qq[j][i]; 82 k++; 83 } 84 } 85 void dfs(int now) 86 { 87 int i,j,val; 88 bool flag=false; 89 node t; 90 while(!Q.empty()){ 91 Q.pop(); 92 } 93 if(now>MAX) MAX = now; 94 memset(hash,false,sizeof(hash)); 95 for(i=0;i<n;i++){ 96 for(j=0;j<m;j++){ 97 if(!hash[i][j] && a[i][j]!=0) 98 { 99 val = bfs(i,j,a[i][j]); 100 if(val == 1) continue; 101 t.x=i; 102 t.y=j; 103 t.val=val*(val-1); 104 flag=true; 105 Q.push(t); 106 } 107 } 108 } 109 if(flag==false) return; 110 t=Q.top(); 111 change(t); 112 dfs(now+t.val); 113 } 114 int main() 115 { 116 int i,j; 117 while(scanf("%d%d",&n,&m)>0) 118 { 119 for(i=0;i<n;i++) 120 scanf("%s",tom[i]); 121 for(i=0;i<n;i++) 122 for(j=0;j<m;j++) 123 a[i][j]=tom[i][j]-‘0‘; 124 MAX=-1; 125 dfs(0); 126 printf("%d\n",MAX); 127 } 128 return 0; 129 }
原文:http://www.cnblogs.com/tom987690183/p/3672431.html