标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 222 Accepted Submission(s): 75
1 #include<bits/stdc++.h> 2 const int M = 1e3 + 10 , inf = 0x3f3f3f3f ; 3 int move[][2] = {{1,0} , {0,1} , {-1,0} , {0,-1}} ; 4 struct node 5 { 6 int id , dis ; 7 bool operator < (const node &rhs) const { 8 return rhs.dis < dis ; 9 } 10 } ; 11 std::priority_queue <node> q ; 12 int d[M * M] ; 13 int mp[M][M] ; 14 int n , m , T ; 15 16 void init () 17 { 18 for (int i = 0 ; i < M * M ; i ++) { 19 d[i] = inf ; 20 } 21 } 22 23 void prim () 24 { 25 while (!q.empty ()) q.pop () ; 26 for (int i = 0 ; i < 4 ; i ++) { 27 int x = move[i][0] , y = move[i][1] ; 28 if (x >= n || y >= m || x < 0 || y < 0) continue ; 29 int dis = fabs (mp[0][0] - mp[x][y]) ; 30 q.push ( (node) {x * m + y , dis} ) ; 31 d[x * m + y] = dis ; 32 } 33 d[0] = -1 ; 34 int sum = 0 ; 35 while (!q.empty ()) { 36 node ans = q.top () ; 37 int id = ans.id , dis = ans.dis ; 38 q.pop () ; 39 if (~ d[id] == 0) continue ; 40 d[id] = -1 ; 41 sum += dis ; 42 for (int i = 0 ; i < 4 ; i ++) { 43 int sx = id / m , sy = id % m ; 44 int x = sx + move[i][0] , y = sy + move[i][1] ; 45 if (x >= n || y >= m || x < 0 || y < 0) continue ; 46 int _id = x * m + y , _dis = fabs (mp[sx][sy] - mp[x][y]) ; 47 if ( ~d[_id] && d[_id] > _dis) { 48 d[_id] = _dis ; 49 q.push ((node) {_id , _dis}) ; 50 } 51 } 52 // for (int i = 0 ; i < n * m ; i ++) printf ("%d , " , d[i]) ; puts ("") ; 53 } 54 printf ("%d\n" , sum) ; 55 } 56 57 int main () 58 { 59 //freopen ("a.txt" , "r" , stdin ) ; 60 scanf ("%d" , &T) ; 61 int cas = 1 ; 62 while (T --) { 63 init () ; 64 printf ("Case #%d:\n" , cas ++) ; 65 scanf ("%d%d" , &n , &m) ; 66 for (int i = 0 ; i < n ; i ++) { 67 for (int j = 0 ; j < m ; j ++) { 68 scanf ("%d" , &mp[i][j]) ; 69 } 70 } 71 prim () ; 72 } 73 return 0 ; 74 }
2015baidu复赛2 连接的管道(mst && 优先队列prim)
标签:
原文地址:http://www.cnblogs.com/get-an-AC-everyday/p/4542777.html