1531:John‘s Trip
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 379 通过数: 241
【题目描述】
来自 CERC 1995
John 有很多朋友住在不同的街,John 想去访问每位朋友,同时希望走的路最少。因为道路很窄,John 在一条路上不能往回走。John 希望从家里出发,拜访完所有的朋友后回到自己的家,且总的路程最短。John 意识到如果可以每条道路都只走一次然后返回起点应该是最短的路径。写一个程序帮助 John 找到这样的路径。给出的每条街连接两个路口。街分别编号为 1 到 n,路口分别编号为 1 到 m。
【输入】
多组数据。
每组数据有多行,每行由三个整数组成:x,y,z。z 为这条街的编号,x 和 y 表示这条街连接的两个路口的编号。可能有自环。
对于每组数据,John 住在第一行中连接的两个顶点中编号较小的路口处。所有的街都可以连通到其他街上。0表示一组数据的结束。
再一个0表示输入的结束。
【输出】
如果能找到所有街道遍历一次的回路,输出找到的路径,两个整数之间用一个空格隔开,行末无空格。如果不存在,输出"Round trip does not exist."。
【输入样例】
1 2 1
2 3 2
3 1 6
1 2 5
2 3 3
3 1 4
0 0
1 2 1
2 3 2
1 3 3
2 4 4
0 0
0 0
【输出样例】
1 2 3 5 4 6
Round trip does not exist.
【提示】
数据范围与提示:
最多有 1995 条街,最多 44 个路口。
思路:已知无向图连通,求最小字典序顺序,dfs.
#include <bits/stdc++.h>
using namespace std;
const int N=50;
int du[N],x,y,z,vis[2000],n,m;
struct edge
{
int u,v;
}a[2000];
void dfs(int x)
{
for(int i=1;i<=n;i++)//边的编号
{
if(!vis[i]&&(a[i].u==x||a[i].v==x))
{
vis[i]=1;
m++;
printf("%d%c",i,m==n?'\n':' ');
dfs(a[i].u+a[i].v-x);
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while(cin >> x >> y,x)
{
memset(du,0,sizeof(du));
memset(vis,0,sizeof(vis));
cin >> z;
int s=min(x,y),ma=0;
n=0;
a[z].u=x;//无向图
a[z].v=y;
du[x]++,du[y]++;
n++;
ma=max(ma,max(x,y));
while(cin >> x >> y,x)
{
cin >> z;
a[z].u=x;//无向图
a[z].v=y;
du[x]++,du[y]++;
n++;
ma=max(ma,max(x,y));
}
int f=0;
for(int i=1;i<=ma;i++)
{
if(du[i]&1)
{
f=1;
break;
}
}
if(f)
{
printf("Round trip does not exist.\n");
continue;
}
m=0;
dfs(s);
}
return 0;
}