Cod sursa(job #196925)

Utilizator gcosminGheorghe Cosmin gcosmin Data 30 iunie 2008 12:04:23
Problema Operatii Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.85 kb
#include <stdio.h>
#include <vector>
using namespace std;

#define NMAX 1000010

int N, nr = 0;

vector <int> poz[100010];

int tata[NMAX];

int father(int x)
{
	if (tata[x] == x) return x;
	return tata[x] = father(tata[x]);
}

void unite(int x, int y)
{
	if (!tata[x] || !tata[y]) return;
	x = father(x); y = father(y);
	if (x == y) return;

	nr--;
	if (rand() & 1) tata[x] = y;
	else tata[y] = x;
}

int main()
{
	int i, q;

	freopen("operatii.in", "r", stdin);
	freopen("operatii.out", "w", stdout);

	scanf("%d", &N);

	for (i = 1; i <= N; i++) {
		scanf("%d", &q);
		poz[q].push_back(i);
	}

	long long rez = 0;

	for (i = 100000; i >= 1; i--) {
		for (vector <int> :: iterator it = poz[i].begin(); it != poz[i].end(); ++it) {
			tata[*it] = *it; nr++;
			unite(*it, *it + 1);
			unite(*it, *it - 1);
		}

		rez += nr;
	}

	printf("%lld\n", rez);

return 0;
}