Time Limit: 20000/10000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 881 Accepted Submission(s): 207
Special Judge
Problem Description
The city is so crowded that the mayor can't bear any longer. He issued an order to change all the roads into one-way street. The news is terrible for Jack, who is the director of a tourism company, because he has to change the travel route. All tourists want to set out from one scenic spot, then go to every scenic spots once and only once and finally return to the starting spot. They don’t care about which spot to start from, but they won’t go back to the starting spot before they have visited all other spots. Fortunately, the roads in the city have been perfectly built and any two scenic spots have been connected by ONE road directly. Jack gives the map of the city to you, and your task is to arrange a new travel route around the city which can satisfy the tourists.
Input
Input consists of multiple test cases and ends with a line of “0”.
For each test case:
The first line contains a single integer n (0
Output
For each test case, print all the spots No. according to the traveling order of the route in one line. If multiple routes exist, just print one of them. If no such route exists, print a “-1” instead. Because the starting spot is the same as the ending spot, so you don’t need to print the ending spot.
This problem needs special judge.
Sample Input
5 0 0 1 1 1 1 0 1 1 0 0 0 0 1 0 0 0 0 0 1 0 1 1 0 0 2 0 1 0 0 0
Sample Output
1 3 4 5 2 -1
Source
2010 National Programming Invitational Contest Host by ZSTU
题意:
某个城市有N个景点,某一天来了一批游客想参观这些景点,他们的要求是这些景点都要去且每个景点仅去一次.特殊的是,对于任意两个景点,路都是单向的.即要么能从A景点到B景点,要么可以从B景点到A景点,不存在双向或者不连通的情况.让你找到一个回路,从某个景点出发,经过全部景点一次且仅一次,最后又能回到起点.
思路:
很显然是让在竞赛图中寻找哈密顿回路,但是由于竞赛图一定存在哈密顿路径,但不一定存在哈密顿回路,所以需要枚举所有起点,构造一个哈密顿路径,然后判断起点和终点是否连通就可以了.
#include
#include
const int MAXN = 1005;
int mp[MAXN][MAXN],ans[MAXN];
void Hamilton(int ans[MAXN], int mp[MAXN][MAXN], int n, int st) {
int nxt[MAXN];
memset(nxt, -1, sizeof(nxt));
int head = st;
for(int i = 1; i <= n; i++) {
if(i == st)continue;
if(mp[i][head]) {
nxt[i] = head;
head = i;
}else {
int pre = head, pos = nxt[head];
while(pos != -1 && !mp[i][pos]) {
pre = pos;
pos = nxt[pre];
}
nxt[pre] = i;
nxt[i] = pos;
}
}
int cnt = 0;
for(int i = head; i != -1; i = nxt[i]) ans[++cnt] = i;
}
int main(void)
{
int n;
while(scanf("%d",&n) != EOF && n) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
scanf("%d",&mp[i][j]);
}
}
if(n == 1){ printf("1\n");continue; }
int flag = 0;
for(int i = 1; i <= n; i++) {
Hamilton(ans, mp, n,i);
if(mp[ans[n]][ans[1]]) {
flag = 1;
for(int k = 1; k <= n; k++) {
if(k == 1) printf("%d",ans[k]);
else printf(" %d",ans[k]);
}
printf("\n");
break;
}
}
if(!flag) printf("-1\n");
}
return 0;
}