AOJ Minimum Spanning Tree (最小生成树)

链接:https://vjudge.net/problem/Aizu-ALDS1_12_A
思路:从第一个结点开始,搜索相邻结点,然后更新所有结点的最小距离,将所有结点重复上述过程即可得到最小生成树

参考链接:https://www.jianshu.com/p/e04a8bdaf7c9
https://www.jianshu.com/p/7eb040a78060

代码:
#include
using namespace std;

const int MAX = 100;
const int INFTY = (1<<21);

int n;
int distance1[MAX][MAX];

int MST(){

int d[MAX];
int color[MAX]; //white = 0,gray = 1,black = 2
int father[MAX];

int u,mins;
for(int i=0;i d[i] = INFTY;
color[i] = 0;
father[i] = -1;
}
d[0] = 0;

while(1){
mins = INFTY;
u = -1;
for(int i=0;i if(d[i] u = i;
mins = d[i];
}
}
if(u==-1)break;
color[u] = 2;
for(int j=0;j if(color[j]!=2&&distance1[u][j]!=INFTY){
if(distance1[u][j] d[j] = distance1[u][j];
color[j] = 1;
father[j] = u;
}
}
}
}
int sum = 0;
for(int i=0;i if(father[i]!=-1)
sum+=distance1[i][father[i]];
}
return sum;
}

int main(){
cin>>n;
for(int i=0;i for(int j=0;j int e;
cin>>e;
distance1[i][j] = (e==-1)?INFTY:e;
}
}
cout< return 0;
}

再次书写的版本:
#include
using namespace std;

const int MAX = 100;
const int INFTY = (1<<21);

int n;
int distance1[MAX][MAX];

int MST(){
int d[MAX];
int color[MAX];//white = 0,gray = 1,black = 2
int father[MAX];
int u,mins;
for(int i=0;i d[i] = INFTY;
color[i] = 0;
father[i] = -1;
}
d[0] = 0;

while(1){
mins = INFTY;
u = -1;
for(int i=0;i if(d[i] u = i;
mins = d[i];
}
}
if(u==-1)break;//搜索完成后退出
color[u] = 2;
for(int j=0;j if(color[j]!=2&&distance1[u][j]!=INFTY){
if(distance1[u][j] d[j] = distance1[u][j];
color[j] = 1;
father[j] = u;
}
}
}
}
int sum = 0;
for(int i=0;i if(father[i]!=-1)
sum+=distance1[i][father[i]];
}
return sum;
}

int main(){
cin>>n;
for(int i=0;i for(int j=0;j int e;
cin>>e;
distance1[i][j] = (e==-1)?INFTY:e;
}
}
cout< return 0;
}

你可能感兴趣的:(AOJ Minimum Spanning Tree (最小生成树))