您的位置:首页 > 大数据 > 人工智能

Uva 11733 - Airports 最小生成森林..Kruskal

2013-11-13 21:17 351 查看
题意:

有N个小镇(N<=10000)...现在可以修建M条无向道路(M<=100000)...并且修建每条路有各自的费用..现在要设立飞机场..要求每个小镇都可以到达至少一个飞机场..并且建设飞机场的费用是A...那么要满足条件最少需要多少费用?...在这个最少费用下..飞机场最多可以建设几个...

题解:

上来就无脑的直接分连通图然后Kruskal搞一遍..样例和谐..交上去WA了..仔细一想是因为有些边的代价会超过建设飞机场的代价.. 所以不如不要这条边..就算多加一个飞机场都划得来些..这个判断在输出的时候就可以做掉了..当一条边的长度不小于建设飞机场的费用..这条边就不在咱考虑的范围了...然后做Kruskal求出最小生成森林就可以了...

关于求最小生成森林..也就是说要要每个联通块都保持联通性..并且总花费最小..很显然和解决最小生成树是一回事...

Program:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<set>
#include <stack>
#include<queue>
#include<algorithm>
#include<cmath>
#define eps 1e-4
#define oo 1000000007
#define MAXN 10005
#define MAXM 100005<<1
#define ll long long
#define pi acos(-1.0) 
using namespace std;   
struct node
{
      int u,v,l,next;
}edge[MAXM]; 
int Ne,_next[MAXN],father[MAXN]; 
void addedge(int u,int v,int l)
{
      edge[++Ne].next=_next[u],_next[u]=Ne;
      edge[Ne].u=u,edge[Ne].v=v,edge[Ne].l=l;
}
int getfather(int x)
{
      if (father[x]==x) return x;
      return father[x]=getfather(father[x]);
}
bool cmp(node a,node b)
{
      return a.l<b.l;
}
int Kruskal(int n,int m)
{
      int u,v,l,x,ans=0;
      sort(edge+1,edge+1+m,cmp);
      for (u=1;u<=n;u++) father[u]=u;
      for (x=1;x<=m;x++)
      {
              u=edge[x].u,v=edge[x].v,l=edge[x].l;
              if (getfather(u)==getfather(v)) continue;
              ans+=l;
              father[father[u]]=father[v];
      }
      return ans;
}
int main()
{       
      int C,cases,N,M,A,u,v,l,ans,num;     
      scanf("%d",&C);
      for (cases=1;cases<=C;cases++)
      {
               scanf("%d%d%d",&N,&M,&A);
               Ne=0,memset(_next,0,sizeof(_next));
               while (M--)
               {
                        scanf("%d%d%d",&u,&v,&l);
                        if (l>=A) continue;
                        addedge(u,v,l),addedge(v,u,l); 
               }
               ans=Kruskal(N,Ne);
               num=0;
               for (u=1;u<=N;u++)
                  if (father[u]==u) num++;
               printf("Case #%d: %d %d\n",cases,ans+num*A,num);               
      }
      return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: