- 總時間限制:
- 10000ms
- 單個測試點時間限制:
- 1000ms
- 內存限制:
- 65536kB
- 描述
要求對一個圖使用kruskal算法求最小生成樹,依次輸出選出的邊所關聯的頂點序列,要求下標較小者在前,如圖所示,其頂點序列爲1 3 4 6 2 5 3 6 2 3
- 輸入
- 若干行整數
第一行爲兩個整數,分別爲圖的頂點數和邊數
第二行開始是該圖的鄰接矩陣,主對角線統一用0表示,無直接路徑的兩點用100來表示(保證各邊權值小於100) - 輸出
- 若干用空格隔開的整數
- 樣例輸入
6 10 0 6 1 5 100 100 6 0 5 100 3 100 1 5 0 5 6 4 5 100 5 0 100 2 100 3 6 100 0 6 100 100 4 2 6 0
- 樣例輸出
1 3 4 6 2 5 3 6 2 3
個人覺得prim算法比較好操作,kruskal算法理解了,但是,判斷有沒回環不知道砸門判斷,所以就用prim算法做了
#include <iostream>
#include "cstring"
#include <stdio.h>
#include "iomanip"
#include "vector"
#include "cmath"
#include "stack"
#include "algorithm"
#include <math.h>
#include "map"
#include "queue"
#include "set"
using namespace std;
const int INF=1<<30;
struct edge{
int start,end;
int w ;
edge(){}
edge(int a,int b,int c){start=a;end=b;w=c;}
bool operator <(const edge&bb)const{
return w>bb.w;
}
};
int main()
{
freopen("a.txt","r",stdin);
int n,v;
cin>>n>>v;
int Map[111][111]={0};
int visit[111]={0};
priority_queue <edge> q;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
int a;
cin>>a;
Map[i][j]=a;
}
visit[1]=1;
for(int k=0;k<n-1;k++)
{
int mini=INF;
int end=0,start=0;
for(int i=1;i<=n;i++)
{
if(visit[i]==1)
{
for(int j=1;j<=n;j++)
{
if(Map[i][j]!=0&&Map[i][j]!=100)
if(mini>Map[i][j]&&visit[j]==0)
{
mini=Map[i][j];
end=j;
start=i;
}
}
}
}
visit[end]=1;
q.push(edge(start,end,mini));
}
while (!q.empty())
{
edge t=q.top();
q.pop();
int a=t.start;
int b=t.end;
int a1=max(a,b);
int b1=min(a,b);
cout<<b1<<" "<<a1<<" ";
}
return 0;
}
///////////////////////////kruskal算法實現
#include <iostream>
#include "cstring"
#include <stdio.h>
#include "iomanip"
#include "vector"
#include "cmath"
#include "stack"
#include "algorithm"
#include <math.h>
#include "map"
#include "queue"
#include "set"
using namespace std;
const int INF=1<<30;
struct edge{
int start,end;
int w ;
edge(){}
edge(int a,int b,int c){start=min(a,b);end=max(a,b);w=c;}
bool operator <(const edge&bb)const{
return w>bb.w;
}
};
int f[1111]={0};
int r[1111]={0};
int find(int a)
{
if(a==f[a])
return a;
return f[a]=find(f[a]);
}
bool abc(int a,int b)
{
int x=find(a);
int y=find(b);
if(x==y)
return false;
if(r[x]>=r[y])
{
f[y]=x;
r[x]++;
}
else
{
f[x]=y;
r[y]++;
}
return true;
}
int main()
{
freopen("a.txt","r",stdin);
int n,v;
cin>>n>>v;
int visit[111]={0};
priority_queue <edge> q;
vector <edge> res;
for(int i=1;i<=n;i++)
{
f[i]=i;
for(int j=1;j<=n;j++)
{
int a;
cin>>a;
if(a!=0&&a!=100)
{
q.push(edge(i,j,a));
}
}
}
while(res.size()!=n-1)
{
edge t=q.top();
q.pop();
int start=t.start;
int end=t.end;
if(abc(start,end))
{
res.push_back(t);
}
}
for(int i=0;i<n-1;i++)
cout<<res[i].start<<" "<<res[i].end<<" ";
return 0;
}