CodeForces1209 D.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 nsnacks 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.
Examples
    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.

题意就是,给出零食的个数和人数,每个人有两种喜欢吃的零食,如果这两种都吃不到他就会很伤心,问最少的伤心的人的个数。

很巧妙的思想,用到了并查集

思想: 遍历所有的人爱吃的两种零食,如果这两种零食在不同的集合里,就证明这两种零食至少可以吃一种(也有可能两种都能吃),如果这两种零食在相同的集合里,就证明这两种零食都被吃了,伤心的人数就加一,然后不论以上两种情况中的哪一种,都把两种零食加入同一个集合里,表明他们都被吃了。


//主要思路如下
int pre[maxn], ans, n, k;

void init() {
    for (int i = 1; i <= n; i++) {
        pre[i] = i;
    }
}

int fin(int x) {
    if (x == pre[x])
        return x;
    else
        return pre[x] = fin(pre[x]);
}

bool merge(int a, int b) {
    if (pre[a] != b) {
        pre[a] = b;
        return true;
    }
    return false;
}

void solve() {
    ans = 0;
    for (int i = 0; i < k; i++) {
        int a, b;
        cin >> a >> b;
        a = fin(a), b = fin(b);
        //cout << a << " " << b << endl;
        if (a == b) {
            ans++;
        }
        else
        pre[a] = b;
    }
}

 

题目还有一种做法,dfs求连通分量个数,以后再看
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值