UVA - 10600 ACM Contest and Blackout
2017-05-05 22:42
267 查看
单纯的次小生成树
这里是先建最小生成树,然后依次不用最小生成树的某一条边再建最小生成树,得到的最小值就是次小生成树。
这个写法比较简单易懂,但是时间会消耗的比较多。
还有一种方式是建完最小生成树之后删一条边,这样就会得到两棵子树,然后找一条能够连接两棵树的边加进来就可以了。我在UVA - 1504里运用到了这种做法的变种,不过这道题用的是上面那个写法。
这里是先建最小生成树,然后依次不用最小生成树的某一条边再建最小生成树,得到的最小值就是次小生成树。
这个写法比较简单易懂,但是时间会消耗的比较多。
还有一种方式是建完最小生成树之后删一条边,这样就会得到两棵子树,然后找一条能够连接两棵树的边加进来就可以了。我在UVA - 1504里运用到了这种做法的变种,不过这道题用的是上面那个写法。
#include<iostream> #include<string> #include<cstdio> #include<set> #include<stack> #include<list> #include<vector> #include<queue> #include<algorithm> #include<cstring> #include<cmath> #include<fstream> using namespace std; typedef long long ll; const int maxn = 110,maxe = maxn * maxn / 2; int fa[maxn],n,m; struct node{ int u,v,w; bool operator < (const node &a) const { return w < a.w; } }; vector<node> e; vector<int> kru; int find(int x){ if (x == fa[x]) return x; return fa[x] = find(fa[x]); } int kruskal(int p){ int num = 1,ans = 0; for(int i = 1;i <= n;++i) fa[i] = i; for(int k = 0;k < m;++k){ if (k == p) continue; int x = e[k].u,y = e[k].v,w = e[k].w; x = find(x),y = find(y); if (x != y){ if (p == -1) kru.push_back(k); fa[x] = y; num++; ans += w; } if (num == n) return ans; } return -1; } void init(){ cin >> n >> m; int a,b,p; e.clear(); for(int i = 0;i < m;++i){ cin >> a >> b >> p; e.push_back({a,b,p}); } sort(e.begin(),e.end()); kru.clear(); int ans = kruskal(-1); cout << ans << ' '; int mi = 0x3f3f3f3f; for(int i = 0;i < kru.size();++i){ int t = kruskal(kru[i]); if (~t) mi = min(mi,kruskal(kru[i])); } cout << mi << endl; } int main(){ int t; cin >> t; while(t--) init(); }
相关文章推荐
- UVA 10600 ACM Contest and Blackout (次小生成树)
- UVA10600-ACM Contest and Blackout
- ACM Contest and Blackout UVA - 10600 (次小生成树)
- UVa10600 ACM Contest and Blackout
- UVa 10600 ACM contest and Blackout( 次小生成树)
- UVa:10600 ACM Contest and Blackout
- uva10600 - ACM Contest and Blackout 次小生成树
- UVA 10600 ACM Contest and Blackout(次小生成树)
- UVA 10600 ACM Contest and Blackout(最小生成树and次小生成树)
- UVA10600 ACM Contest and Blackout (次小生成树)
- uva 10600 - ACM Contest and Blackout(次小生成树)
- UVA-10600 ACM Contest and Blackout (次小生成树)
- UVA 10600 ACM Contest and Blackout
- UVA 10600 ACM Contest and Blackout (次小生成树)
- UVA 10600 - ACM Contest and Blackout 次小生成树
- UVA - 10600 ACM Contest and Blackout(次小生成树)
- (beginer) 最小生成树 UVA 10600 ACM Contest and Blackout
- UVA 10600 - ACM Contest and Blackout (次小生成树)
- UVa 10600 - ACM Contest and Blackout(最小生成树)
- UVA 10600 - ACM Contest and Blackout 次小生成树