Description
There is a travel agency in Adelton town on Zanzibar island. It has decided to offer its clients, besides many other attractions, sightseeing the town. To earn as much as possible from this attraction, the agency has accepted a shrewd decision: it is necessary to find the shortest route which begins and ends at the same place. Your task is to write a program which finds such a route.
In the town there are N crossing points numbered from 1 to N and M two-way roads numbered from 1 to M. Two crossing points can be connected by multiple roads, but no road connects a crossing point with itself. Each sightseeing route is a sequence of road numbers y_1, …, y_k, k>2. The road y_i (1<=i<=k-1) connects crossing points x_i and x_{i+1}, the road y_k connects crossing points x_k and x_1. All the numbers x_1,…,x_k should be different.The length of the sightseeing route is the sum of the lengths of all roads on the sightseeing route, i.e. L(y_1)+L(y_2)+…+L(y_k) where L(y_i) is the length of the road y_i (1<=i<=k). Your program has to find such a sightseeing route, the length of which is minimal, or to specify that it is not possible,because there is no sightseeing route in the town.
【题目分析】
求最小环,递归的去处理一个问题,统计环时,按照floyd的思想,每次都加入当前编号最大的点,然后要求选这个点就可以了。
【代码】
#include<cstdio>
#include<cstring>
int map[1005][1005];
int dis[1005][1005];
int pre[1005][1005];
int ans[1005];
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
map[i][j]=0x7ffffff;
dis[i][j]=0x7ffffff;
pre[i][j]=i;
}
}
for(int i=0;i<m;i++)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
x--;y--;
if(map[x][y]>w)
{
map[x][y]=map[y][x]=w;
dis[x][y]=dis[y][x]=w;
}
}
int cont=0;
int minn=0x7ffffff;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
for(int k=j+1;k<n;k++)
{
if(dis[j][k]+map[k][i]+map[i][j]<minn)
{
minn=dis[j][k]+map[k][i]+map[i][j];
cont=0;
ans[cont++]=i;
ans[cont++]=j;
int s=k,e=j;
while(1)
{
if(pre[s][e]==s)break;
ans[cont++]=pre[s][e];
e=pre[s][e];
}
ans[cont++]=k;
}
}
}
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
if(dis[j][k]>dis[j][i]+dis[i][k])
{
dis[j][k]=dis[j][i]+dis[i][k];
pre[j][k]=pre[i][k];
}
}
}
}
if(minn==0x7ffffff)
{
printf("No solution.\n");
}
for(int i=0;i<cont;i++)
{
if(i==0)printf("%d",ans[i]+1);
else
printf(" %d",ans[i]+1);
}
printf("\n");
}
}
本文介绍了一种通过编程解决旅行代理机构寻找最短观光路线的问题。该问题要求找到连接城镇中若干交叉点并最终返回起点的最短路径。文章提供了一个使用C++实现的具体算法示例,采用类似于Floyd算法的方法逐步构建最短环路。
251

被折叠的 条评论
为什么被折叠?



