http://acm.timus.ru/problem.aspx?space=1&num=1416
最小生成树 和次小生成树
代码:
#include<iostream> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #include<vector> #include<set> #include<map> #include<string> #include<queue> #include<stack> #include <iomanip> using namespace std; #define LL long long const int INF=0x3f3f3f3f; //priority_queue<int,vector<int>,greater<int> >qt; const int N=505; int f[N]; int a[N][N]; vector<int>tree[N]; vector<int>value[N]; struct node { int l,r; int k; bool used; }side[N*N]; bool cmp(node x,node y) { return x.k<y.k; } int findx(int x) { if(f[x]!=x) f[x]=findx(f[x]); return f[x]; } int Kruskal(int n,int m) { sort(side,side+m,cmp); for(int i=1;i<=n;++i) {tree[i].clear();value[i].clear();} for(int i=1;i<=n;++i) f[i]=i; int sum=0; for(int i=0;i<m;++i) { int l=side[i].l; int r=side[i].r; if(findx(l)!=findx(r)) { side[i].used=true; sum+=side[i].k; f[findx(l)]=findx(r); tree[l].push_back(r); tree[r].push_back(l); value[l].push_back(side[i].k); value[r].push_back(side[i].k); } } return sum; } void dfs(int s,int x,int pre,int k) { a[s][x]=k; for(unsigned int i=0;i<tree[x].size();++i) { if(tree[x][i]==pre) continue; dfs(s,tree[x][i],x,max(k,value[x][i])); } } int Ctree(int n,int m,int MIN) { for(int i=1;i<=n;++i) dfs(i,i,-1,0); int sum=-1; for(int i=0;i<m;++i) { int l=side[i].l; int r=side[i].r; if(side[i].used==false) { if(sum==-1) sum=MIN-a[l][r]+side[i].k; else sum=min(sum,MIN-a[l][r]+side[i].k); } } return sum; } int main() { //freopen("data.in","r",stdin); int n,m; while(cin>>n>>m) { for(int i=0;i<m;++i) { cin>>side[i].l>>side[i].r>>side[i].k; side[i].used=false; } int MIN=Kruskal(n,m); int CMIN=Ctree(n,m,MIN); cout<<"Cost: "<<MIN<<endl; cout<<"Cost: "<<CMIN<<endl; } return 0; }