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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

POJ 2421 Constructing Roads MST kruskal

發布時間:2023/12/1 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 POJ 2421 Constructing Roads MST kruskal 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近剛學的并查集所以用kruskal來試試最小生成樹~

kruskal其實用幾句話就能說完~?

1.貪心所有邊的權值,從小到大取值

2.取值時~將邊權非0的兩個頂點~進行并查操作~如果兩個點的祖先不同...邊權加入最小生成樹...并且將兩個點納入同一個集合中

3.判斷是否所有點都在同一個集合中

完畢~

下面上代碼~這個代碼應該可以作為模版了...但是并查集沒有優化~所以復雜度約為0(n^3)但是比prim好一點

32ms水過...

mian()前的代碼修改一下可以作為kruskal的模版...我再寫一篇專門放模版吧~


#include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <cctype> #include <cstdio> #include <string> #include <vector> #include <cassert> #include <cstdlib> #include <cstring> #include <sstream> #include <iostream> #include <algorithm> using namespace std; const int V = 101; int father[V],map[V][V]; struct point {int s,v,rank; }p[V*V]; int cmp(point a, point b) { return a.rank<b.rank; } int find(int x) {if(x!=father[x])father[x]=find(father[x]);return father[x]; } void Union(int a,int b) {int x = find(a);int y = find(b);if(x==y) return ;father[y]=x; } bool found(int n) {int x=find(0);for(int i=0;i<n;i++)if(find(i)!=x)return false;return true; } int kruskal(int map[][V],int n) {int i,j,cnt,mst=0;for(i=0,cnt=0;i<n;i++){father[i]=i;for(j=0;j<n;j++){p[cnt].s=i;p[cnt].v=j;p[cnt].rank = map[i][j];cnt++;}}sort(p,p+n*n,cmp);for(i=0;i<n*n;i++){if(p[i].rank!=0 && p[i].rank!=-1){if(find(p[i].s)!=find(p[i].v))mst+=p[i].rank;Union(p[i].s,p[i].v);if(found(n)==true)return mst;}else if(p[i].rank==-1){Union(p[i].s,p[i].v);if(found(n)==true)return mst;}} } int main() { // freopen("in.txt","r",stdin);int n;scanf("%d",&n);int m,i,j,p,q,cnt=0;memset(map,0,sizeof(map));for(i=0;i<n;i++)for(j=0;j<n;j++)scanf("%d",&map[i][j]);cin>>m;while(m--){cin>>p>>q;map[p-1][q-1]=-1;}cout<<kruskal(map,n)<<endl; return 0; }

轉載于:https://www.cnblogs.com/Felix-F/archive/2012/08/10/3223657.html

總結

以上是生活随笔為你收集整理的POJ 2421 Constructing Roads MST kruskal的全部內容,希望文章能夠幫你解決所遇到的問題。

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