UVa-10391 Compound Words

来源:互联网 发布:小非农数据 编辑:程序博客网 时间:2024/06/06 04:50
UVa-10391 Compound Words


分析:这个题起初我是用c语言里的基础做的,也就是说,没用 STL,便一跪再跪,超时再超时,但我感觉我的做法是
完全没错的。复合词这个题便是每种情况都遍历一下试试,看看有没有可能有两个词能组成它便可。难点就在于怎么拆分,之后再
判断他是否能由两个词组成。
先献上我超时多次,报到我想狗带的代码

#include <cstdio>
#include <cstring>
char word[120005][50];
char s1[50],s2[50];
int n;
void jie(int i,int j)
{
    int k;
    for (k=0;k<=j;k++)
        s1[k]=word[i][k];
    s1[k]='\0';
}
/*void wei(int i,int j)
{
    int k,t=0;
    for (k=j+1;k<strlen(word[i]);k++)
        s2[t++]=word[i][k];
    s2[t]='\0';
}*/
int search(char *a)
{
    for (int i=0;i<n;i++)
        if (strcmp(word[i],a)==0) return 1;
    return 0;
}
int main()
{
    char ch[25];
    n=0;
    int f=0;
    while (scanf("%s",ch)==1&&ch[0]!='0')
    {
        strcpy(word[n],ch);
        n++;
    }
    for (int i=0;i<n;i++)
    {
        if (strlen(word[i])>1)
        {
            for (int j=0;j<strlen(word[i])-1;j++)
            {
                jie(i,j);
                char *p=word[i]+j+1;//
                //wei(i,j);
                strcpy(s2,p);
                if (search(s2)&&search(s1)) printf("%s\n",word[i]);
            }
        }
    }
    return 0;
}
用两个函数分别拆分每个词超时是必然,因为效率实在是太低,第二次我稍微优化了一下,便是用指针存后面的部分
,也许可能会稍微提高,但是还是超时了,这几个字符串函数的效率还是太低啊。

下面是STL做的代码,成功AC
核心理念:设定一个string类型的集合,使用STL函数的那几个函数,效率真是提高了无数倍,
substr(a,b)注意b为截的元素的个数,亦或说长度。


#include <iostream>
#include <set>
#include <string>
using namespace std;
int main()
{
    set<string> s;
    string tmp;
    while (cin>>tmp) s.insert(tmp);
    set<string>::iterator it;
    for (it=s.begin();it!=s.end();it++)
    {
        tmp=*it;
        for (int i=1;i<tmp.length();i++)
        {
            if (s.find(tmp.substr(0,i))!=s.end()&&s.find(tmp.substr(i,tmp.length()-i))!= s.end())
            {
                cout<<tmp<<endl;
                break;
            }
        }
    }
    return 0;
}


0 0
原创粉丝点击