Codeforces Round #584 D. Cow and Snacks

链接:

https://codeforces.com/contest/1209/problem/D

题意:

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.

思路:

考虑将零食看成点, 每个牛看成边,用边将喜欢的两点连起来, 如果x个边连成一个环,不管环内的谁先取最多只有x-1.
建图DFS.

代码:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5+10;

int n, k;
vector<int> G[MAXN];
int Vis[MAXN], l[MAXN], r[MAXN];
int cnt;

void Dfs(int u)
{

    Vis[u] = 1;
    for (int i = 0;i < G[u].size();i++)
    {
        if (Vis[G[u][i]])
            continue;
        cnt++;
        Dfs(G[u][i]);
    }
}

int main()
{
    cin >> n >> k;
    int u, v;
    for (int i = 1;i <= k;i++)
    {
        cin >> u >> v;
        G[u].push_back(v);
        G[v].push_back(u);
        l[i] = u, r[i] = v;
    }
    for (int i = 1;i <= k;i++)
    {
        if (!Vis[l[i]])
            Dfs(l[i]);
        if (!Vis[r[i]])
            Dfs(r[i]);
    }
    cout << k-cnt << endl;

    return 0;
}
posted @ 2019-10-10 01:20  YDDDD  阅读(228)  评论(0编辑  收藏  举报