您的位置:首页 > 其它

ZOJ 3332 Strange Country II dfs

2012-03-31 21:05 169 查看
题意:

有n个点,每两个点之间只有一条有向路线,共 n*(n-1)/2条路径,可以从任意一点出发,问能否每个点走一遍,把所有的点走完

本来还以为直接dfs会超时 居然过了,这个。。。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>///???
#include<string>
#include<cmath>
#include<math.h>
using namespace std;
int map[102][102];
int road[102];
int n,cnt;
bool vs[102];
bool dfs(int x)
{
if(cnt==n)
{
return 1;
}

int i;
for(i=1;i<=n;i++)
{
if(!vs[i]&&map[x][i])
{
vs[i]=1;
road[++cnt]=i;
if(dfs(i))return 1;
cnt--;
vs[i]=0;
}
}

return 0;
}
int main()
{
int CASE,N,i;
int a,b;
scanf("%d",&CASE);
while(CASE--)
{
memset(map,0,sizeof(map));
memset(vs,0,sizeof(vs)) ;
scanf("%d",&n);
N=n*(n-1)/2;
for(i=1;i<=N;i++)
{
scanf("%d%d",&a,&b);
map[a][b]=1;
}
bool fg=0;
for(i=1;i<=n;i++)
{
cnt=1;
road[1]=i;
vs[i]=1;
if(dfs(i))
{
fg=1;
break;
}
vs[i]=0;
}

if(fg)
{
for(i=1;i<n;i++)
printf("%d ",road[i]);
printf("%d\n",road[i]);
}
else
{
printf("Impossible\n");
}

}
return 0;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: