Cod sursa(job #372675)

Utilizator indestructiblecont de teste indestructible Data 11 decembrie 2009 11:13:50
Problema Nums Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
#define N 1<<17
using namespace std;
vector <int> v[N];
struct query
{
	int a,b;
};
query A[N];
int n,r,s,val[N],ord[N],aib[N],back[N];
char t[N];
inline int cif(char x)
{
	return x>='0' && x<='9';
}
void read()
{
	scanf("%d\n",&n);
	int i,poz,tip;
	for (i=1; i<=n; i++)
	{
		poz=0; tip=0;
		fgets(t+1,N,stdin);
		while (cif(t[poz+1]))
			tip=t[poz+1]-'0',poz++;
		while (t[poz+1]==' ')
			poz++;
		if (tip)
		{
			s++;
			while (cif(t[poz+1]))
			{
				poz++;
				v[s].push_back(t[poz]-'0');
			}
			ord[s]=s;
		}
		else
		{
			r++;
			while (cif(t[poz+1]))
			{
				poz++;
				A[r].a=A[r].a*10+t[poz]-'0';
			}
			A[r].b=s;
		}
	}
}
bool comp(int x,int y)
{
	if (v[x].size()<v[y].size())
		return 1;
	if (v[x].size()>v[y].size())
		return 0;
	int i;
	for (i=0; i<v[x].size(); i++)
	{
		if (v[x][i]<v[y][i])
			return 1;
		if (v[x][i]>v[y][i])
			return 0;
	}
	return 0;
}
void inlocuire()
{
	int i;
	for (i=1; i<=s; i++)
		val[ord[i]]=i;
	for (i=1; i<=s; i++)
		back[val[i]]=i;
}
int lsb(int x)
{
	return x & -x;
}
void update(int poz,int val)
{
	int i;
	for (i=poz; i<=s; i+=lsb(i))
		aib[i]+=val;
}
int suma(int x)
{
	int i,s=0;
	for (i=x; i>=1; i-=lsb(i))
		s+=aib[i];
	return s;
}
int cbin(int val)
{
	int i,step=N;
	for (i=0; step; step>>=1)
		if (i+step<=s && suma(i+step)<=val)
			i+=step;
	return i;
}
void solve()
{
	int i,j,start=0,nr;
	for (i=1; i<=s; i++)
	{
		update(val[i],1);
		while (A[start+1].b==i)
		{
			start++;
			nr=cbin(A[start].a);
			for (j=0; j<v[back[nr]].size(); j++)
				printf("%d",v[back[nr]][j]);
			printf("\n");
		}
	}
}
int main()
{
	freopen("nums.in","r",stdin);
	freopen("nums.out","w",stdout);
	read();
	sort(ord+1,ord+s+1,comp);
	inlocuire();
	solve();
	return 0;
}