标签:school turn can style push names eof 算法 dir
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; }
标签:school turn can style push names eof 算法 dir
原文地址:http://www.cnblogs.com/Alruddy/p/7295995.html