Prim 算法, hdu 1102 Constructing Roads

/* * m.cpp * * Created on: 2010-5-3 * Author: Administrator */ #include //#include #include #include #include #include #include #include #include using namespace std; typedef pair vetex; int prim(int map[][101], int n) { int max = 0; int visit[101], distance[101]; for (int i = 0; i < 101; i++) { visit[i] = false; distance[i] = 2000; } distance[1] = 0; priority_queue, greater > q; q.push(vetex(0, 1)); while (!q.empty()) { int u = q.top().second; visit[u] = true; q.pop(); for (int i = 1; i <= n; i++) { if (!visit[i] && map[u][i] < distance[i]) { distance[i] = map[u][i]; q.push(vetex(map[u][i], i)); } } } for (int i = 1; i <= n; i++) { max += distance[i]; } return max; } int main() { //freopen("in.txt", "r", stdin); int n; int map[101][101]; while (scanf("%d", &n) != EOF) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { scanf("%d", &map[i][j]); } } int t; int a, b; scanf("%d", &t); for (int i = 0; i < t; i++) { scanf("%d %d", &a, &b); map[a][b] = 0; map[b][a] = 0; } cout<

 

使用结构体的priority_queue

/* * m.cpp * * Created on: 2010-5-3 * Author: Administrator */ #include #include #include #include #include #include using namespace std; struct node { int distance; int visitp; //最小生成树,已经访问过的点 int nextp; //最小生成树外面,与树连接且未访问过的点 //保存两点之间已经访问过的点, 和未访问过的点, 以及两点距离。 friend bool operator>(const node & a, const node & b) { return a.distance > b.distance; } friend bool operator<(const node & a, const node & b) { return a.distance < b.distance; } node(const int &a, const int &b, const int &c) { distance = a; visitp = b; nextp = c; } }; int prim(int map[][101], int n) { int max = 0; int visit[101]; for (int i = 0; i < 101; i++) { visit[i] = false; } priority_queue, greater > q; q.push(node(0, 1, 1)); while (!q.empty()) { int u = q.top().nextp; if (!visit[u]) { max += map[q.top().visitp][u]; visit[u] = true; } q.pop(); for (int i = 1; i <= n; i++) { if (!visit[i]) { q.push(node(map[u][i], u, i)); } } } return max; } int main() { //freopen("in.txt", "r", stdin); int n; int map[101][101]; while (scanf("%d", &n) != EOF) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { scanf("%d", &map[i][j]); } } int t; int a, b; scanf("%d", &t); for (int i = 0; i < t; i++) { scanf("%d %d", &a, &b); map[a][b] = 0; map[b][a] = 0; } cout<

你可能感兴趣的:(Prim,算法,distance,2010,c)