#include <bits/stdc++.h> using namespace std; void addedge(vector<vector<int>> &adj, int…
- User
#include <bits/stdc++.h> using namespace std;
void add_edge(vector<vector> &adj, int u, int v) { adj[u].push_back(v); }
bool dfs(vector<vector> &adj, vector &vis, int start, int node) { vis[node] = true; bool can_loop_back = false;
codefor (int it : adj[node]) { if (!vis[it]) { if (dfs(adj, vis, start, it)) { can_loop_back = true; } } else if (it == start && all_of(vis.begin(), vis.end(), [](bool v){ return v; })) { can_loop_back = true; } } return can_loop_back;}
int main() { int n, m; cin >> n >> m; vector<vector> adj(n);
codefor (int i = 0; i < m; i++) { int u, v; cin >> u >> v; add_edge(adj, u - 1, v - 1); } vector<bool> vis(n, false); bool result = dfs(adj, vis, 0, 0); if (result) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0;}
Tejas stands at the entrace of A4, confused, as all first years are, where do these hallways of Vindhya lead to? He holds the map of the entire building in the form of a graph and wants to know that if he does take a wrong turn, will he be able to reach back after exploring all the rooms or not? Formally, he has a directed graph with N nodes and M edges. Starting from node 1, he wants to know whether he can visit all the nodes and then return to node 1 or not? 3.1 Input format The first line contains N and M, the number of nodes and edges respectively. Next M lines contain 2 integer, u and v denoting there is a directed edge from node u to node v. 3.2 Output format Print ”YES” (without quotes) if it is possible for Tejas to go to all rooms of Vindhya and back to A4 entrance and ”NO” (without quotes) otherwise. 3.3 Constraints All cases: 1 ≤ M ≤ min( N∗(N−1) 2 , 106 ) Subtask 1(5 points): N ≤ 10 Subtask 2(25 points): N ≤ 103 Subtask 3(70 points): N ≤ 105
- Assistant
- User
#include <bits/stdc++.h> using namespace std;
void add_edge(vector<vector> &adj, int u, int v) { adj[u].push_back(v); }
bool dfs(vector<vector> &adj, vector &vis, int start, int node) { vis[node] = true; bool can_loop_back = false;
codefor (int it : adj[node]) { if (!vis[it]) { if (dfs(adj, vis, start, it)) { can_loop_back = true; } } else if (it == start && all_of(vis.begin(), vis.end(), [](bool v){ return v; })) { can_loop_back = true; } } return can_loop_back;}
int main() { int n, m; cin >> n >> m; vector<vector> adj(n);
codefor (int i = 0; i < m; i++) { int u, v; cin >> u >> v; add_edge(adj, u - 1, v - 1); } vector<bool> vis(n, false); bool result = dfs(adj, vis, 0, 0); if (result) { cout << "YES" << endl; } else { cout << "NO" << endl; } return 0;} why is this code wrong
- Assistant