题目大意:输入文章,将文章中的单词按字典序排列输出。
解题思路:储存每个单词然后排序。时间复杂度比较大,容易 TLE,要优化算法,顺便学了一下快排,希望今后能记住。还有比较坑的是出现 RE,数组要开大一些。
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
char word[100000][500];
bool ch(char c) {
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return true;
else return false;
}
void Qsort(int left, int right) {
if(left >= right) return;
int i = left;
int j = right;
char key[200];
strcpy(key, word[left]);
while(i < j) {
while(i < j && (strcmp(key,word[j]) <= 0))
j--;
strcpy(word[i],word[j]);
while(i < j && (strcmp(key,word[i]) >= 0))
i++;
strcpy(word[j],word[i]);
}
strcpy(word[i],key);
Qsort(left, i-1);
Qsort(i+1, right);
}
int main() {
char c;
int tot = -1;
while((c = getchar()) != EOF) {
int i = 0;
if(ch(c)) {
tot++;
while(ch(c)) {
if (c >= 'A' && c <= 'Z')
c = c - 'A' + 'a';
word[tot][i++] = c;
c = getchar();
}
word[tot][i] = '\0';
}
}
Qsort(0, tot);
for (int i = 0; i <= tot; i++){
if(i && (strcmp(word[i], word[i-1]) == 0)) continue;
puts(word[i]);
}
return 0;
}