http://lightoj.com/volume_showproblem.php?problem=1059最小產生樹變形

來源:互聯網
上載者:User

利用kruscal求最小產生樹,如果建一條路的費用超過建一個機場,就去掉該邊(這點很關鍵);

#include<cstdio>#include<string.h>#include<algorithm>using namespace std;const __int64 N=10002;const int INF=9999999999;struct node{ __int64 u,v; __int64 cost;}a[N*10];__int64 fa[N],con[N],n,m,cs;bool vis[N];void init(){ memset(vis,false,sizeof(vis)); for(__int64 i=0;i<N;i++) {       fa[i]=i;           }}bool cmp(node a,node b){return a.cost<b.cost;}int find(int x){ return x==fa[x]?x:fa[x]=find(fa[x]);}int main(){ /*freopen("1.txt","r",stdin);freopen("2.txt","w",stdout); */ int t;scanf("%d",&t);for(int i=1;i<=t;i++){init(); printf("Case %d: ",i); scanf("%d%d%d",&n,&m,&cs); for(int j=1;j<=m;j++) { scanf("%d%d%lld",&a[j].u,&a[j].v,&a[j].cost);  } sort(a+1,a+m+1,cmp); __int64 Con=0,cnt=0,res=0; for(int j=1;j<=m;j++) {  int xx=find(a[j].u),yy=find(a[j].v);  if(xx!=yy&&a[j].cost<cs)   {          fa[xx]=yy;    Con+=a[j].cost;  cnt++;    } } if(cnt==n-1) {   printf("%lld 1\n",Con+cs); } else{//printf("n=%d\n",n);   printf("%lld ",(Con+(n-cnt)*cs));   printf("%lld\n",n-cnt); }}  return 0;}/* 5 3 100 1 2 3 2 4 1 3 5 2 */

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.