Cod sursa(job #67774)

Utilizator sims_glAlexandru Simion sims_gl Data 25 iunie 2007 14:02:28
Problema Obiective Scor 35
Compilator cpp Status done
Runda preONI 2007, Runda Finala, Clasele 11-12 Marime 2.04 kb
#include <stdio.h>
#include <vector>
#include <algorithm>

using namespace std;

#define nm 32100
#define tm 100010
#define inf 1000000

struct vecin
{
	int nod, t;
};

struct querry
{
	int x, y;
};

int n, m, k, pl[tm], c[nm], q[2][nm], ql[2], qr[2], len[nm], sol[nm];
vector<vecin> a[nm];
querry s[tm];

void go(int start)
{
	int i, cost = 0, crt = 1;

	ql[1] = qr[1] = ql[2] = qr[2] = 0;
    q[1][qr[1]++] = start;
	c[start] = 0;

	while(ql[crt] < qr[crt])
	{
    	while(ql[crt] < qr[crt])
    	{
        	for (i = 0; i < len[q[crt][ql[crt]]]; ++i)
            	if (c[q[crt][ql[crt]]] == cost && c[a[q[crt][ql[crt]]][i].nod] > cost && a[q[crt][ql[crt]]][i].t == 0)
    			{
    				q[crt][qr[crt]++] = a[q[crt][ql[crt]]][i].nod;
    				c[a[q[crt][ql[crt]]][i].nod] = cost;
    			}
				else if (c[q[crt][ql[crt]]] == cost && c[a[q[crt][ql[crt]]][i].nod] > cost)
                {
					q[1 - crt][qr[1 - crt]++] = a[q[crt][ql[crt]]][i].nod;
					c[a[q[crt][ql[crt]]][i].nod] = cost + 1;
				}
    
    		++ql[crt];
    	}

		++cost;
		ql[crt] = qr[crt] = 0;
		crt = 1 - crt;
    }
}

int comp(int a, int b)
{
	return s[a].x < s[b].x || (s[a].x == s[b].x && s[a].y < s[b].y);
}

int main()
{
	int i, j, x, y;
	vecin aux;

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

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

	for (i = 1; i <= m; ++i)
	{
	 	scanf("%d%d", &x, &y);

        aux.nod = y;
		aux.t = 0;
		a[x].push_back(aux);

		aux.nod = x;
		aux.t = 1;
		a[y].push_back(aux);
	}

	for (i = 1; i <= n; ++i)
		len[i] = a[i].size();

	scanf("%d", &k);

	for (i = 1; i <= k; ++i)
	{
    	scanf("%d%d", &s[i].x, &s[i].y);
		pl[i] = i;
	}

    sort(pl + 1, pl + k + 1, comp);

	for (i = 1; i <= k; ++i)
	{
		for (j = 1; j <= n; ++j)
			c[j] = inf;

		go(s[pl[i]].x);

		sol[pl[i]] = c[s[pl[i]].y];

		while(s[pl[i]].x == s[pl[i + 1]].x)
		{
			++i;
			sol[pl[i]] = c[s[pl[i]].y];
        }
	}

	for (i = 1; i <= k; ++i)
		printf("%d\n", sol[i]);

	return 0;
}