字符串头尾连接问题-木棒连接

问题 D: 木棒连接

时间限制: 1 Sec  内存限制: 64 MB
提交: 996  解决: 51
[提交][状态][讨论版]

题目描述

有一堆木棒,用一串字母表示,如果两个木棒的的首尾字母相同,则可以连接在一起,比如“abc”和“cde”可以连接成“abccde”。现给出一堆这样的木棒,请你判断一下他们是否可以连接在一起成为一跟木棒。

输入

第一行为T,表示有T组数据。每组数据的第一行为N,表示有N(1 <= N <= 100000)根木棒. 接下来N行数据,表示N根木棒。每根木棒不超过1000个小写字母。

输出

如果可以连接成一根木棒,则输出“YES”,否则输出“NO”。

样例输入

3
2
acm
ibm
3
acm
malform
mouse
2
ok
ok

样例输出

NO
YES
NO
 
解题思路:
晚上被这题卡死,
写不来
还没搞清楚为什么这个代码是对的
 1 #include<stdio.h>
 2 #include<string.h>
 3 typedef struct stick {
 4     char c;
 5     int n;
 6 } stick;
 7 int main()
 8 {
 9     int n,i,j,m;
10     int len;
11     int index;
12     char result[50][4];
13     scanf("%d",&n);//输入组数n
14     i = 0;
15     while(i < n)
16     {
17         char buf[50][20]= {0};//木棒数组
18         int in_count = 0;
19         int out_count = 0;
20         stick in[50] = {0,0};
21         stick out[50] = {0,0};
22         scanf("%d",&m);//输入当前组数木棒数
23         for(j = 0; j < m; j++)
24         {
25             scanf("%s",buf[j]);//输入木棒
26         }
27         in[0].c = buf[0][0];
28         in[0].n = 1;
29         len = strlen(buf[0]);
30         out[0].c = buf[0][len-1];
31         out[0].n = 1;
32         for(j = 1; j < m; j++)
33         {
34             in[j].c = buf[j][0];
35             in[j].n = 1;
36             len = strlen(buf[j]);
37             out[j].c = buf[j][len-1];
38             out[j].n = 1;
39             for(index = 0; index < j ; index++)
40             {
41                 if(out[index].n == 1 && out[index].c == in[j].c)
42                 {
43                     out[index].n = 2;
44                     in[j].n = 2;
45                 }
46                 if(in[index].n == 1 && in[index].c == out[j].c)
47                 {
48                     in[index].n = 2;
49                     out[j].n = 2;
50                 }
51             }
52         }
53         for(j = 0; j < m; j++)
54         {
55             if(in[j].n == 1)
56             {
57                 in_count++;
58             }
59             if(out[j].n == 1)
60             {
61                 out_count++;
62             }
63         }
64         if(in_count > 1 || out_count > 1)
65         {
66             printf("NO\n");
67         }
68         else
69         {
70             printf("YES\n");
71         }
72         i++;
73     }
74     return 0;
75 }
 
posted @ 2013-12-12 00:12  Jeremy Wu  阅读(529)  评论(0编辑  收藏  举报