题目:http://acm.hdu.edu.cn/showproblem.php?pid=3371
ac:
#include <cstdio> #include <cstring> #include <iostream> using namespace std; const int INF = 0x3f3f3f3f; int map[550][550], dis[550], vis[550]; int n, m, K; void Prim() { int sum = 0; memset(vis, 0, sizeof(vis)); for(int i = 1; i <= n; i++) dis[i] = map[1][i]; vis[1] = 1; for(int i = 1; i < n; i++) { int min = INF, temp; for(int j = 1; j <= n; j++) { if(!vis[j] && dis[j] < min) { temp = j; min = dis[j]; } } vis[temp] = 1; if(min == INF){ printf("-1 "); return; } sum += min; for(int j = 1; j <=n; j++) { if(!vis[j] && dis[j] > map[temp][j]) dis[j] = map[temp][j]; } } printf("%d ",sum); } int main() { int T; scanf("%d", &T); while(T--) { scanf("%d %d %d", &n, &m, &K); for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) map[i][j]=(i==j?0:INF); int u, v, w; for(int k = 0; k < m; k++){ scanf("%d %d %d", &u, &v, &w); if(map[u][v] > w) map[u][v] = map[v][u] = w; } int a[110]; for(int Q = 0; Q < K; Q++) { int L; scanf("%d", &L); for(int i = 0; i < L; i++) scanf("%d", &a[i]); for(int b = 0; b < L; b++) for(int c = 0; c <= b; c++) map[a[b]][a[c]]=map[a[c]][a[b]]=0; } Prim(); } return 0; }
Kl 超时; 卡不过。
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; struct Rode { int a, b, Val; } num[25050]; int cmp(Rode a, Rode b) { return a.Val < b.Val; } int n, m, k; int father[550], Yh[550], cnt; void init() { for(int i = 1; i <= n; i++){ father[i] = i; Yh[i] = 0; } cnt = n - 1; } int find(int a) { int r, j, k; r = a; while(r != father[r]) r = father[r]; j = a; while(j != r) { k = father[j]; father[j] = r; j = k; } return r; } bool mercy(int a, int b) { if(a == -1) return false; int Q = find(a); int p = find(b); if(Q != p) { if(Yh[Q] < Yh[p]) { Yh[p] += Yh[Q]; father[Q] = p; } else { Yh[Q] += Yh[p]; father[p] = Q; } cnt--; // father[Q] = p; return true; } return false; } /* bool Judge() { int sum = 0; for(int i = 1; i <= n; i++) if(father[i] == i) sum++; if(sum == 1) return true; else return false; } */ int main() { int T; scanf("%d", &T); while(T--) { scanf("%d %d %d", &n, &m, &k); init(); for(int i = 0; i < m; i++) scanf("%d %d %d", &num[i].a, &num[i].b, &num[i].Val); int Q; for(int j = 0; j < k; j++) { scanf("%d", &Q); int pre = -1, Yes; for(int k = 0; k < Q; k++){ scanf("%d", &Yes); mercy(pre, Yes); pre = Yes; } } sort(num, num + m, cmp); int total = 0; for(int i = 0; i < n; i++) { if(mercy(num[i].a, num[i].b)) total += num[i].Val; } //if(Judge()) if(cnt == 0) printf("%d ", total); else printf("-1 "); } return 0; }