Give a group of words to determine whether words can be sorted so that the first letter of each word is the same as the last letter of the previous word.
Input:
The first row of each test data is an integer N (1 <=n <= 10000), followed by N rows, each row is a word, each word contains only lowercase letters and a maximum of 100 characters.
Output:
If the word sequence cannot be reorganized to meet the requirements, an "Impossible" line is output; otherwise, "Possible" is output ".
Input example:
2
OK
OK
2
OK
Ko
Output example:
Impossible
Possible
1 # include <stdio. h>
2 # include <stdlib. h>
3 # include <string. h>
4
5 // return the last character of a word.
6 char endOfString (char s [])
7 {
8 int I;
9
10 for (I = 0; s [I + 1]! = '\ 0'; I ++)
11;
12
13 return s [I];
14}
15
16 // returns the first character of a word
17 char firstOfWord (char s [])
18 {
19 return s [0];
20}
21
22 // print all words
23/* void print (char temp [] [100], int N)
24 {
25 int I;
26 for (I = 0; I <N; I ++)
27 printf ("% s \ n", temp [I]);
28 }*/
29
30 // check whether splicing is allowed. If yes, 1 is returned; otherwise, 0 is returned.
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 = firstOfWord (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 [I], "") = 0)
46 continue;
47 else if (firstOfWord (temp [I]) = end)
48 {
49 end = endOfString (temp [I]);
50 strcpy (temp [I], "");
51 count ++;
52 count_N ++;
53}
54 else if (endOfString (temp [I]) = head)
55 {
56 head = firstOfWord (temp [I]);
57 count ++;
58 strcpy (temp [I], "");
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 [I]);
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", firstOfWord (word [0]);
100
101 return 0;
102}
From zhengmian