POJ 1258 Agri-Net

Prim模板

C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <queue>
#include <vector>
#define MAX 101

using namespace std;

int arr[MAX][MAX];
bool vis[MAX];
int num;

struct node{
int num;
int v;
bool operator<(const node &b) const{
return v > b.v;
}
};

int prim(int start){
int ans = 0;
priority_queue<node> q;
memset(vis, false, sizeof(vis));
node tmp;
tmp.num = start;
tmp.v = 0;
q.push(tmp);
for(int k = 0; k < num; k++){
node cur;
do{
cur = q.top();
q.pop();
}while(vis[cur.num]);
vis[cur.num] = true;
ans += cur.v;
for(int i = 0; i < num; i++){
if(!vis[i] && arr[cur.num][i] > 0){
node tmp;
tmp.num = i;
tmp.v = arr[cur.num][i];
q.push(tmp);
}
}
}
return ans;
}

int main(){
while(~scanf("%d", &num)){
for(int i = 0; i < num; i++){
for(int j = 0; j < num; j++){
scanf("%d", &arr[i][j]);
}
}
int ans = prim(0);
printf("%d\n", ans);
}
return 0;
}