Codeforces Round #584 D. Cow and Snacks

1755 단어
링크:
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 
using namespace std;
const int MAXN = 1e5+10;

int n, k;
vector 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;
}

좋은 웹페이지 즐겨찾기