题目描述
根据输入创建无向网。分别用Prim算法和Kruskal算法构建最小生成树。(假设:输入数据的最小生成树唯一。)
输入
顶点数n
n个顶点
边数m
m条边信息,格式为:顶点1顶点2权值
Prim算法的起点v
输出
输出最小生成树的权值之和
对两种算法,按树的生长顺序,输出边信息(Kruskal中边顶点按数组序号升序输出)
样例查看模式
正常显示
查看格式
输入样例1 <-复制
6
v1 v2 v3 v4 v5 v6
10
v1 v2 6
v1 v3 1
v1 v4 5
v2 v3 5
v2 v5 3
v3 v4 5
v3 v5 6
v3 v6 4
v4 v6 2
v5 v6 6
v1
输出样例1
15
prim:
v1 v3 1
v3 v6 4
v6 v4 2
v3 v2 5
v2 v5 3
kruskal:
v1 v3 1
v4 v6 2
v2 v5 3
v3 v6 4
v2 v3 5
#include <iostream>
#include <deque>
#include <string>
#include <algorithm>
using namespace std;
int n;deque<string>d;int e;string ks;int kks;int arr[100][100];
int main(){
cin>>n;
for (int i = 0; i < n; ++i) {cin>>ks;d.emplace_back(ks);}
cin>>e;int ee=e;
while (ee--){
string a,b;int w;cin>>a>>b>>w;
auto ait= find(d.begin(),d.end(),a);
auto bit= find(d.begin(),d.end(),b);
int l=ait-d.begin();int r=bit-d.begin();
arr[l][r]=w;arr[r][l]=w;
}cin>>ks;auto kit= find(d.begin(),d.end(),ks);
kks=kit-d.begin();int v[100]={0};v[kks]=1;
deque<string>out;int c=0;
int nn=n;nn--;
while (nn--){
int min=99;int i=0;int j=0;
for (int ii = 0; ii < n; ++ii) {
if(v[ii]==0)continue;
for (int jj = 0; jj < n; ++jj) {
if(v[jj]==1)continue;
if(min>arr[ii][jj]&&arr[ii][jj]!=0){
min=arr[ii][jj];i=ii;j=jj;
}
}
}c+=min;v[j]=1;
out.emplace_back(d[i]+" "+d[j]+" "+to_string(min));
}
cout<<c<<endl<<"prim:"<<endl;
for(auto it=out.begin();it!=out.end();++it)cout<<*it<<endl;
cout<<"kruskal:"<<endl;int xt[100][100]={0};
while (e--){
int min=99;int i=0;int j=0;
for (int ii = 0; ii < n; ++ii) {
for (int jj = 0; jj < n; ++jj) {
if(min>arr[ii][jj]&&arr[ii][jj]!=0){
min=arr[ii][jj];i=ii;j=jj;
}
}
}arr[i][j]=0;arr[j][i]=0;xt[i][j]=min;xt[j][i]=min;
int xtt[100][100]={0}; int t=100;
for (int k = 0; k < n; ++k) {
for (int l = 0; l < n; ++l) {
xtt[k][l]=xt[k][l];
}
}
while (t--){
for (int iii = 0; iii < n; ++iii) {int cc=0;
for (int jjj = 0; jjj < n; ++jjj) {
if(xtt[iii][jjj]!=0)cc++;
}if(cc<=1){
for (int kk = 0; kk < n; ++kk) {
xtt[kk][iii]=0;xtt[iii][kk]=0;
}
}
}
}
int f=0;
for (int k = 0; k < n; ++k) {
for (int l = 0; l < n; ++l) {
f+=xtt[k][l];
}
}if(f!=0){
xt[i][j]=0;xt[j][i]=0;
} else
cout<<d[i]<<" "<<d[j]<<" "<<min<<endl;
}
}