POJ1386+欧拉回路

View Code
 1 #include<cstdio>

 2 #include<vector>

 3 #include<iostream>

 4 #include<cstdlib>

 5 #include<cstring>

 6 using namespace std;

 7 int in[30],out[30],vis[30];

 8 int n;

 9 

10 vector<int> edge[27];

11 

12 void dfs(int s){

13     vis[s]=1;

14     for(int i=0;i<edge[s].size();i++)

15         if(vis[edge[s][i]]==0)

16             dfs(edge[s][i]);

17     return ;

18 }

19 

20 bool euler(int s){

21     int i;

22     memset(vis,0,sizeof(vis));

23     dfs(s);

24     for(i=0;i<26;i++){

25         if(vis[i]==0&&edge[i].size()!=0)

26             return false;

27     }

28     return true;

29 }

30 

31 int main(){

32     int t,n,i,j,len;

33     char str[1010];

34     scanf("%d",&t);

35     while(t--){

36         scanf("%d",&n);

37         memset(in,0,sizeof(in));

38         memset(out,0,sizeof(out));

39         for(i=0;i<26;i++)

40             edge[i].clear();

41         while(n--){

42             cin>>str;

43             len=strlen(str);

44             len--;

45             out[str[0]-'a']++;

46             in[str[len]-'a']++;

47             edge[str[0]-'a'].push_back(str[len]-'a');

48             edge[str[len]-'a'].push_back(str[0]-'a');

49         }

50 

51         //search the eulerian path

52         if(euler(str[0]-'a')==false){

53             cout<<"The door cannot be opened."<<endl;

54             continue;

55         }

56         int f1=0,f2=0;

57         for(i=0;i<26;i++){

58             if(in[i]!=out[i]){

59                 if(in[i]<out[i]){

60                     if(out[i]-in[i]==1&&f1==0)

61                         f1=1;

62                     else

63                         break;

64                 }

65                 if(out[i]<in[i]){

66                     if(in[i]-out[i]==1&&f2==0)

67                         f2=1;

68                     else

69                         break;

70                 }

71             }

72         }

73 

74         if(i==26)

75             cout<<"Ordering is possible."<<endl;

76         else

77             cout<<"The door cannot be opened."<<endl;

78     }

79     return 0;

80 }

你可能感兴趣的:(poj)