codeforces 421D-Bug in Code(容斥)

这篇博客探讨了一种处理投票数据的问题,其中每个人可以投票给两个人。文章详细介绍了如何通过排序和二分查找来计算投票对数,并解决重复投票的去重问题。作者使用了容斥原理来精确计算满足条件的投票对数,并给出了相应的C++代码实现。
摘要由CSDN通过智能技术生成

传送门

题意:

n n n个人,每个人都投票给了两个人,求有多少对 ( x , y ) (x,y) (xy) 满足其投票数相加 ≥ p \geq p p

题解:

按投票数排序,二分求出 c n t [ x ] + c n t [ y ] ≥ p cnt[x]+cnt[y] \geq p cnt[x]+cnt[y]p 的个数。

但是难点在于去重,比如对于 ( 1 , 2 ) (1,2) (1,2) ,假如只有一个人投票给了 ( 1 , 2 ) (1,2) (1,2) ,其他人都没有投给1,2 ,那么计算出来的 c n t [ 1 ] + c n t [ 2 ] = 2 cnt[1]+cnt[2] = 2 cnt[1]+cnt[2]=2 ,但实际上为 1 1 1. 所以要求出 c n t [ x ] + c n t [ y ] − m p [ x , y ] ≥ p cnt[x]+cnt[y] -mp[x,y] \geq p cnt[x]+cnt[y]mp[x,y]p的对数

所以考虑容斥,先求出所有 c n t [ x ] + c n t [ y ] ≥ p cnt[x]+cnt[y] \geq p cnt[x]+cnt[y]p 的对数,再去求出满足 c n t [ x ] + c n t [ y ] ≥ p cnt[x]+cnt[y] \geq p cnt[x]+cnt[y]p的条件下, c n t [ x ] + c n t [ y ] − m p [ x , y ] < p cnt[x]+cnt[y]-mp[x,y] < p cnt[x]+cnt[y]mp[x,y]<p 的对数,然后减去即可。因为最多只有 n n n m p [ x , y ] mp[x,y] mp[x,y]​ ,所以遍历一遍即可。

代码:

#pragma GCC diagnostic error "-std=c++11"
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<set>
#include<ctime>
#define iss ios::sync_with_stdio(false)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int,int> pii;
const int mod=1e9+7;
const int MAXN=3e5+5;
const int inf=0x3f3f3f3f;
int vis[MAXN];
map<pii,int>mp;
int a[MAXN];
int main()
{
    int n,p;
    cin>>n>>p;
    for(int i=1;i<=n;i++)
    {
        int u,v;
        cin>>u>>v;
        vis[u]++;
        vis[v]++;
        if(u>v) swap(u,v);
        mp[{u,v}]++;
    }
    for(int i=1;i<=n;i++)
    {
        a[i]=vis[i];
    }
    sort(a+1,a+1+n);
    ll ans=0;
    for(int i=1;i<=n;i++)
    {   
        int res=max(0,p-a[i]);
        int l=1,r=i-1;
        int pos=i;
        while(l<=r)
        {
            int mid=(l+r)>>1;
            if(a[mid]>=res)
            {
                pos=mid;
                r=mid-1;
            }
            else l=mid+1;
        }
        ans+=i-pos;
    }
    for(auto i:mp)
    {
        int u=i.first.first;
        int v=i.first.second;
        if(vis[u]+vis[v]>=p&&vis[u]+vis[v]-i.second<p){
            ans--;
        }
    }
    cout<<ans<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值