ZOJ 3332 Strange Country II dfs

题意:

有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;
}

  

posted @ 2012-03-31 21:05  快乐.  阅读(209)  评论(0编辑  收藏  举报