The above question is commonly seen in a final exam of the course Data Structures. That is, given a graph G, you are supposed to tell if a sequence of vertices can be possibly obtained from any depth first search (DFS) on G.
Now it is your job to write a program which can give the answers automatically.
Note: it is required that each vertex must be visited once even if the graph is not connected. In the graph given by the sample input, if we start from vertex 4, then vertex 1 cannot be reached during this DFS, yet it can be the first vertex visited in the next DFS. Hence the 5th query 4 3 2 5 1
is possible.
Input Specification:
Each input file contains one test case. For each case, the first line contains 3 positive integers: N (≤103), M (≤104), and K (≤100), which are the number of vertices, the number of edges, and the number of queries, respectively. Then M lines follow, each gives an edge in the format:
source destination
which means that there is an edge from source
vertex to destination
vertex. Here we assume that all the vertices are numbered from 1 to N. It is guaranteed that source
is never the same as destination
.
Finally K lines of queries are given, each contains N vertices. The numbers in a line are separated by spaces.
Output Specification:
For each query, print in a line yes
if the given sequence does correspond to a DFS sequence, or no
if not.
Sample Input:
5 7 6
1 2
1 3
1 5
2 5
3 2
4 3
5 4
1 5 4 3 2
1 3 2 5 4
1 2 5 4 3
1 2 3 4 5
4 3 2 5 1
5 4 3 2 5
Sample Output:
yes
yes
yes
no
yes
no
#include<iostream>
#include<unordered_set>
#include<queue>
#include<cstring>
#include<vector>
using namespace std;
const int N = 1010,M = 10010;
int n,m,k;
bool g[N][N],st[N],suc = true;
int seq[N];
vector<int> v[N];
queue<int> q;
void dfs(int x){
if(!suc||q.empty()) return ;
st[x] = true;
while(!q.empty()){
if(g[x][q.front()]){
int y = q.front();
q.pop();
dfs(y);
}else{
auto &vx = v[x];
for(int i = 0;i<vx.size();i++){
if(!st[vx[i]]){
suc = false;
return ;
}
}
return;
}
}
}
int main(){
cin>>n>>m>>k;
for(int i = 0;i<m;i++){
int a,b;
cin>>a>>b;
g[a][b] = true;
v[a].push_back(b);
}
while(k--){
memset(st,0,sizeof st);
suc = true;
while(q.size()) q.pop();
unordered_set<int> ss;
for(int i = 0;i<n;i++){
int x;cin>>x;
ss.insert(x);
q.push(x);
}
while(q.size()){
int x = q.front();
q.pop();
dfs(x);
}
if(!suc||ss.size()!=n)puts("no");
else puts("yes");
}
}