codeforces1209——D.Cow and Snacks(并查集)

简介: codeforces1209——D.Cow and Snacks(并查集)

原题链接

题意:

n种食物,一种食物只有一个,m个人,每个人有两种喜欢吃的食物。每个人来的时候会把喜欢吃的未被吃过的食物都吃掉,如果吃不到食物的话就会难过,适当安排序列,使得难过的人最少,并输出该数量。

思路:

读错题了,以为是匹配。本题中人可能不止吃一个食物。

考虑把食物看成节点,第一个来的人肯定是吃两个食物,这就构成了一条边。以后每来一个人,如果两个喜欢的食物在一个连通块里的话,说明都被以前的人吃了,他就会不开心;否则,就一定会有食物吃。

用并查集维护就好了。

代码:

#pragma GCC optimize(3)
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll>PLL;
typedef pair<int,int>PII;
typedef pair<double,double>PDD;
#define I_int ll
inline ll read()
{
    ll x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
char F[200];
inline void out(I_int x) {
    if (x == 0) return (void) (putchar('0'));
    I_int tmp = x > 0 ? x : -x;
    if (x < 0) putchar('-');
    int cnt = 0;
    while (tmp > 0) {
        F[cnt++] = tmp % 10 + '0';
        tmp /= 10;
    }
    while (cnt > 0) putchar(F[--cnt]);
    //cout<<" ";
}
ll ksm(ll a,ll b,ll p){ll res=1;while(b){if(b&1)res=res*a%p;a=a*a%p;b>>=1;}return res;}
const ll inf = 0x3f3f3f3f3f3f3f3f;
const int maxn=1e6+100,N=1e6+100;
const double PI = atan(1.0)*4;
const double eps=1e-6;
int root[maxn],cnt=0,n,m;
int Find(int x){
    if(x!=root[x]) root[x]=Find(root[x]);
    return root[x];
}
void Union(int u,int v){
    u=Find(u),v=Find(v);
    if(u!=v){
        cnt++;
        root[u]=v;
    }
}
int main(){
    n=read(),m=read();
    for(int i=1;i<=n;i++) root[i]=i;
    for(int i=1;i<=m;i++){
        int u=read(),v=read();
        Union(u,v);
    }
    out(m-cnt);
    return 0;
}
目录
相关文章
|
8月前
codeforces 272C. Dima and Staircase(线段树)
题目很长,看加猜加谷歌翻译才看懂了题目。每级台阶的宽都是1,但高不同,并且告诉你了,然后给你m个箱子,长和宽都告诉你,把箱子靠左放,求箱子的底部有多高。
19 0
|
8月前
华为机试HJ44:Sudoku(数独问题,深度优先遍历DFS解法)
华为机试HJ44:Sudoku(数独问题,深度优先遍历DFS解法)
|
10月前
UVa872 - Ordering(拓扑排序)
UVa872 - Ordering(拓扑排序)
49 0
|
8月前
|
C++
poj 2182 Lost Cows(树状数组)
FJ有n头牛,现在它们排成一排,每一头牛都有一个不同的编号(1-n),现在知道从第二头牛开始每头牛左边比自己编号小的牛的数目,让你确定每头牛的编号。
25 0
|
10月前
UVa302 - John's trip(并查集、欧拉回路、DFS)
UVa302 - John's trip(并查集、欧拉回路、DFS)
38 0
AtCoder Beginner Contest 216 G - 01Sequence (并查集 贪心 树状数组 差分约束)
AtCoder Beginner Contest 216 G - 01Sequence (并查集 贪心 树状数组 差分约束)
119 0
codeforces1253——D. Harmonious Graph(并查集)
codeforces1253——D. Harmonious Graph(并查集)
72 0
Codeforces1153——D. Serval and Rooted Tree(思维好题+dfs+贪心)
Codeforces1153——D. Serval and Rooted Tree(思维好题+dfs+贪心)
102 0
Codeforces1153——D. Serval and Rooted Tree(思维好题+dfs+贪心)
|
人工智能
洛谷P1569-Generic Cow Protests(一维区间DP)
洛谷P1569-Generic Cow Protests(一维区间DP)
洛谷P1569-Generic Cow Protests(一维区间DP)
|
人工智能 Java
[HDU 7136] Jumping Monkey | 并查集 | 逆向思维
Jumping Monkey Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others) Total Submission(s): 747 Accepted Submission(s): 360
194 0
[HDU 7136] Jumping Monkey | 并查集 | 逆向思维

热门文章

最新文章