E. New Reform
time limit per test
memory limit per test
input
output
n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed
The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).
separate, if no road leads into it, while it is allowed to have roads leading from this city.
Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.
Input
n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).
m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the numbers of the cities connected by the i-th road.
It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.
Output
Print a single integer — the minimum number of separated cities after the reform.
Examples
input
4 3 2 1 1 3 4 3
output
1
input
5 5 2 1 1 3 2 3 2 5 4 3
output
0
input
6 5 1 2 2 3 4 5 4 6 5 6
output
1
遍历每个点,若该点未被访问,则从该点i开始搜索,搜出i能到达的所有点,打上标记,这些点都有边指向自己.现在就是判断有没有边指向i,若从i搜索出的连通图是环,或者i在搜索中有数次被访问则有边指向i,否则没有
#include <bits/stdc++.h>
#define maxn 100005
using namespace std;
typedef long long ll;
vector<int> v[maxn];
bool vis[maxn];
int cnt;
void dfs(int j, int f){
for(int i = 0; i < v[j].size(); i++){
int h = v[j][i];
if(h != f){
if(vis[h])
cnt = 1;
else{
vis[h] = true;
dfs(h, j);
}
}
}
}
int main(){
// freopen("in.txt", "r", stdin);
int n, m, a, b;
scanf("%d%d", &n, &m);
for(int i = 0; i < m; i++){
scanf("%d%d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
}
int ans = 0;
for(int i = 1; i <= n; i++){
if(vis[i] == false){
cnt = 0;
dfs(i, -1);
if(vis[i] == false && cnt == 0)
ans++;
}
}
cout << ans << endl;
return 0;
}