Airline Routes

Given a map of airline routes, you are supposed to check if a round trip can be planned between any pair of cities.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers N (2) and M (≤), which are the total number of cities (hence the cities are numbered from 1 to N) and the number of airline routes, respectively. Then M lines follow, each gives the information of a route in the format of the source city index first, and then the destination city index, separated by a space. It is guaranteed that the source is never the same as the destination.

After the map information, another positive integer K is given, which is the number of queries. Then K lines of queries follow, each contains a pair of distinct cities' indices.

Output Specification:

For each query, output in a line Yes if a round trip is possible, or No if not.

Sample Input:

12 19
3 4
1 3
12 11
5 9
6 2
3 2
10 7
9 1
7 12
2 4
9 5
2 6
12 4
11 10
4 8
8 12
11 8
12 7
1 5
20
11 4
12 7
3 6
2 3
5 3
3 9
4 3
8 3
8 10
10 11
7 8
7 1
9 5
1 9
2 6
3 1
3 12
7 3
6 9
6 8
 

Sample Output:

Yes
Yes
No
No
No
No
No
No
Yes
Yes
Yes
No
Yes
Yes
Yes
No
No
No
No
No
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 vector<int> vc;
 5 vector<set<int> > vd;
 6 vector<pair<int,int> > v;
 7 pair<int,int> p;
 8 stack<int> s;
 9 int ddfs,color;
10 
11 void tarjan(int x)
12 {
13     set<int>::iterator its;
14     v[x].first=-(++ddfs);
15     v[x].second=ddfs;
16     s.push(x);
17     for(its=vd[x].begin();its!=vd[x].end();++its)
18     {
19         if(!v[*its].first)
20         {
21             tarjan(*its);
22             v[x].second=min(v[*its].second,v[x].second);
23         }
24         else if(v[*its].first<0)
25         v[x].second=min(v[x].second,-v[*its].first);
26     }
27     if(v[x].first+v[x].second==0)
28     {
29         v[x].first=-v[x].first;
30         vc[x]=++color;
31         for(;s.top()!=x;s.pop())
32         {
33             vc[s.top()]=color;
34             v[s.top()].first=-v[s.top()].first;
35         }
36         s.pop();
37     }
38 }
39 int main()
40 {
41 //  ios::sync_with_stdio(false);
42 //  freopen("data.txt","r",stdin);
43     int n,k,x,c1,c2;
44     scanf("%d %d",&n,&k);
45     v.resize(n,pair<int,int>(0,0));
46     vd.resize(n);
47     vc.resize(n);
48       for(;k--;)
49       {
50         scanf("%d %d",&c1,&c2);
51         c1--,c2--;
52         vd[c1].insert(c2);
53       }
54       ddfs=0;
55       color=0;
56       for(int i=0;i<v.size();i++)
57       {
58           if(!v[i].first)
59           tarjan(i);
60     }
61       scanf("%d",&k);
62       for(;k--;)
63       {
64         scanf("%d %d",&c1,&c2);
65         c1--,c2--;
66         if(vc[c1]-vc[c2])
67          printf("No\n");
68         else
69            printf("Yes\n");
70       }
71       return 0;
72 }

猜你喜欢

转载自www.cnblogs.com/SkystarX/p/12285807.html