首页 > 代码库 > ACdream原创群赛(16) F
ACdream原创群赛(16) F
MST
Time Limit: 2000/1000MS (Java/Others) Memory Limit: 128000/64000KB (Java/Others)
SubmitStatus
Problem DescriptionGiven 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。