Cod sursa(job #67612)
#include <stdio.h>
#include <vector>
using namespace std;
const char iname[] = "obiective.in";
const char oname[] = "obiective.out";
#define MAX_N 32005
int N, M, T;
vector <int> G[MAX_N];
int Q[MAX_N], h, t, D[MAX_N];
bool U[MAX_N], V[MAX_N];
void clear(void)
{
int i;
for (i = 0; i <= t; ++ i)
V[Q[i]] = U[Q[i]] = false, D[Q[i]] = 0;
}
bool BF(const int s, const int d)
{
int x, y;
int i;
for (U[Q[h = t = 0] = s] = true; h <= t; ++ h) {
x = Q[h];
for (i = (int)(G[x].size() - 1); i >= 0; -- i) {
y = G[x][i];
if (U[y] == false)
U[Q[++ t] = y] = true;
if (y == d) {
clear();
return true;
}
}
}
clear();
return false;
}
int main(void)
{
FILE *fi = fopen(iname, "r");
FILE *fo = fopen(oname, "w");
int x;
int y;
int s, d;
int ans;
int i;
for (fscanf(fi, "%d %d", &N, &M); M > 0; -- M) {
fscanf(fi, "%d %d", &x, &y);
G[x].push_back(y);
}
for (fscanf(fi, "%d", &T); T > 0; -- T) {
fscanf(fi, "%d %d", &s, &d);
if (BF(s, d) == false) {
ans = int(1e6);
for (V[Q[h = t = 0] = d] = true; h <= t; ++ h) {
x = Q[h];
for (i = (int)(G[x].size() - 1); i >= 0; -- i) {
y = G[x][i];
if (U[y] == true) {
if (ans > D[y]) ans = D[y];
}else if (V[y] == false)
U[Q[++ t] = y] = true, D[y] = D[x] + 1;
}
}
} else
ans = 0;
fprintf(fo, "%d\n", ans);
clear();
}
fclose(fi);
fclose(fo);
return 0;
}