hdu 2072 单词数 解题报告 strtok函数 字符串流 字典树
解题报告:有很多写法,每种我都介绍下。
1.用set,istringtream。set是一种容器,往里面插入重复的内容时会自动失效,就做到了去重的效果。这种方法很简单,了解一下就行。
#include<iostream>
#include<math.h>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<string.h>
#include<map>
#include<stack>
#include<stdio.h>
#include<cstdio>
#include<stdlib.h>
#include<fstream>
#include<sstream>
#include<set>
#pragma warning(disable:4996)
#define INF 0x3f3f3f3f
#define ll long long
#define PI acos(-1.0)
const int N = 1000010;
const int maxn = 1e9;
using namespace std;
int main()
{
string s;
while (getline(cin, s) && s != "#")
{
istringstream is(s);
set<string>st;//set自动去重
string t;
while (is >> t)
{
st.insert(t);
}
cout << st.size() << endl;
}
}
2.用strtok函数。这个函数是专门用来分解字符串的。在delim中的所有字符都会作为分隔点,可以不只是空格。
#include<iostream>
#include<math.h>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<string.h>
#include<map>
#include<stack>
#include<stdio.h>
#include<cstdio>
#include<stdlib.h>
#include<fstream>
#include<sstream>
#include<set>
#pragma warning(disable:4996)
#define INF 0x3f3f3f3f
#define ll long long
#define PI acos(-1.0)
const int N = 1000010;
const int maxn = 1e9;
using namespace std;
int main()
{
char buf[1024];
char pound[] = "#";
char delim[] = " ";
char* p;
set<string>st;
while (gets_s(buf) != NULL)
{
if (strcmp(buf, pound) == 0)
break;
st.clear();
p = strtok(buf, delim);
while (p)
{
st.insert(p);
p = strtok(NULL, delim);
}
cout << st.size() << endl;
}
}
3.用字典树。
#include<iostream>
#include<math.h>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<cstring>
#include<string>
#include<string.h>
#include<map>
#include<stack>
#include<stdio.h>
#include<cstdio>
#include<stdlib.h>
#include<fstream>
#include<sstream>
#include<set>
#pragma warning(disable:4996)
#define INF 0x3f3f3f3f
#define ll long long
#define PI acos(-1.0)
const int N = 1000010;
const int maxn = 1e9;
using namespace std;
struct trie {
int cnt;
trie* next[26];
trie()
{
cnt = 0;
for (int i = 0; i < 26; i++)
{
next[i] = NULL;
}
}
};
int ans;
trie* root, * temp, * t;
void insert(string str)
{
t = root;
for (int i = 0; i < str.length(); i++)
{
if (t->next[str[i] - 'a'] == NULL)
{
temp = new trie;
t->next[str[i] - 'a'] = temp;
}
t = t->next[str[i] - 'a'];
}
if (!t->cnt)
{
t->cnt = 1;
ans++;
}
}
int main()
{
string str;
while (getline(cin, str))
{
ans = 0;
root = new trie;
if (str.length() == 1 && str[0] == '#')
break;
istringstream is(str);
string s;
while (is >> s)
{
insert(s);
}
printf("%d\n", ans);
}
}