F Call to your teacher [DFS+BFS] in the fourth practice competition of the national multi-school algorithmic winter vacation training camp in 2018

Title Description

When you come out of the lab, you suddenly find that you have left your computer in the lab, but the teacher of the lab has locked the door. To make matters worse, you don't have the teacher's telephone number. You start calling everyone you know, asking if they have a teacher's phone, and if not, they ask their classmates to ask for their phone number. So, can you contact the teacher and get the computer?

Input Description:

There are multiple sets of test samples
The first line of each set of samples is two integers n(1), respectively.

Output description:

For each set of test cases, if you finally get in touch with the teacher, output "Yes" or "No".

Example 1

input

5 5
1 3
2 3
3 4
2 4
4 5

output

Yes

Example 2

input

4 3
1 2
2 3
4 1

output

No

Topic: Brief

Analysis: We can use the adjacency table to build the map, search it directly, and then see if n points have been visited, or BFS layer-by-layer access can also be done.

DFS reference code

#include <bits/stdc++.h>
using namespace std;

vector<int> E[51];
bool vis[55];
int n,m;
bool flg = false;

void dfs(int idx) {
    for(int i = 0;i < E[idx].size();i++) {
        if(vis[E[idx][i]]) continue;
        vis[E[idx][i]] = true;
    }
}
int main() {
    while(cin>>n>>m) {
        for(int i = 0;i < 51;i++) E[i].clear();
        memset(vis,0,sizeof vis);
        for(int i = 0;i < m;i++) {
            int a,b;cin>>a>>b;
            E[a].push_back(b);
        }
        flg = false;
        dfs(1);
        if(vis[n]) cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
    return 0;
}

BFS reference code

#include <bits/stdc++.h>
using namespace std;

vector<int> E[51];
bool vis[51];
int n,m;
bool flg = false;

int main() {
    while(cin>>n>>m) {
        for(int i = 0;i < 51;i++) E[i].clear();
        memset(vis,false,sizeof vis);
        for(int i = 0;i < m;i++) {
            int a,b;cin>>a>>b;
            E[a].push_back(b);
        }
        flg = false;
        vis[1] = true;
        queue<int> q;
        q.push(1);
        while (!q.empty()) {
            int t = q.front();
            q.pop();
            for(int i = 0;i < E[t].size();i++) {
                if(E[t][i] == n) {
                    flg = true;
                    break;
                } else {
                    if(vis[E[t][i]]) continue;
                    else {
                        q.push(E[t][i]);
                    }
                }
            }
            if(flg) break;
        }
        if(flg) cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
    return 0;
}
  • If there are errors or omissions, please talk about UP, thx in private

Posted by sujithtomy on Wed, 06 Feb 2019 13:09:17 -0800