NH tree

Problem C: NH tree
Time limit: 1 Sec Memory Limit: 128 MB
[submit] [state]
title description
Xiaoming finally busy playing a variety of courses, can finally continue the learning algorithm.
He saw the tree on graph theory book, the tree has many special properties. Xiao Ming suddenly in love with this special tree.
So he invented his own non-scoring methods for directed graph.
No definition of a fraction of the graph, the number of blocks each of communicating tree.
Now given a free edges m n points to FIG asked at Xiaoming scoring method a score of how much.
A communication block tree, if and only if the number of sides less than 1 point.

Input
of the first row two integers n and m, represent the points and edges FIG.
The second row has m pairs of integers, u and v represent, there is an edge between node u and node v.
No weight given the absence of edges to the graph.

Output
output line comprises an integer representing the FIG no ratings, i.e., the number of trees.
Sample input the Copy
. 8. 6
. 1 2
. 1. 3
2. 4
. 5. 6
. 6. 7
. 5. 7
sample output the Copy
2
Tip
20% of the data,. 1 <= n-<2000 =
100% of the data, 1 <= n <= 100000,0 <= m <= min (n * (n-1) / 2,200000)

#include <iostream>
#include <cstdio>
#include <queue>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
const int M = 100005;

vector<int>v[M];
int n,m;
bool vis[M],flag;

void dfs(int x,int last){
    vis[x] = 1;
    
    for(int i=0; i<v[x].size(); i++){
        if(vis[v[x][i]]){
            if(v[x][i]!=last)
                flag = true; // 我们就认为连通图中存在环,不是树
        }
        else
            dfs(v[x][i],x);
    }
}
int main()
{
    cin >> n >> m;
    int x,y;
    while(m--){
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    int ans = 0;
    for(int i=1; i<=n; i++){
        if(!vis[i]){
            flag = false;
            dfs(i,-1);
            if(!flag)
                ans++;
        }
    }
    cout << ans << endl;
    return 0;
}


发布了62 篇原创文章 · 获赞 0 · 访问量 1761

Guess you like

Origin blog.csdn.net/jhckii/article/details/104236316