Advertisement
dyamondz

Bosc - X41530

Nov 29th, 2018
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. typedef vector<int> Vec;
  6. typedef vector<Vec> Matrix;
  7.  
  8. Matrix graph;
  9.  
  10. bool cycle(vector< vector<int> >& g, int parent, int  u, vector<bool>& visited){
  11.         if(visited[u]) return true;
  12.         else{
  13.             visited[u]=true;
  14.             for(int v : g[u]){
  15.                 if (v != parent and  cycle(g, u, v, visited)) return true;
  16.             }
  17.         }
  18.         return false;
  19. }
  20.  
  21. int main(){
  22.     int n,m;
  23.     while(cin>>n){
  24.         cin>>m;
  25.         graph = Matrix(n);
  26.        
  27.         int x,y;
  28.         for(int i=0; i<m; ++i){
  29.             cin>>x>>y;
  30.             graph[x].push_back(y);
  31.             graph[y].push_back(x);
  32.         }
  33.         int trees=0;
  34.         bool has_cycle=false;
  35.  
  36.         vector<bool> visited(n,false);
  37.         for(int i=0; i<n; ++i){
  38.             if(!visited[i]){
  39.                 if(!cycle(graph,-1,i,visited)) ++trees;
  40.                 else has_cycle = true;
  41.             }
  42.         }
  43.         if(has_cycle) cout<<"no"<<endl;
  44.         else cout<<trees<<endl;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement