版权声明:https://blog.csdn.net/huashuimu2003 https://blog.csdn.net/huashuimu2003/article/details/85769611
题目
http://acm.hdu.edu.cn/showproblem.php?pid=3414
代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=1e3;
inline int read()
{
int f=1,num=0;
char ch=getchar();
while (!isdigit(ch)) { if (ch=='-') f=-1; ch=getchar(); }
while (isdigit(ch)) num=(num<<1)+(num<<3)+(ch^48), ch=getchar();
return num*f;
}
int n,Next[maxn+3],a[maxn+3][maxn+3];
bool eprepend(int s)
{
memset(Next,-1,sizeof(Next));
int head=s, tail=s;
for (int i=0;i<n;++i)
{
if (i==s) continue;
if (a[i][head])//直接插入
{
Next[i]=head;
head=i;
}
else//找到合适的位置插入
{
int pre=head,pos=Next[head];
while (pos!=-1 && a[pos][i])
{
pre=pos;
pos=Next[pos];
}
Next[pre]=i;
Next[i]=pos;
if (pos==-1)
tail=i;
}
}
if (a[tail][head])
{
Next[tail]=head;
return true;
}
return false;
}
bool Hamilton()
{
for (int i=0;i<n;++i)
if (eprepend(i))
return true;
return false;
}
int main()
{
while (~(n=read()),n)
{
for (int i=0;i<n;++i)
for (int j=0;j<n;++j)
a[i][j]=read();
if (n==1)
puts("1");
else if (n==2 || !Hamilton())
puts("-1");
else
{
for (int i=0,j=0;i<n;++i,j=Next[j])
printf("%d%c",j+1,i==n-1?'\n':' ');
}
}
return 0;
}