CodeForces-1209D-Cow and Snacks (并查集)

CodeForces-1209D-Cow and Snacks

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,…,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≤n≤105, 1≤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≤xi,yi≤n, xi≠yi), favorite snack flavors of the i-th guest.

Output
Output one integer, the smallest possible number of sad guests.

Input
5 4
1 2
4 3
1 4
3 4
Output
1
Input
6 5
2 3
2 1
3 4
6 5
4 5
Output
0
Note
In the first example, Bessie can order the guests like this: 3,1,2,4. Guest 3 goes first and eats snacks 1 and 4. Then the guest 1 goes and eats the snack 2 only, because the snack 1 has already been eaten. Similarly, the guest 2 goes up and eats the snack 3 only. All the snacks are gone, so the guest 4 will be sad.

In the second example, one optimal ordering is 2,1,3,5,4. All the guests will be satisfied.

题目大意:

给N个甜品,有N个动物,每个动物都有对应的两个喜欢吃的甜品,让按照一定顺序吃甜品,吃到喜欢的甜品,动物就会高兴,否则动物会不高兴,求最小的不高兴的动物数量。

题目分析:

题目意思很容易理解,最开始的想法是找孤立点,然后找到最大的高兴动物数量,但发现有点太复杂了,于是画了个样例的图,发现可以用并查集写。题目比较简单,直接上代码。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define maxn 200005
#define INF 0x3f3f3f3f
using namespace std;
 
typedef long long ll;
 
int n, k, ans;
int x, y;
int pre[maxn];

int find(int x)
{
    int r = x;
    while(pre[r] != r)
        r = pre[r];
    int i = x;
    int j;
    while(i != r)
    {
        j = pre[i];
        pre[i] = r;
        i = j;
    }
    return r;
}

void join(int x, int y)
{
    int fx, fy;
    fx = find(x);
    fy = find(y);
    if(fx == fy)
        ans ++;
    else
    {
        pre[fx] = fy;
    }  
}

int main()
{
    while(cin >> n >> k)
    {
        for(int i = 0; i < n; i ++)
            pre[i] = i;
        ans = 0;
        for(int i = 0; i < k; i ++)
        {
            cin >> x >> y;
            join(x, y);
        }
        cout << ans << endl;
    }
    return 0;
}

你可能感兴趣的:(CF练习记录)