Untitled77.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
#define maxx 9999
using namespace std;
int n;//城市总数量
int l[maxx][maxx];//标记两两城市之间的距离
int go_city;//初始出发的城市
int visited[maxx];//标记是否已经走过,visited[i]=1为走过,=0为未走过
int min_l = 0;//最小总路程
int greedy(int index)
{
cout << "路线为:" << endl;
cout << index << " --> ";
//已经确定从第go_city号城市出发,所以只需要在确定n-1个城市
for(int i=1;i<n;i++)
{
int len = maxx;
int j_j;
for(int j=1;j<=n;j++)
{
if(visited[j] != 0)
{
continue;
}
//筛选与当前城市距离最短的城市,并标记
if(len > l[index][j])
{
len = l[index][j];
j_j = j;
}
}
index = j_j;
cout << index << " --> ";
//标记j_j号城市已走过。
visited[j_j] = 1;
min_l += len;
}
//加上最后一个城市到go_city城市的距离
min_l += l[index][go_city];
cout << go_city << endl;
return 0;
}
int main()
{
memset(visited,0,sizeof(visited));
cout << "请输入城市数量:";
cin >> n;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
printf("请输入%d号城市到%d号城市之间的距离:",i,j);
cin >> l[i][j];
l[j][i] = l[i][j];
}
}
cout << "请输入您出发的城市是第几个城市:";
cin >> go_city;
visited[go_city] = 1;
greedy(go_city);
cout << "最短路程长度为: ";
cout << min_l << endl;
return 0;
}