1. 程式人生 > >HDU-1113-Word Amalgamation

HDU-1113-Word Amalgamation

這題比較方便的解法是使用STL裡的map和set程式碼如下:

#include"bits/stdc++.h"
using namespace std;
map<string,set<string> >mp;
string s,t;
int main(){
    while(cin>>s&&(s!="XXXXXX")){
        t=s;
        sort(s.begin(),s.end());
        mp[s].insert(t);
    }
    while(cin>>s&&(s!="
XXXXXX")){ sort(s.begin(),s.end()); if(mp.count(s)){ for(auto i:mp[s]) cout<<i<<endl; } else puts("NOT A VALID WORD"); puts("******"); } return 0; }

這裡再加一種我用字典樹和鏈式前向星胡亂搞出來的解法:

#include"bits/stdc++.h"
using namespace
std; typedef long long LL; char s[105][10];int tot; char *point[105]; int Next[105];char t[10]; struct tree{ int fir; tree *Next[26]; }*root; bool cmp(char *s,char *t){ return strcmp(s,t)==1; } tree* init(){ tree* n=(tree*)malloc(sizeof(tree)); memset(n->Next,NULL,sizeof(n->Next)); n
->fir=-1; return n; } void in(char *t,int id){ tree* now=root; for(int i=0;t[i];i++){ int j=t[i]-'a'; if(!now->Next[j]) now->Next[j]=init(); now=now->Next[j]; } Next[id]=now->fir; now->fir=id; } void out( char *t){ tree* now=root; for(int i=0;t[i];i++){ int j=t[i]-'a'; if(!now->Next[j]){ puts("NOT A VALID WORD"); return; } now=now->Next[j]; } if(~now->fir){ for(int i=now->fir;~i;i=Next[i]) puts(point[i]); } else puts("NOT A VALID WORD"); } int main(){ root=init(); while(scanf("%s",s[tot])&&strcmp(s[tot],"XXXXXX")) point[tot]=s[tot++]; sort(point,point+tot,cmp); for(int i=0;i<tot;i++){ strcpy(t,point[i]); sort(t,t+strlen(t)); in(t,i); } while(scanf("%s",t)&&strcmp(t,"XXXXXX")){ sort(t,t+strlen(t)); out(t); puts("******"); } return 0; }