标签:style blog http color os io 2014 art
题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1416
题目大意:给一个n个点m条边的无向图,求最小生成树和次小生成树(图无重边,似乎是连通图)。
思路:参考2014年汪汀的IOI集训队论文《最小生成树问题的拓展》。时间复杂度为O(n^2)。
代码(0.109MS):
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 #include <iostream> 5 using namespace std; 6 7 const int MAXV = 510; 8 const int MAXE = MAXV * MAXV; 9 const int INF = 0x3f3f3f3f; 10 11 int head[MAXV], ecnt; 12 int to[MAXE], next[MAXE], cost[MAXE]; 13 bool select[MAXE]; 14 int n, m; 15 16 void init() { 17 memset(head + 1, -1, n * sizeof(int)); 18 ecnt = 0; 19 } 20 21 void add_edge(int u, int v, int c) { 22 to[ecnt] = v; cost[ecnt] = c; next[ecnt] = head[u]; head[u] = ecnt++; 23 to[ecnt] = u; cost[ecnt] = c; next[ecnt] = head[v]; head[v] = ecnt++; 24 } 25 26 int dis[MAXV], pre[MAXV]; 27 int maxPath[MAXV][MAXV]; 28 bool vis[MAXV]; 29 30 int prim() { 31 memset(dis + 1, 0x3f, n * sizeof(int)); 32 dis[1] = 0; 33 int res = 0; 34 for(int _ = 0; _ < n; ++_) { 35 int u = -1; 36 for(int i = 1; i <= n; ++i) if(!vis[i] && dis[i] < INF) 37 if(u == -1 || dis[i] < dis[u]) u = i; 38 if(u == -1) return -1; 39 for(int p = head[u]; ~p; p = next[p]) { 40 int &v = to[p]; 41 if(vis[v]) continue; 42 if(cost[p] < dis[v]) dis[v] = cost[p], pre[v] = p; 43 } 44 for(int i = 1; i <= n; ++i) if(vis[i]) { 45 int &v = to[pre[u] ^ 1]; 46 maxPath[i][u] = maxPath[u][i] = max(maxPath[i][v], dis[u]); 47 } 48 res += dis[u]; 49 vis[u] = true; 50 if(u != 1) select[pre[u]] = select[pre[u] ^ 1] = true; 51 } 52 return res; 53 } 54 55 int solve(int ans) { 56 int res = -1; 57 for(int u = 1; u <= n; ++u) { 58 for(int p = head[u]; ~p; p = next[p]) { 59 int &v = to[p]; 60 if(select[p] || u == v) continue; 61 if(res == -1 || ans - maxPath[u][v] + cost[p] < res) 62 res = ans - maxPath[u][v] + cost[p]; 63 } 64 } 65 return res; 66 } 67 68 int main() { 69 scanf("%d%d", &n, &m); 70 init(); 71 for(int i = 0, a, b, c; i < m; ++i) { 72 scanf("%d%d%d", &a, &b, &c); 73 add_edge(a, b, c); 74 } 75 int ans1 = prim(), ans2 = -1; 76 if(ans1 != -1) ans2 = solve(ans1); 77 printf("Cost: %d\n", ans1); 78 printf("Cost: %d\n", ans2); 79 }
URAL 1416 Confidential(次小生成树),布布扣,bubuko.com
标签:style blog http color os io 2014 art
原文地址:http://www.cnblogs.com/oyking/p/3865646.html