题意:n个点m条边,现在要把这些边变为单向,求没有边连入的最少的点。
题解:并查集
对于并查集,其实就是一棵树,从根节点往下,那么只有根节点没有边连入,但是对于自环来说,并不存在这样的点。所以只要判断一下在构成集合的时候是否存在自环即可,若存在自环,则将根节点标记。
最后答案就是不存在自环的集合数量。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int Max = 1e5 + 5;
int Parent[Max], Rank[Max], rep[Max];
int Find(int x) {
return Parent[x] == x ? x : Parent[x] = Find(Parent[x]);
}
void Union(int x, int y) {
int u, v, root;
u = Find(x);
v = Find(y);
if (u == v) {
rep[u] = 1;
return;
}
if(rep[u] == 1) rep[v] = rep[u];
root = Parent[u] = v;
//return root;
}
int n, m, u, v;
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) Parent[i] = i;
for (int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
Union(u, v);
}
int num = 0;
for (int i = 1; i <= n; i++) {
if (Parent[i] == i && !rep[i]) num++;
}
printf("%d\n", num);
return 0;
}