标签:nyoj38
1 4 6 1 2 10 2 3 10 3 1 10 1 4 1 2 4 1 3 4 1 1 3 5 6
4
#include <stdio.h> #include <string.h> #define maxn 502 #define maxm maxn * maxn #define inf 0x7fffffff int head[maxn], dist[maxn], id, ans; struct Node{ int to, c, next; } E[maxm]; bool vis[maxn]; void addEdge(int u, int v, int c) { E[id].to = v; E[id].c = c; E[id].next = head[u]; head[u] = id++; } void getMap(int n, int m) { int i, u, v, c; id = 0; memset(head, -1, sizeof(int) * (n + 1)); for(i = 0; i < m; ++i){ scanf("%d%d%d", &u, &v, &c); addEdge(u, v, c); addEdge(v, u, c); } scanf("%d", &ans); for(i = 1; i < n; ++i){ scanf("%d", &u); if(u < ans) ans = u; } } int getNext(int n) { int i, u = -1, tmp = inf; for(i = 1; i <= n; ++i) if(!vis[i] && dist[i] < tmp){ tmp = dist[i]; u = i; } return u; } int Prim(int n) { int i, u, v, len = 0, count = 0; for(i = 1; i <= n; ++i){ vis[i] = 0; dist[i] = inf; } u = 1; dist[u] = 0; while(count < n){ len += dist[u]; ++count; vis[u] = 1; for(i = head[u]; i != -1; i = E[i].next) if(E[i].c < dist[E[i].to]) dist[E[i].to] = E[i].c; u = getNext(n); } return len; } void solve(int n) //Prim { printf("%d\n", ans + Prim(n)); } int main() { int t, n, m; scanf("%d", &t); while(t--){ scanf("%d%d", &n, &m); getMap(n, m); solve(n); } return 0; }
标签:nyoj38
原文地址:http://blog.csdn.net/chang_mu/article/details/38797519