1. 程式人生 > >HDU 5253 Prim算法

HDU 5253 Prim算法

using hdu padding sta 優先 space code med 新的

http://acm.hdu.edu.cn/showproblem.php?pid=5253

Prim算法是

1.每次選出 (已經選出的)點集 能夠連接 邊權值最小的點

2.使用新找出的點能帶來的新的更小的邊權,來更新舊的較大的邊權

3.重復,直到連接所有點

的貪心算法

使用優先權隊列優化 查找 邊權值最小的點 的步驟。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <queue>
#include 
<algorithm> using namespace std; typedef long long LL; typedef pair<int,int> P; int cnt; int t,n,m; int mp[1005][1005]; bool vis[1005][1005]; int dirx[] = {0,1,0,-1}; int diry[] = {1,0,-1,0}; LL bfs() { priority_queue<P, vector<P>, greater<P> > pq; while(!pq.empty()) pq.pop(); memset(vis,
0, sizeof(vis)); pq.push(P(0, 0)); LL cost = 0; int cnt = 0; while(!pq.empty()) { P p = pq.top(); pq.pop(); int val = p.first, id = p.second; int x = id/m, y = id%m; if(vis[x][y]) continue; vis[x][y] = 1; cost += val; for(int
i = 0; i < 4; i++) { int nx = x + dirx[i], ny = y + diry[i]; if(nx < 0 || ny < 0 || nx >= n || ny >= m || vis[nx][ny]) continue; int nval = abs(mp[x][y] - mp[nx][ny]), nid = nx*m+ny; pq.push(P(nval, nid)); } cnt++; if(cnt >= m*n) break; } return cost; } int main() { scanf("%d", &t); while(t--) { scanf("%d%d", &n,&m); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { scanf("%d", &mp[i][j]); } } static int kase = 0; printf("Case #%d:\n%lld\n", ++kase, bfs()); } return 0; }

HDU 5253 Prim算法