Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- typedef vector<int> Vec;
- typedef vector<Vec> Matrix;
- Matrix graph;
- bool cycle(vector< vector<int> >& g, int parent, int u, vector<bool>& visited){
- if(visited[u]) return true;
- else{
- visited[u]=true;
- for(int v : g[u]){
- if (v != parent and cycle(g, u, v, visited)) return true;
- }
- }
- return false;
- }
- int main(){
- int n,m;
- while(cin>>n){
- cin>>m;
- graph = Matrix(n);
- int x,y;
- for(int i=0; i<m; ++i){
- cin>>x>>y;
- graph[x].push_back(y);
- graph[y].push_back(x);
- }
- int trees=0;
- bool has_cycle=false;
- vector<bool> visited(n,false);
- for(int i=0; i<n; ++i){
- if(!visited[i]){
- if(!cycle(graph,-1,i,visited)) ++trees;
- else has_cycle = true;
- }
- }
- if(has_cycle) cout<<"no"<<endl;
- else cout<<trees<<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement