D. Cow and Snacks
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!
There are ?n snacks flavors, numbered with integers 1,2,…,?1,2,…,n. Bessie has ?n snacks, one snack of each flavor. Every guest has exactly two favorite flavors. The procedure for eating snacks will go as follows:
- First, Bessie will line up the guests in some way.
- Then in this order, guests will approach the snacks one by one.
- Each guest in their turn will eat all remaining snacks of their favorite flavor. In case no favorite flavors are present when a guest goes up, they become very sad.
Help Bessie to minimize the number of sad guests by lining the guests in an optimal way.
Input
The first line contains integers ?n and ?k (2≤?≤1052≤n≤105, 1≤?≤1051≤k≤105), the number of snacks and the number of guests.
The ?i-th of the following ?k lines contains two integers ??xi and ??yi (1≤??,??≤?1≤xi,yi≤n, ??≠??xi≠yi), favorite snack flavors of the ?i-th guest.
Output
Output one integer, the smallest possible number of sad guests.
题意就是,我们有N个小吃还有K个顾客,我们要最多的让所有顾客满意,问的是最少的不满意数,其中只要吃了一个自己喜欢的食物就算是满意了,并且会把所有自己喜欢吃的食物吃完(不留给后人)。
然后,这里就是并查集去维护一下,因为任意相关联的x个食物,最多分配给(x-1)个人,所以,我们求这样的个数即可。
几个测试样例:
5 4
1 2
1 2
2 3
4 5
ans:1
2 2
1 2
1 2
ans:1
4 4
1 2
3 4
1 4
3 4
ans:1
My Code:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define efs 1e-6
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(x, y) make_pair(x, y)
using namespace std;
typedef double lb;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 2e5 + 7;
int N, K, du[maxN] = {0}, peo[maxN][2], ans = 0, root[maxN], siz[maxN] = {0};
int fid(int x) { return x == root[x] ? x : root[x] = fid(root[x]); }
bool vis[maxN] = {false};
set<int> st;
set<int>::iterator it;
void mix(int x, int y)
{
int u = fid(x), v = fid(y);
if(u != v)
{
root[u] = v;
siz[v] += siz[u];
}
}
int main()
{
scanf("%d%d", &N, &K); //N个事物、K个顾客
int ans = 0;
for(int i=1; i<=N; i++) root[i] = i;
for(int i=1; i<=N; i++) siz[i] = 1;
for(int i=1, xi, yi; i<=K; i++)
{
scanf("%d%d", &xi, &yi);
mix(xi, yi);
}
for(int i=1, u; i<=N; i++)
{
u = fid(i);
if(vis[u]) continue;
vis[u] = true;
ans += siz[u] - 1;
}
printf("%d\n", K - ans);
return 0;
}