zoj 3432 Find the Lost Sock(解决时间超时问题)

来源:互联网 发布:linux新建文件命令 编辑:程序博客网 时间:2024/04/30 14:18

此题我不会,总是超时,在别处看到代码,如下:

转自/http://hi.baidu.com/chenyy197/item/81b6a8fa920626673c14853e

一:题目描述:

Alice bought a lot of pairs of socks yesterday. But when she went home, she found that she has lost one of them. Each sock has a name which contains exactly 7 charaters.


Alice wants to know which sock she has lost. Maybe you can help her.

Input

There are multiple cases. The first line containing an integer n (1 <= n <= 1000000) indicates that Alice bought n pairs of socks. For the following 2*n-1 lines, each line is a string with 7 charaters indicating the name of the socks that Alice took back.

Output

The name of the lost sock.

Sample Input

2aabcdefbzyxwvubzyxwvu4aqwertyeas fghaqwertyeasdfgheasdfghaqwertyaqwerty20x0abcd0ABCDEF0x0abcd

Sample Output

aabcdefeas fgh0ABCDEF

Hint

Because of HUGE input, scanf is recommended.

二:引用代码实现如下://我添加注释

#include<stdio.h>
int main()
{
    int n,i,j;
    char str[8],str1[8];
    while(scanf("%d",&n)!=EOF)//读入袜子总数
    {
        getchar();  //吸收回车
        if(n==0)
            break;
        gets(str);  //读入字符串
        for(i=0;i<2*(n-1);++i)   //读入字符串
        {
            gets(str1);
            for(j=0;j<7;++j)
                str[j]=str[j]^str1[j];

/**

 *这句话作用是什么?按位异或结果是什么:

 *此句找到了不同的字符串!?

 *难道与相同字符串两次按位异或就会变回原来字符串?

 */
        }
        printf("%s\n",str);
    }
    return 0;//不要忘了写这句。
}

如果用一般的思路写的话,会超时的。 

转自/http://hi.baidu.com/chenyy197/item/81b6a8fa920626673c14853e

csdn  renyuzhuo0版权

三:我的代码

代码如下

//运行超时。与上文相比,添加注释如下

#include<stdio.h>
#include<string.h>
int main()
{
int i,j,m,n,flag,opq=1;    //opq变量名不好,让人理解比让机器运行更重要!
char a[10000][10],d[10];    //数据太大,没有好的处理机制就会出现如此的……惭愧
while(scanf("%d",&n)!=EOF){
flag=0;    //用于标记某一次是否找到不同字符串,0没找到,1找到了
m=2*n-1;
for(i=0;i<m;i++){
fflush(stdin);    //不是特别规范的清空键盘缓存的方法,勉强可以接受
gets(a[i]);
fflush(stdin);
}
/**

*这里曾尝试用多种方法解决时间超时问题,都没用,这是最后使用的一种方法,不好也没用。

*/

for(i=m-1;i>=0&&flag==0;i--){ 

for(j=i+1;j<m;j++){    //查找某一字符串前面的字符串,有相同改flag为1
if(strcmp(a[i],a[j])==0){
flag=1;
continue;
}
}
for(j=0;j<i;j++){    //查找某一字符串后面的字符串,有相同改flag为1
if(strcmp(a[i],a[j])==0){
flag=1;
continue;
}
}
if(flag==1)flag=0;
else flag=1;    //为下次查找做准备,是不是应该在循环中初始化呢?
}
printf("%s\n",a[i+1]);
}

return(0);
}



原创粉丝点击