Cod sursa(job #219054)

Utilizator tvladTataranu Vlad tvlad Data 4 noiembrie 2008 22:08:06
Problema Distincte Scor 35
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.19 kb
#include <cstdio>
#include <algorithm>
using namespace std;

struct query_int {
	int s, f, orig_poz;
	long long rez;
};

const int N = 100000;
const int K = N;
const int M = 100000;
const int AINT_SIZE = 1 << 18;

int n, k, m;
int v[N];
query_int q[M];
int last[K+1];
int top_length;
long long ai[AINT_SIZE];

bool comp_interval ( const query_int &a, const query_int &b ) { return (a.f == b.f) ? a.s < b.s : a.f < b.f; }
bool comp_orig_poz ( const query_int &a, const query_int &b ) { return a.orig_poz < b.orig_poz; }

void add ( int node, int node_start, int node_length, int target, int value ) {
	ai[node] += value;
	if (node_length > 1)
		if (target < node_start + (node_length >> 1))
			add(node*2+1, node_start, node_length >> 1, target, value); else
			add(node*2+2, node_start + (node_length >> 1), node_length >> 1, target, value);
}

long long query ( int node, int node_start, int node_length, int target_start, int target_end ) {
	if (target_start == node_start && target_end == node_start + node_length - 1)
		return ai[node];
	int mid = node_start + (node_length >> 1);
	long long r = 0;
	if (target_start < mid)
		r += query(node*2+1, node_start, node_length >> 1, target_start, min(target_end, mid-1));
	if (target_end >= mid)
		r += query(node*2+2, mid, node_length >> 1, max(target_start, mid), target_end);
	return r;
}

int main() {
	freopen("distincte.in","rt",stdin);
	freopen("distincte.out","wt",stdout);
	scanf("%d %d %d",&n,&k,&m);
	for (top_length = 1; top_length < n; top_length <<= 1);
	for (int i = 0; i < n; ++i) scanf("%d",&v[i]);
	for (int i = 0; i < m; ++i) {
		scanf("%d %d",&q[i].s,&q[i].f);
		--q[i].s;
		--q[i].f;
		q[i].orig_poz = i;
	}

	sort(q,q+m,comp_interval);
	
	for (int i = 1; i <= k; ++i) last[i] = -1;
	int query_ptr = 0;
	for (int i = 0; i < n; ++i) {
		add(0, 0, top_length, i, v[i]);
		if (last[v[i]] != -1)
			add(0, 0, top_length, last[v[i]], -v[i]);
		last[v[i]] = i;

		for (; query_ptr < m && q[query_ptr].f == i; ++query_ptr)
			q[query_ptr].rez = query(0, 0, top_length, q[query_ptr].s, q[query_ptr].f);
	}

	sort(q,q+m,comp_orig_poz);
	for (int i = 0; i < m; ++i)
		printf("%lld\n",q[i].rez);
	return 0;
}