题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2072
解题思路:
找出所有的单词一共有多少个,要求单词是不同的,虽然这题现在看起来很简单,但是对于当时刚接触才acm的人,什么都不知道,可算是不知wrong了多少次,才做出一个符合题意,但却超时的代码,不过现在回忆起来却感到满满的幸福感.
AC代码(strtok函数):
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char s[1000],a[1000][1000];
int main()
{
while(gets(s))
{
if(strcmp(s,"#")==0)
break;
int i,j,k,n=0;
char *p;
p=strtok(s," ");
for(i=0;p!=NULL;i++)
{
strcpy(a[i],p);
p=strtok(NULL," ");
}
for(k=0;k<i;k++)
for(j=k+1;j<i;j++)
{
if(strcmp(a[k],a[j])==0)
{
n++;break;
}
}
printf("%d\n",i-n);
}
return 0;
}
AC代码(set):
#include<iostream>
#include<set>
#include<string>
using namespace std;
int main()
{
set<string> st;
string s;
char c;
s.clear();
while((c=cin.get())!='#')
{
while(c!=' '&&c!='\n')
{
s+=c;
c=cin.get();
}
if(s.length())
{
st.insert(s);
s.clear();
}
if(c=='\n')
{
cout<<st.size()<<endl;
st.clear();
s.clear();
}
}
return 0;
}
AC代码(map):
#include<iostream>
#include<string>
#include<cctype>
#include<map>
using namespace std;
int main()
{
string s;
map<string,int> m;
while(getline(cin,s)&&s!="#")
{
string str;
m.clear();
int len=s.length();
for(int i=0;i<len;i++)
{
if(isalpha(s[i]))
{
str.clear();
int j;
for(j=i;isalpha(s[j])&&j<len;j++)
str+=s[j];
i=j;
m[str]++;
}
}
cout<<m.size()<<endl;
}
return 0;
}
AC代码(map):
#include <iostream>
#include <sstream>
#include <string>
#include <set>
using namespace std;
int main(){
set<string>st;
string str;
while(getline(cin,str)){
st.clear();
if(str[0]=='#')
break;
stringstream strm(str);
string tmp;
while(strm>>tmp)
st.insert(tmp);
cout<<st.size()<<endl;
}
return 0;
}
AC代码(字典树):
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct node
{
int cnt;
struct node *next[26];
node()
{
cnt = 0;
memset(next,0,sizeof(next));
}
};
node *root = NULL;
int sum;
void buildtrie(char *s)
{
node *p=root;
node *tmp=NULL;
int i,l=strlen(s);
for(i=0;i<l;i++)
{
if(p->next[s[i]-'a']==NULL)
{
tmp=new node;
p->next[s[i]-'a']=tmp;
}
p=p->next[s[i]-'a'];
}
if(!p->cnt)
sum++;
p->cnt++;
}
int main()
{
char str[1000005], ss[1005];
while(gets(str) && str[0] != '#')
{
root = new node;
int l = strlen(str);
sum = 0;
for(int i = 0; i < l; i++){
while(str[i++] == ' '); i--;
if(i == l)
break;
int j = 0;
while(str[i] != ' ' && i < l)
ss[j++] = str[i++];
ss[j] = '\0';
//cout<<sum<<endl;
buildtrie(ss);
}
printf("%d\n",sum);
}
return 0;
}