概述
A. New Reform
Berland has 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 that you can get from any city to any other one, using only the existing roads.
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).
In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered 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
The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).
Next 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
inputCopy
4 3
2 1
1 3
4 3
outputCopy
1
inputCopy
5 5
2 1
1 3
2 3
2 5
4 3
outputCopy
0
inputCopy
6 5
1 2
2 3
4 5
4 6
5 6
outputCopy
1
题目大意:
n个数,m组数据,无向图变有向图,问:变有向图后,有向图入度最少的点有多少个
思路:
入度为0最少点时,有环连环,环和环延伸出的路都没有入度为0的点。然后把剩余点连独立的路,每条独立路有一个入度为0的点(独立路中的点vis都为0)。
题外话:(老犯这个毛病,题意理解错了,夸夸写了一个多小时,写到绝望,吊死在一棵歪脖树上,我可长点心吧)
#include<iostream>
#include<cstdio>
#include<cmath>
#include<string>
#include<cstring>
#include<string.h>
#include<algorithm>
#include<set>
using namespace std;
int n,m;
int f[100001];
int vis[100001];
int findd(int z)
//并查集
{
if(f[z]==z)
return z;
else
return f[z]=findd(f[z]);
}
void emerge(int x,int y)
//并查集
{
int a=findd(x);
int b=findd(y);
if(a!=b)
{
f[a]=b;
if(vis[a]||vis[b]||vis[x]||vis[y] //路中没有vis等于1的点,有等于1的证明有环或环延伸出的路中的点,
//环延伸出的路也没有入度为0的点
{
//cout<<a<<b<<x<<y<<endl;
vis[a]=vis[b]=vis[x]=vis[y]=1;
}
}
else
//环
{
vis[a]=vis[y]=vis[b]=vis[x]=1;
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
f[i]=i;
}
for(int i=1;i<=m;i++)
{
int a,b;
cin>>a>>b;
emerge(a,b);
}
int num=0;
for(int i=1;i<=n;i++)
{
if(f[i]==i&&!vis[i])
//独立的路中,有一个点爹是自己,并且不在环中
{
num++;
//
cout<<i<<endl;
}
}
cout<<num<<endl;
return 0;
}
最后
以上就是闪闪鸡为你收集整理的【并查集】codeforces:New Reform的全部内容,希望文章能够帮你解决【并查集】codeforces:New Reform所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复