Cod sursa(job #393421)

Utilizator Mishu91Andrei Misarca Mishu91 Data 9 februarie 2010 14:16:25
Problema Nums Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.95 kb
#include <cstdio>
#include <string>
#include <ext/hash_map>

using namespace __gnu_cxx;
using namespace std;

#define foreach(V) for(typeof(V).begin() it = (V).begin(); it != (V).end(); ++it)

const int MAX_N = 100005;

struct eqstr
{
	bool operator() (const char* s1, const char *s2) const
	{
		return strcmp(s1, s2) == 0;
	}
};

hash_map <const char*, int, hash <const char*>, eqstr> H;
pair <int, string> Q[MAX_N];
string V[MAX_N];
string P[MAX_N];

int N, M, L, T, A[MAX_N], U[MAX_N], W[MAX_N], I[MAX_N];
char viz[MAX_N];

inline int lsb(int x)
{
	return (x & -x);
}

void update(int poz)
{
	for(; poz < MAX_N; poz += lsb(poz))
		++A[poz];
}

int sum(int poz)
{
	int rez = 0;
	for(; poz; poz -= lsb(poz))
		rez += A[poz];
	return rez;
}

struct cmp
{
	bool operator() (const int &a, const int &b)
	{
		if(W[a] == W[b])
			return V[a].compare(V[b]) < 0;
		return W[a] < W[b];
	}
};

int main()
{
	freopen("nums.in","rt",stdin);
	freopen("nums.out","wt",stdout);

	scanf("%d\n", &N);

//	int nrl = 0;
	for(int i = 1; i <= N; ++i)
	{
		char buf[MAX_N];
		fgets(buf, MAX_N, stdin);
		int m = strlen(buf);
		if(buf[m-1] == '\n') buf[m-1] = 0;

		if(buf[0] == '1')
		{
			V[++L] = string(buf+2);
			Q[++T] = make_pair(1, string(buf+2));
			W[L] = m;
			I[L] = L;
		}

		else
			Q[++T] = make_pair(2, string(buf+2));
		
	}

	sort(I+1, I+L+1, cmp());

	int nr = 0;
	for(int i = 1; i <= L; ++i)
		{
			const char *s = V[I[i]].c_str();
//				fprintf(stderr, "%s\n", s);
			if(H.find(s) == H.end())
			{
				H[s] = ++nr;
				P[nr] = string(s);
			}
		}

	N = nr;

	for(int i = 1; i <= T; ++i)
	{
		int op = Q[i].first;
		const char *s = Q[i].second.c_str();

		if(op == 1)
		{
			int poz = H[s];
			if(U[poz]) continue;
			U[poz] = 1;

			update(poz);
		}

		if(op == 2)
		{
			int k = 0;
			for(int j = 0; s[j]; ++j)
				k = k * 10 + s[j] - '0';

			int lg = (1 << 17), i = 0;

			for(; lg; lg >>= 1)
				if(i + lg < MAX_N && sum(i + lg) < k)
					i += lg;

			printf("%s\n", P[i+1].c_str());
		}
	}
}