跳到正文

题解

CF420C Bug in Code

GlenBzc约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年8月9日
篇幅
约 3 分钟
获赞
2
题目
CF420C

版本

  1. v1当前

首先大致看了看题面,一眼二分,可以开个桶数组 aa 存每个人被怀疑的次数,排个序,因为需要 xx ,yy 两个人被怀疑的次数之和大于等于 pp ,所以我们可以遍历桶数组,每次用 lower_bound() 或者手动二分找到第一个符合 a[i]+a[j]≥p a[i] + a[j] \ge p 的索引 jj ,答案 ansans 就可以直接加上 (n−j+1)(n - j + 1 ) 。

代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
signed main()
{
    int n,p;cin>>n>>p;
    int a[n+1];
    memset(a,0,sizeof(a));
    for(int i=1;i<=n;i++)
    {
          int x,y;cin>>x>>y;
          a[x]++;a[y]++;
    }
    long long ans=0;   
    sort(a+1,a+1+n);
    for(int i=1;i<=n;i++)
    {
        int j=lower_bound(a+1+i,a+1+n,(p-a[i]))-a;
        ans+=(n-j+1);
    }
    cout<<ans<<endl;
    return 0;
}

然而 Wrong answer on test 6 …
仔细一想发现不对,因为可能有重复的情况也就是多个人怀疑的一样,所以我们可以在排序前预处理一下。

代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
map<pair<int,int>,int> mp;
signed main()
{
   int n,p;cin>>n>>p;
    int a[n+1];
    memset(a,0,sizeof(a));
    mp.clear();
    for(int i=1;i<=n;i++)
    {
        int x,y;cin>>x>>y;
        if(x>y)swap(x,y);//别忘了swap,因为1,2和2,1是一样的
        a[x]++;a[y]++;
        mp[{x,y}]++;
    }
    long long ans=0;   
    for(auto i=mp.begin();i!=mp.end();i++)
    {
        if(a[i->first.first]+a[i->first.second]>=p&&a[i->first.first]+a[i->first.second]-i->second<p)
        {
            ans--;
        }
    }
    sort(a+1,a+1+n);
    for(int i=1;i<=n;i++)
    {
        int j=lower_bound(a+1+i,a+1+n,(p-a[i]))-a;
        ans+=(n-j+1);
    }
        cout<<ans<<endl;
	return 0;
}

时间卡的有点紧,可以开个读入优化。

原文