问题描述:
1008. Airline Routes (35)
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<= N <= 104) and M (<=6N), 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 8Sample Output:
Yes Yes No No No No No No Yes Yes Yes No Yes Yes Yes No No No No No
由于各种各样的原因鸽了几天,在3.18前应该还会更一/两题。。。
一开始直接无脑暴力用了dfs和bfs,最后一个点都直接"运超",后来知道要用把时间复杂压缩到 O(n),于是改用dalao们所说的tarjan算法。。。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
#include<bits/stdc++.h> using namespace std; vector<int> vc; vector<set<int> > vd; vector<pair<int,int> > v; pair<int,int> p; stack<int> s; int ddfs,color; void tarjan(int x) { set<int>::iterator its; v[x].first=-(++ddfs); v[x].second=ddfs; s.push(x); for(its=vd[x].begin();its!=vd[x].end();++its) { if(!v[*its].first) { tarjan(*its); v[x].second=min(v[*its].second,v[x].second); } else if(v[*its].first<0) v[x].second=min(v[x].second,-v[*its].first); } if(v[x].first+v[x].second==0) { v[x].first=-v[x].first; vc[x]=++color; for(;s.top()!=x;s.pop()) { vc[s.top()]=color; v[s.top()].first=-v[s.top()].first; } s.pop(); } } int main() { // ios::sync_with_stdio(false); // freopen("data.txt","r",stdin); int n,k,x,c1,c2; scanf("%d %d",&n,&k); v.resize(n,pair<int,int>(0,0)); vd.resize(n); vc.resize(n); for(;k--;) { scanf("%d %d",&c1,&c2); c1--,c2--; vd[c1].insert(c2); } ddfs=0; color=0; for(int i=0;i<v.size();i++) { if(!v[i].first) tarjan(i); } scanf("%d",&k); for(;k--;) { scanf("%d %d",&c1,&c2); c1--,c2--; if(vc[c1]-vc[c2]) printf("No\n"); else printf("Yes\n"); } return 0; } |