Cod sursa(job #1709769)

Utilizator UTCN_heapstrUTCN HeapStr UTCN_heapstr Data 28 mai 2016 13:49:37
Problema Pq Scor 100
Compilator cpp Status done
Runda ONIS 2016 - Runda - 2 - ACM ICPC Romanian Programming Contest Marime 2.18 kb
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <algorithm>
#include <string>
#include <string.h>
#include <math.h>
#include <set>

using namespace std;

vector<pair<int, int>> queries[100002];

int *lastIndex = new int[100002];

vector<int> a;

struct Compfunc
{
	bool operator ()(const pair<int, int> &a, const pair<int, int> &b)
	{
		if (a.first != b.first){
			return a.first < b.first;
		}

		return a.second < b.second;
	}
};


set<pair<int, int>, Compfunc> tree;

int main(){
	freopen("pq.in", "r", stdin);
	freopen("pq.out", "w", stdout);

	int n, q;

	scanf("%d %d", &n, &q);

	

	for (int i = 0; i < n; i++){
		int val;
		scanf("%d", &val);

		a.push_back(val);
	}

	

	for (int i = 0; i < q; i++){
		int start, end;

		scanf("%d %d", &start, &end);

		queries[end-1].push_back(make_pair(start-1, i));
	}

	int *sol = new int[q];

	


	

	for (int i = 0; i < 100002; i++){
		lastIndex[i] = -1;
	}

	set<pair<int, int> >::iterator it;
	set<pair<int, int> >::iterator it2;

	for (int i = 0; i < n; i++){

		if (lastIndex[a[i]] != -1){
			int len = i - lastIndex[a[i]];
			int index = lastIndex[a[i]];

			it = tree.lower_bound(make_pair(index, -1));
			if (it == tree.begin()){
				it = tree.end();
			}
			else {
				it--;
			}


			while (it != tree.end()){
				if (it->second <= len){
					tree.erase(it);

					it = tree.lower_bound(make_pair(index, -1));
					if (it == tree.begin()){
						it = tree.end();
					}
					else {
						it--;
					}
				}
				else {
					break;
				}
			}

			it = tree.lower_bound(make_pair(index, 10000000));

			if (it == tree.end() || len > it->second) {
				tree.insert(make_pair(index, len));
			}
		}

		for (int j = 0; j < queries[i].size(); j++){
			pair<int, int> qqq = queries[i][j];

			it = tree.upper_bound(make_pair(queries[i][j].first, -1));

			if (it == tree.end()){
				sol[queries[i][j].second] = -1;
			}
			else {
				sol[queries[i][j].second] = it->second;
			}
		}

		lastIndex[a[i]] = i;
	}

	for (int i = 0; i < q; i++){
		printf("%d\n", sol[i]);
	}

	return 0;
}