1 or 2(dfs求联通块)
题目描述
There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.
Let Ai be the integer written on the i-th card.
Your objective is to guess A1,A2,…,AN correctly.
You know the following facts:
For each i=1,2,…,M, the value A Xi+A Yi+Zi is an even number.
You are a magician and can use the following magic any number of times:
Magic: Choose one card and know the integer Ai written on it. The cost of using this magic is 1.
What is the minimum cost required to determine all of A1,A2,…,AN?
It is guaranteed that there is no contradiction in given input.
Let Ai be the integer written on the i-th card.
Your objective is to guess A1,A2,…,AN correctly.
You know the following facts:
For each i=1,2,…,M, the value A Xi+A Yi+Zi is an even number.
You are a magician and can use the following magic any number of times:
Magic: Choose one card and know the integer Ai written on it. The cost of using this magic is 1.
What is the minimum cost required to determine all of A1,A2,…,AN?
It is guaranteed that there is no contradiction in given input.
Constraints
·All values in input are integers.
·2≤N≤105
·1≤M≤105
·1≤Xi<Yi≤N
·1≤Zi≤100
·The pairs (Xi,Yi) are distinct.
·There is no contradiction in input. (That is, there exist integers A1,A2,…,AN that satisfy the conditions.)
输入
Input is given from Standard Input in the following format:
N M
X1 Y1 Z1
X2 Y2 Z2
⋮
XM YM ZM
输出
Print the minimum total cost required to determine all of A1,A2,…,AN.
样例输入 Copy
3 1
1 2 1
样例输出 Copy
2
提示
You can determine all of A1,A2,A3 by using the magic for the first and third cards.
思路:多个数联通起来,只要我们知道了其中一个数,其他的数就可以推出来了。
所以是一个求联通块的题。
#pragma GCC optimize(3 , "Ofast" , "inline")
#include <bits/stdc++.h>
#define rep(i , a , b) for(register int i=(a);i<=(b);i++)
#define rop(i , a , b) for(register ll i=(a);i<(b);i++)
#define per(i , a , b) for(register ll i=(a);i>=(b);i--)
#define por(i , a , b) for(register ll i=(a);i>(b);i--)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll , ll> pi;
const int maxn = 2e5+10;
vector<int>e[maxn];
int vis[maxn];
template<class T>
inline void read (T &x) {
x = 0;
int sign = 1;
char c = getchar ();
while (c < '0' || c > '9') {
if ( c == '-' ) sign = - 1;
c = getchar ();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar ();
}
x = x * sign;
}
void dfs(int x) {
int siz = e[x].size ();
vis[x]=1;
rep (i,0,siz-1) {
int v = e[x][i];
if(vis[v]) continue;
dfs (v);
}
}
int main () {
int n,m;
read (n);
read (m);
rep (i,1,m) {
int u,v,w;
read (u);read (v);read (w);
e[u].push_back (v);
e[v].push_back (u);
}
int ans = 0;
rep (i,1,n) {
if(!vis[i]) {
dfs(i);
ans++;
}
}
cout<<ans<<endl;
return 0;
}