给出一组单词,判断是否可以将单词排序,使得每个单词的第一个字母和前一个单词的最后一个字母相同。
输入:
每个测试数据的第一行为整数N(1<=N<=10000),接下来的N 行,每行为一个单词,每个单词都只包含小写字母并且最多包含100 个字符。
输出:
如果不能将单词序列重组以满足要求,则输出一行”Impossible”,否则输出”Possible”。
输入样例:
2
ok
ok
2
ok
ko
输出样例:
Impossible
Possible
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 //返回单词最后一个字符。
6 char endOfString(char s[])
7 {
8 int i;
9
10 for(i=0; s[i+1]!='\0'; i++)
11 ;
12
13 return s;
14 }
15
16 //返回单词第一个字符
17 char firstOf
word(char s[])
18 {
19 return s[0];
20 }
21
22 //打印所有的单词
23 /*void print(char temp[][100],int N)
24 {
25 int i;
26 for(i=0; i<N; i++)
27 printf("%s\n",temp);
28 }*/
29
30 //查看是不是可以拼接,可则返回1,否则返回0
31 int check(char temp[][100],int N)
32 {
33 int i,j,count=0,flag_pos=1,count_N=1;
34 char head,end;
35
36 head = firstOf
word(temp[0]);
37 end = endOfString(temp[0]);
38 strcpy(temp[0],"");
39
40 for(j=1; j<N; j++)
41 {
42 count=0;
43 for(i=1; i<N; i++)
44 {
45 if(strcmp(temp,"")==0)
46 continue;
47 else if(firstOf
word(temp)==end)
48 {
49 end = endOfString(temp);
50 strcpy(temp,"");
51 count ++;
52 count_N++;
53 }
54 else if(endOfString(temp)==head)
55 {
56 head = firstOf
word(temp);
57 count++;
58 strcpy(temp,"");
59 count_N++;
60 }
61 else
62 continue;
63 }
64
65 if(count==0)
66 {
67 flag_pos=0;
68 break;
69 }
70
71 if(count_N==N)
72 break;
73
74 }
75 return flag_pos;
76 }
77
78 int main()
79 {
80 int N,flag_pos,i;
81 char
word[1000][100];
82
83 //printf("please input;\n");
84 scanf("%d",;N);
85 for(i=0; i<N; i++)
86 {
87 scanf("%s",
word);
88 }
89
90 flag_pos = check(
word,N);
91 if(flag_pos==0)
92 printf("Impossible\n");
93 else
94 printf("Possible\n");
95
96 //print(
word,N);
97 //printf("%s\n",
word[0]);
98 //printf("The end of the
word is %c\n",endOfString(
word[0]));
99 //printf("The first of the
word is %c\n",firstOf
word(
word[0]));
100
101 return 0;
102 }