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

bool hasCycle(int s, vector<bool> &visited, vector<vector<int>> &adjList)
{
	if(visited[s]){
		return true;
		cout << s << endl;
	}
	if(!visited[s]){
		visited[s]=true;
		for(auto i=adjList[s].begin(); i!=adjList[s].end(); i++){
			if(!visited[*i])
				if(hasCycle(*i, visited, adjList))
				    return true;
		}
	}
	return false;
}

int main() {
	int m, n;
	cin >> m >> n;
	if(m-1 != n){
		cout << "NO" << endl;
		return 0;
	}
	vector<vector<int>> adjList(m+1);
	int a, b;
	for(int i=1; i<=m; i++){
		cin >> a >> b;
		adjList[a].push_back(b);
		adjList[b].push_back(a);
	}
	vector<bool> visited(m+1, false);
	int start = a;
    if(hasCycle(start, visited, adjList))
        cout << "NO" <<endl;
    else
        cout << "YES" << endl;
	return 0;
}

Generated URL:

Output:

YES
Report Bug