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

bool hasCycle(int s, int p, vector<bool> &visited, vector<vector<int>> &adjList)
{
	visited[s]=true;
	for(auto i=adjList[s].begin(); i!=adjList[s].end(); i++){
	    if(*i == p) continue; // Can't generate a cycle with it's parent
		if(!visited[*i]){
			if(hasCycle(*i, s, visited, adjList))
			    return true;
		}
		else{
		    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<=n; 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,0, visited, adjList)){
        cout << "NO" <<endl;
    }
    else{
        cout << "YES" << endl;
    }
	return 0;
}

Generated URL:

Output:

NO
Report Bug