POJ 1318

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 char a[101][7],s[7];
 5 int compare(const void *p,const void *q)
 6 {
 7     return (*(char *)p - *(char *)q);
 8 }
 9 int check(char p[7],char q[7]);
10 int main()
11 {
12     char c[7];
13     int i,j,flag,n;
14     i = 0;
15     while(scanf("%s",&a[i]) && strcmp(a[i],"XXXXXX")){
16         i++;
17     }
18     n = i;
19     for(i = 0;i < n-1;i++){
20         for(j = i;j < n;j++){
21             if(strcmp(a[i],a[j]) > 0){
22                 strcpy(c,a[i]);
23                 strcpy(a[i],a[j]);
24                 strcpy(a[j],c);
25             }
26         }
27     }
28     while(scanf("%s",s) && strcmp(s,"XXXXXX")){
29         flag = 1;
30         for(j = 0;j < n;j++){
31             if(check(s,a[j])){
32                 flag = 0;
33                 printf("%s\n",a[j]);
34             }
35         }
36         if(flag){
37             printf("NOT A VALID WORD\n");
38         }
39         printf("******\n");
40     }
41     system("pause");
42     return 0;
43 }
44 int check(char p[7],char q[7])
45 {
46     char c[7];
47     int len1,len2;
48     int i;
49     len1 = strlen(p);
50     len2 = strlen(q);
51     if(len1 != len2)
52     return 0;
53     strcpy(c,q);
54     qsort(c,len2,sizeof(char),compare);
55     qsort(p,len1,sizeof(char),compare);
56     for(i = 0;i < len1;i++){
57         if(c[i] != p[i]){
58            return 0;
59         }
60     } 
61     return 1;
62 }
63 我在做1318时遇到过一个问题,当对字典字符串排序时不能用qsort,因为它只对各个字符串首字母进行排序,比如:输入Sample Input 中的tarp,trap,用aptr查时结果却是trap在前面。但是如果是用C++则可直接调用sort对字典进行排序。没办法,只有自己编了,19~27行,用了一般的排序方法,两个for循环,时间达到了O(n^2),但是竟然是0MS,AC。我想可能是因为题目把字典字符串数限制在100以内吧,数量不大。

posted on 2009-04-22 22:36 Johnnx 阅读(299) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2009年4月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

统计

常用链接

留言簿(1)

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜