日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Slim Span UVA - 1395

發布時間:2025/3/21 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Slim Span UVA - 1395 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題意:尋找滿足條件的最小生成樹,條件是生成樹中最長邊與最短邊的差越小越好。

題解:將邊進行排序后,枚舉第一條邊,然后不斷更新答案就行了。

1 #define INF 1e8 2 #include<cstdio> 3 #include<cstring> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 8 const int maxn=10005; 9 10 struct edge{ 11 int u,v,cost; 12 bool operator<(const edge& i)const{ 13 return cost<i.cost; 14 } 15 }es[maxn]; 16 17 int n,m,cnt; 18 int F[105]; 19 20 void Init(){ 21 for(int i=1;i<=n;i++) F[i]=i; 22 cnt=1; 23 } 24 25 int Find(int a){ 26 if(a!=F[a]) F[a]=Find(F[a]); 27 return F[a]; 28 } 29 30 bool unite(int a,int b){ 31 int x=Find(a),y=Find(b); 32 if(x==y) return false; 33 else { F[x]=y; return true; } 34 } 35 36 int Kruskal(){ 37 sort(es,es+m); 38 int ans=INF; 39 for(int i=0;i<m;i++){ 40 Init(); 41 unite(es[i].u,es[i].v); 42 for(int j=i+1;j<m;j++){ 43 if(unite(es[j].u,es[j].v)){ 44 cnt++; 45 if(cnt==n-1) ans=min(ans,es[j].cost-es[i].cost); 46 } 47 } 48 } 49 return ans; 50 } 51 52 int main() 53 { while(~scanf("%d%d",&n,&m)){ 54 if(n==0&&m==0) break; 55 for(int i=0;i<m;i++) scanf("%d%d%d",&es[i].u,&es[i].v,&es[i].cost); 56 int ans=Kruskal(); 57 if(m==0||(n>2&&m==1)) cout<<"-1"<<endl; 58 else if(n==2&&m==1) cout<<"0"<<endl; 59 else if(ans==INF) cout<<"-1"<<endl; 60 else cout<<ans<<endl; 61 } 62 return 0; 63 }

?

轉載于:https://www.cnblogs.com/zgglj-com/p/7351368.html

總結

以上是生活随笔為你收集整理的Slim Span UVA - 1395的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。