POJ-1885(列表数组)

题目: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值