思路
最小生成树模板题。
(Prim)。
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 2e2 + 10;
struct node {
int next ,to ,val;
}edge[MAXN * MAXN];
int head[MAXN] ,cnt = 0;
void add (int from ,int to ,int val) {
edge[++ cnt].next = head[from];
head[from] = cnt;
edge[cnt].to = to;
edge[cnt].val = val;
}
int n;
int dis[MAXN] ,vis[MAXN];
int prim (int cur) {
int ans = 0;
memset (dis ,0x3f ,sizeof (dis));
memset (vis ,0 ,sizeof (vis));
dis[cur] = 0;
vis[cur] = 1;
for (int q = head[cur];~ q;q = edge[q].next) {
dis[edge[q].to] = edge[q].val;
}
for (int q = 1;q < n;++ q) {
int minl = 0x3f3f3f3f ,ind;
for (int w = 1;w <= n;++ w) {
if (minl > dis[w] && ! vis[w]) {
minl = dis[w];
ind = w;
}
}
ans += dis[ind];
vis[ind] = 1;
for (int q = head[ind];~ q;q = edge[q].next) {
int v = edge[q].to;
if (! vis[v])
dis[v] = min (dis[v] ,edge[q].val);
}
}
return ans;
}
int main () {
memset (head ,-1 ,sizeof (head));
scanf ("%d",&n);
int x;
for (int q = 1;q <= n;++ q) {
for (int w = 1;w <= n;++ w) {
scanf ("%d",&x);
if (x != 0) add (q ,w ,x) ,add (w ,q ,x);
}
}
printf ("%d
",prim (1));
return 0;
}