Cod sursa(job #1709204)

Utilizator DEFINEtelyEngineersUPB Pirtoaca Vasilescu Zamfiratos DEFINEtelyEngineers Data 28 mai 2016 11:16:33
Problema Pq Scor 100
Compilator cpp Status done
Runda ONIS 2016 - Runda - 2 - ACM ICPC Romanian Programming Contest Marime 1.77 kb
#include<fstream>
#include<iostream>
#include<algorithm>
using namespace std;

#define NMAX 400001

int v[NMAX],val,a,b,cp,c[NMAX],poz;

struct entry {
	int x, y, poz;
	
	entry () {
		x = 0;
		y = 0;
		poz = 0;
	}
	
	entry (int _x, int _y, int _poz) {
		x = _x;
		y = _y;
		poz = _poz;
	}
};

struct cmp {
	bool operator () (const entry &a, const entry &b) const {
		if(a.y == b.y)
			return a.x < b.x;
		return a.y < b.y;
	}
};

inline int maxim(int a, int b)
{
	if(a>=b)
		return a;
	return b;
}

inline void update(int nod, int st, int dr)
{
	int mij;
	if(st==dr) {
		v[nod]=val;
		return ;
	}
	mij=(st+dr)/2;
	if(poz<=mij)
		update(nod*2,st,mij);
	else update(nod*2+1,mij+1,dr);
	v[nod]=maxim(v[2*nod],v[2*nod+1]);
}

inline void query(int nod, int st, int dr)
{
	int mij;
	if((a<=st)&&(dr<=b)) {
		if(v[nod]>val)
			val=v[nod];
		return ;
	}
	mij=(st+dr)/2;
	if(a<=mij)
		query(nod*2,st,mij);
	if(mij<b)
		query(nod*2+1,mij+1,dr);
}

entry Q[NMAX],V[NMAX];
int _last[NMAX],sol[NMAX];

int main ()
{
	int n, i, q, x ,y, k, j;
	ifstream f("pq.in");
	ofstream g("pq.out");
	f >> n >> q;
	for(i=1; i <= n; i++) 
		f >> c[i];
	for(i=1;i<=q;i++) {
		f>>x>>y;
		Q[i] = entry(x,y,i);
	}
	f.close();
	sort(Q + 1, Q + q + 1, cmp());
	k = 0;
	for(i = 1; i <= n; i++) {
		if(_last[c[i]]) 
			V[++k] = entry(_last[c[i]], i, i);
		_last[c[i]]=i;
	}
	sort(V + 1, V + k + 1, cmp());
	j = 1;
	for(i = 1; i <= q; i++) {
		while(j <= k && V[j].y <= Q[i].y) {
			poz = V[j].x;
			val = V[j].y - V[j].x;
			update(1, 0, 99999);
			j++;
		}
		a = Q[i].x;
		b = Q[i].y;
		val = 0;
		query(1, 0, 99999);
		if(val == 0)
			val = -1;
		sol[Q[i].poz] = val;
	}
	for(i=1;i<=q;i++)
		g<<sol[i]<<'\n';
	g.close();
	return 0;
}