Prim算法
来源:互联网 发布:新浪微博没有mac版 编辑:程序博客网 时间:2024/05/29 14:30
1003 电话连线
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 黄金 Gold
题目描述 Description
一个国家有n个城市。若干个城市之间有电话线连接,现在要增加m条电话线(电话线当然是双向的了),使得任意两个城市之间都直接或间接经过其他城市有电话线连接,你的程序应该能够找出最小费用及其一种连接方案。
输入描述 Input Description
输入文件的第一行是n的值(n<=100).
第二行至第n+1行是一个n*n的矩阵,第i行第j列的数如果为0表示城市i与城市j有电话线连接,否则为这两个城市之间的连接费用(范围不超过10000)。
输出描述 Output Description
输出文件的第一行为你连接的电话线总数m,第二行至第m+1行为你连接的每条电话线,格式为i j,(i<j), i j是电话线连接的两个城市。输出请按照Prim算法发现每一条边的顺序输出,起始点为1.
第m+2行是连接这些电话线的总费用。
样例输入 Sample Input
5
0 15 27 6 0
15 0 33 19 11
27 33 0 0 17
6 19 0 0 9
0 11 17 9 0
样例输出 Sample Output
2
1 4
2 5
17
数据范围及提示 Data Size & Hint
n<=100
分类标签 Tags 点此展开
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int n,p[109][109];
int sum=0,temp=0;
struct N
{
int a,b;
} q[109];
void Prim()
{
int Lowcost[109],mst[109],d,vis[109];
memset(vis,0,sizeof(vis));
for (int i=2; i<=n; i++)
{
Lowcost[i]=p[1][i];
mst[i]=1;
}
Lowcost[1]=0;
vis[1]=1;
for (int i=0;i<n;i++)
{
int Min=99999999,c=0,d;
for (int i=1; i<=n; i++) //找到最小边
{
if (vis[i]==1)
{
c++;
continue;
}
if (Min>Lowcost[i])
{
Min=Lowcost[i];
d=i;
}
}
if (c==n) break;
sum+=Min;
vis[d]=1;
if (Min)
{
q[temp].a=min(d,mst[d]);
q[temp].b=max(d,mst[d]);
temp++;
}
for (int i=2; i<=n; i++)
{
if (!vis[i]&&Lowcost[i]>p[i][d])
{
Lowcost[i]=p[i][d];
mst[i]=d;
}
}
}
}
int main()
{
cin>>n;
//输入数据
for (int i=1; i<=n; i++)
{
for (int j=1; j<=n; j++)
{
cin>>p[i][j];
}
}
//Prim算法实现
Prim();
//sort(q,q+temp,So);
cout<<temp<<endl;
for (int i=0; i<temp; i++)
{
cout<<q[i].a<<' '<<q[i].b<<endl;
}
cout<<sum<<endl;
return 0;
}
#include <cstring>
#include <algorithm>
using namespace std;
int n,p[109][109];
int sum=0,temp=0;
struct N
{
int a,b;
} q[109];
void Prim()
{
int Lowcost[109],mst[109],d,vis[109];
memset(vis,0,sizeof(vis));
for (int i=2; i<=n; i++)
{
Lowcost[i]=p[1][i];
mst[i]=1;
}
Lowcost[1]=0;
vis[1]=1;
for (int i=0;i<n;i++)
{
int Min=99999999,c=0,d;
for (int i=1; i<=n; i++) //找到最小边
{
if (vis[i]==1)
{
c++;
continue;
}
if (Min>Lowcost[i])
{
Min=Lowcost[i];
d=i;
}
}
if (c==n) break;
sum+=Min;
vis[d]=1;
if (Min)
{
q[temp].a=min(d,mst[d]);
q[temp].b=max(d,mst[d]);
temp++;
}
for (int i=2; i<=n; i++)
{
if (!vis[i]&&Lowcost[i]>p[i][d])
{
Lowcost[i]=p[i][d];
mst[i]=d;
}
}
}
}
int main()
{
cin>>n;
//输入数据
for (int i=1; i<=n; i++)
{
for (int j=1; j<=n; j++)
{
cin>>p[i][j];
}
}
//Prim算法实现
Prim();
//sort(q,q+temp,So);
cout<<temp<<endl;
for (int i=0; i<temp; i++)
{
cout<<q[i].a<<' '<<q[i].b<<endl;
}
cout<<sum<<endl;
return 0;
}
阅读全文
0 0
- prim 算法
- Prim算法
- Prim算法
- prim算法
- Prim算法
- Prim算法。
- Prim 算法
- Prim算法
- prim算法
- Prim算法
- Prim算法
- Prim算法
- prim算法
- prim算法
- Prim算法
- Prim算法
- prim算法
- prim算法
- 阴影贴图1
- 【C++】<string> 与<string.h>、<cstring>的区别
- 面试感悟:3年工作经验java程序员应有的技能
- vb.net 教程 8-2 简单的SQL语言8
- HCL 模拟器安装注意
- Prim算法
- AXI总线简介
- 阴影贴图2
- 深度学习6:softmax线性分类器与神经网络分类的性能比较
- bootstrap基础
- 使用Dropwizard(2)-配置分类ConfiguredBundle
- 3d图
- 匿名内部类
- 部署Django项目到Apache服务器(下)