MST
Time Limit: 2000/1000MS (Java/Others) Memory Limit: 128000/64000KB (Java/Others)
SubmitStatus
Problem Description
Given a connected, undirected graph, a spanning tree of that graph is a subgraph that is a tree and connects all the vertices together. A single graph can have many different spanning trees. We can also assign a weight to each edge, which is a number representing
how unfavorable it is, and use this to assign a weight to a spanning tree by computing the sum of the weights of the edges in that spanning tree. A minimum spanning tree (MST) is then a spanning tree with weight less than or equal to the weight of every other
spanning tree.
------ From wikipedia
Now we make the problem more complex. We assign each edge two kinds of weight: length and cost. We call a spanning tree with sum of length less than or equal to others MST. And we want to find a MST who has minimal sum of cost.
Input
There are multiple test cases.
The first line contains two integers N and M indicating the number of vertices and edges in the gragh.
The next M lines, each line contains three integers a, b, l and c indicating there are an edge with l length and c cost between a and b.
1 <= N <= 10,000
1 <= M <= 100,000
1 <= a, b <= N
1 <= l, c <= 10,000
Output
For each test case output two integers indicating the sum of length and cost of corresponding MST.
If you can find the corresponding MST, please output "-1 -1".
Sample Input
4 5
1 2 1 1
2 3 1 1
3 4 1 1
1 3 1 2
2 4 1 3
Sample Output
3 3
题意比较坑人,可以存在不连通的图。
这是一个稀疏图,故用kruskal算法!!!
AC代码如下:
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #define inf 100000000 using namespace std; int f[10005]; struct H{ int l,r,d,c; }w[100005]; int find (int a) { return f[a]==a? a : f[a]=find(f[a]); } bool cmp(H a, H b) { return a.d<b.d||(a.d==b.d&&a.c<b.c);//主要注意这个条件的判断就可以了 } int main() { int n,m; int i,j; int a,b,c,d; int ans; while(cin>>n>>m) { memset(w,0,sizeof w); for(i=1;i<=n;i++) f[i]=i; for(i=1;i<=m;i++) { cin>>a>>b>>c>>d; w[i].l=a; w[i].r=b; w[i].d=c; w[i].c=d; } int ans=0,cost=0,bj=0; sort(w+1,w+m+1,cmp); for(i=1;i<=m;i++) { int xx,yy; xx=find(w[i].l); yy=find(w[i].r); if(xx!=yy) { bj++; ans+=w[i].d; cost+=w[i].c; f[xx]=yy; } } if(bj==n-1) printf("%d %d\n",ans,cost); else printf("-1 -1\n"); } return 0; }
ACdream原创群赛(16) F