Cod sursa(job #254418)

Utilizator raduzerRadu Zernoveanu raduzer Data 7 februarie 2009 12:02:15
Problema Cuburi2 Scor 20
Compilator cpp Status done
Runda Stelele Informaticii 2009, clasele 9-10, ziua 2 Marime 1.87 kb
#include <cstdio>

const int MAX_N = 5010;
const int INF = 10000000000LL;
const int MAX_L = 1 << 19;

int n, m, z, sol, pq;
long long a[MAX_N], b[MAX_N], c[MAX_N];
int arb[MAX_L], poz[MAX_L];

void query(int p, int a, int b, int x, int y)   
{   
    int mij = (a + b) / 2;   
    if (a >= x && b <= y)   
    {   
        if (sol < arb[p]) sol = arb[p], pq = poz[p];   
        return;   
    }   
    if (x <= mij) query(p * 2, a, mij, x, y);   
    if (y > mij) query(p * 2 + 1, mij + 1, b, x, y);   
} 

void solve2()
{
	int pow = 1, pu = 0;
	int i, x, y, j;
	while (pow < n) pow = 1 << (++pu);
	
	for (i = pow; i < pow + n; ++i) 
	{
		scanf("%d", &arb[i]);
		poz[i] = i - pow + 1;
	}
	
	for (i = pu - 1; i > 0; --i)
		for (j = (1 << i); j < (1 << (i + 1)); ++j)
		{
			arb[j] = arb[j * 2];
			poz[j] = poz[j * 2];
			if (arb[j * 2 + 1] > arb[j]) 
			{
				arb[j] = arb[j * 2 + 1];
				poz[j] = poz[j * 2 + 1];
			}
		}
		
	for (i = 1; i <= m; ++i)
	{
		scanf("%d %d", &x, &y);
		
		sol = 0, pq = 0;
		
		query(1, 1, pow, x, y);
		
		printf("%d %d\n", pq, sol);
	}
	
	
}

void solve1()
{
	int i, x, y;
	for (i = 1; i <= n; ++i) 
	{
		scanf("%lld", &a[i]);
		b[i] = b[i - 1] + a[i];
	}
	
	for (i = n; i; --i) c[i] = c[i + 1] + a[i];
		
	for (; m; --m)
	{
		scanf("%d %d", &x, &y);
		if (x > y) x ^= y ^= x ^= y;
		
		long long s1 = 0, s2 = 0;
		for (i = y - 1; i >= x; --i) s2 += (c[i + 1] - c[y + 1]);
		
		long long mn = INF;
		int p = 0;
		
		for (i = x; i <= y; ++i)
		{
			if (s1 + s2 < mn) mn = s1 + s2, p = i;
			s1 += (b[i] - b[x - 1]);
			s2 -= (c[i + 1] - c[y + 1]);
		}
		
		printf("%d %lld\n", p, mn);
	}
}

int main()
{
	int i, x, y;
	freopen("cuburi2.in", "r", stdin);
	freopen("cuburi2.out", "w", stdout);
	
	scanf("%d %d", &n, &m);
	
	if (n <= 5000 && m <= 5000) solve1();
	else solve2();
}