题目:http://poj.org/problem?id=1885
题目中说不超过10000个不同的单词,实测是扯淡的,单词数量大于20000个
#include <cstdio>
#include <iostream>
#include <cctype>
#include <list>
#include <string>
using namespace std;
#define MAX_LIST 400
#define MAX_CAPACITY 100
int idx = MAX_LIST - 1;
list<string> arr[MAX_LIST];
string GetWord(int n)
{
//make n to be an index starting from 0
--n;
//find its location list
int i = idx, cnt = 0;
for(; cnt + arr[i].size() <= n; ++i) cnt += arr[i].size();
//now arr[i] contains the word
list<string>::iterator iter = arr[i].begin();
n -= cnt;
while(n--) ++iter;
//we need to transfer this word from arr[i] to the very front
arr[idx].splice(arr[idx].begin(), arr[i], iter);
if(arr[idx].size() > MAX_CAPACITY){
arr[idx-1].splice(arr[idx-1].begin(), arr[idx], iter);
--idx;
}
return *iter;
}
void AddWord(const string& s)
{
if(arr[idx].size() >= MAX_CAPACITY) --idx;
arr[idx].push_front(s);
}
int main()
{
ios::sync_with_stdio(false);
string line, word;
while(getline(cin, line), line != "0"){
int i = 0, len = line.size(), num = 0;
bool bufferingNumber = false;
word.clear();
for(; i < len; ++i){
char c = line[i];
if(isdigit(c)){
num = num * 10 + c - '0';
bufferingNumber = true;
}
else{
//check if number ends here
if(bufferingNumber){
printf("%s", GetWord(num).c_str());
bufferingNumber = false;
num = 0;
}
//print this char as it is
putchar(c);
//check if we have a new word now
if(isalpha(c)){
word.push_back(c);
}
else{
if(!word.empty()){
AddWord(word);
word.clear();
}
}
}
}
if(bufferingNumber){
printf("%s", GetWord(num).c_str());
bufferingNumber = false;
num = 0;
}
if(!word.empty()){
AddWord(word);
word.clear();
}
putchar('\n');
}
return 0;
}