Cod sursa(job #2858081)

Utilizator DooMeDCristian Alexutan DooMeD Data 26 februarie 2022 22:17:25
Problema Distincte Scor 35
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.22 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int nmax = 1e5;
const int base = 256;

struct range{
	int l, r;
	int ind;
}query[nmax+5];

int v[nmax+5];
int vf[nmax+5];
ll sol[nmax+5];
ll ans;

bool comp(range a, range b) {
	int ar = a.l / base;
	int br = b.l / base;
	if(ar!=br) return (ar<br);
	return (a.r<b.r);
}

void add(int poz) {
	vf[v[poz]]++;
	if(vf[v[poz]]==1) ans = ans + 1LL * v[poz];
}

void rem(int poz) {
	if(vf[v[poz]]==1) ans = ans - 1LL * v[poz];
	vf[v[poz]]--;
}

int main () {
	ifstream f("distincte.in");
	ofstream g("distincte.out");
	
	int n,k,m; f >> n >> k >> m;
	for(int i=1; i<=n; i++) f >> v[i];
	for(int i=1; i<=m; i++) {
		f >> query[i].l >> query[i].r;
		query[i].ind = i;
	}
	sort(query+1,query+m+1,comp);
	int cl = 0, cr = 0;
	for(int i=1; i<=m; i++) {
		//cout << "on query " << query[i].l << " " << query[i].r << "\n";
		while(cl>query[i].l) {
			cl--;
			add(cl);
		}
		while(cr<query[i].r) {
			cr++;
			add(cr);
		}
		while(cl<query[i].l) {
			rem(cl);
			cl++;
		}
		while(cr>query[i].r) {
			rem(cr);
			cr--;
		}
		sol[query[i].ind] = ans;
		//for(int j=1; j<=n; j++) cout << j << ": " << vf[j] << "\n";
		//cout << "\n";
	}
	for(int i=1; i<=m; i++) g << sol[i] << "\n";
	return 0;
}