1 #include<cstdio> 2 #include<queue> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 using namespace std; 7 8 int G[1005][1005]; 9 int vis[1005][1005]; 10 int d[4][2]={1,0,0,1,-1,0,0,-1}; 11 int m,n; 12 const int inf=0x3f3f3f3f; 13 14 int cal(int x1,int y1,int x2,int y2) 15 { 16 return abs(G[x1][y1]-G[x2][y2]); 17 }; 18 19 struct lowercost 20 { 21 int x,y; 22 int cost; 23 bool operator < (const lowercost &temp)const 24 { 25 return cost>temp.cost; 26 } 27 }; 28 29 void init() 30 { 31 memset(vis,0,sizeof(vis)); 32 } 33 34 int prim() 35 { 36 priority_queue<lowercost>q; 37 lowercost t1,t2; 38 int sum=0,i,cnt; 39 t1.x=t1.y=t1.cost=0; 40 q.push(t1); 41 cnt=0; 42 while(!q.empty()) 43 { 44 t1=q.top(); 45 q.pop(); 46 if(vis[t1.x][t1.y]) 47 continue; 48 vis[t1.x][t1.y]=1; 49 sum+=t1.cost; 50 for(i=0;i<4;i++) 51 { 52 t2.x=t1.x+d[i][0]; 53 t2.y=t1.y+d[i][1]; 54 t2.cost=cal(t1.x,t1.y,t2.x,t2.y); 55 if(t2.x>=0&&t2.x<m&&t2.y>=0&&t2.y<n&&!vis[t2.x][t2.y]) 56 q.push(t2); 57 } 58 } 59 return sum; 60 } 61 62 int main() 63 { 64 int t,i; 65 scanf("%d",&t); 66 for(i=1;i<=t;i++) 67 { 68 init(); 69 scanf("%d%d",&m,&n); 70 for(int i=0;i<m;i++) 71 for(int j=0;j<n;j++) 72 scanf("%d",&G[i][j]); 73 int ans=prim(); 74 printf("Case #%d:\n",i); 75 printf("%d\n",ans); 76 } 77 return 0; 78 }
原文:http://www.cnblogs.com/homura/p/4735737.html