Codeforces 1209D

有k人,每個人都想得到n中物品中的兩件,如果一個人一件都沒有得到,那麼就會不高興,求不高興的人數。
把物品看成點,人看成邊,如果一個點被訪問過,那麼一定有一個人被滿足了
如果一個連通分量有m個點,無論有多少條邊,只能最多有m-1條邊是第一次訪問這些點的,也就是隻有m-1個人能被滿足,所有人數減去被滿足的人數即答案

#include<bits/stdc++.h>
using namespace std;
#define f first
#define s second
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
const int N = 2e5 + 10;
int n,k,x,y,vis[N];
int h[N],to[N*2],nt[N*2],cnt;
void add(int x,int y){
	to[++cnt] = y ;
	nt[cnt] = h[x];
	h[x] = cnt;
}
void dfs(int u,int fa){
	cnt++;
	vis[u] = 1;
	for(int i = h[u] ; i ; i = nt[i]){
		int v = to[i];
		if(v == fa) continue;
		if(!vis[v]) dfs(v,u);
	}
}
int main(){
	ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	//freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	cin>>n>>k;
	int ans = k ;
	for(int i = 0 ; i < k ; i++) {
		cin>>x>>y;
		add(x,y);
		add(y,x);
	}
	for(int i = 1; i <= n ;i ++)
		if(!vis[i]) {
			cnt = 0 ;
			dfs(i, -1);
			ans -= (cnt - 1);
		}
	cout<<ans<<endl;
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章