Pagini recente » Cod sursa (job #812) | Cod sursa (job #2137730) | Cod sursa (job #3033147) | Cod sursa (job #2921068) | Cod sursa (job #3203399)
using namespace std;
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#define NMAX 32001
ifstream fin("obiective.in");
ofstream fout("obiective.out");
int n, m, t;
vector<int> G[NMAX], Ginv[NMAX];
char cost[NMAX][NMAX];
pair<int,int> muchii[2*NMAX];
int comp[NMAX];
bool viz[NMAX];
vector<int> s;
vector<vector<int>> total;
void kosaraju();
void dfs(int nod);
void dfs2(int nod, vector<int> &c);
int main() {
fin >> n >> m;
for (int i = 1; i<=m; i++) {
int a, b;
fin >> a >> b;
muchii[i] = {a,b};
G[a].push_back(b);
Ginv[b].push_back(a);
}
kosaraju();
for (int i = 0; i<total.size(); i++) {
for (int j = 0; j<total.size(); j++) {
cost[i][j] = -1;
}
}
for (int i = 1; i<=m; i++) {
if (comp[muchii[i].first] != comp[muchii[i].second]) {
//cout << comp[muchii[i].first] << " " << comp[muchii[i].second] << endl;
cost[comp[muchii[i].first]][comp[muchii[i].second]] = 0;
cost[comp[muchii[i].second]][comp[muchii[i].first]] = 1;
}
}
/*
for (int i = 0; i<total.size(); i++) {
for (int j = 0; j<total.size(); j++) {
cout << (int)cost[i][j] << " ";
}
cout << endl;
}
cout << endl;*/
for (int k = 0; k<total.size(); k++) {
for (int i = 0; i<total.size(); i++) {
for (int j = 0; j<total.size(); j++) {
if (i == j) continue;
if (cost[i][k] > -1 && cost[k][j] > -1) {
if (cost[i][j] == -1 || cost[i][j] > cost[i][k] + cost[k][j]) {
cost[i][j] = cost[i][k] + cost[k][j];
//cout << i << " " << k << " " << j << " " << (int)cost[i][j] << endl;
}
}
}
}
}
/*
for (int i = 0; i<total.size(); i++) {
for (int j = 0; j<total.size(); j++) {
cout << (int)cost[i][j] << " ";
}
cout << endl;
}*/
fin >> t;
while (t--) {
int a, b;
fin >> a >> b;
fout << (int)cost[comp[a]][comp[b]] << "\n";
}
return 0;
}
void kosaraju() {
for (int i = 1; i<=n; i++) {
if (viz[i]) continue;
dfs(i);
}
for (int i = 1; i<=n; i++) {
viz[i] = 0;
}
while (!s.empty()) {
int nod = s.back();
s.pop_back();
if (viz[nod]) /*s.pop_back();*/ continue;
vector<int> c;
dfs2(nod, c);
total.push_back(c);
}
for (int i = 0; i<total.size(); i++) {
for (int j = 0; j<total[i].size(); j++) {
// cout << total[i][j] << " ";
comp[total[i][j]] = i;
}
//cout << endl;
}
}
void dfs(int nod) {
viz[nod] = 1;
for (auto it: G[nod]) {
if (!viz[it]) {
dfs(it);
}
}
s.push_back(nod);
}
void dfs2(int nod, vector<int> &c) {
viz[nod] = 1;
c.push_back(nod);
for (auto it: Ginv[nod]) {
if (!viz[it]) {
dfs2(it, c);
}
}
}