题目地址
题意:给出一个n阶的竞赛图,找出一个哈密顿回路,如果有输出路径,否则输出-1。
思路:按照竞赛图的性质竞赛图一定是存在哈密顿路径的,所以我们遍历每个点为起点的哈密顿路径,再判断是不是首尾相连,如果是直接输出路径就好了。
补充:
- 1、竞赛图:就是一个把所有的边从有向边转化为无向边,之后这个图是完全图。
- 2、哈密顿路径:通过图中的每一个节点一次并且仅一次的路径。
- 3、哈密顿回路:通过图中的每一个节点一次并且仅一次,最后回到起点的路径。
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <cstdio>
#include <algorithm>
#define LL long long
#define N 1010
#define M 200010
#define inf 0x3f3f3f3f
using namespace std;
const LL mod = 998244353;
const double eps = 1e-9;
int mapp[N][N], nex[N], n;
bool check(int s) {
memset(nex, -1, sizeof(nex));
int head = s, tail = s;
for (int i = 1; i <= n; i++) {
if (i == s) continue;
if (mapp[i][head]) {
nex[i] = head;
head = i;
}
else {
int x = head, y = nex[head];
while (y != -1 && mapp[y][i]) {
x = y;
y = nex[y];
}
nex[x] = i;
nex[i] = y;
if(y == -1)
tail = i;
}
}
if (mapp[tail][head]) {
nex[tail] = head;
return true;
}
return false;
}
bool solve() {
for (int i = 1; i <= n; i++) {//每个点找哈密尔顿回路
if (check(i)) return true;
}
return false;
}
int main(){
cin.sync_with_stdio(false);
while (cin >> n) {
if (n == 0) break;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> mapp[i][j];
}
}
if (n == 1) {
cout << "1" << endl;
}
else if (n == 2 || !solve()) {
cout << -1 << endl;
}
else {
cout << 1;
for (int i = 1, j = nex[1]; i < n; i++, j = nex[j]) {
cout << " " << j;
}
cout << endl;
}
}
return 0;
}