CF420C Bug in Code

· · 题解

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

代码如下:

#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 ...
仔细一想发现不对,因为可能有重复的情况也就是多个人怀疑的一样,所以我们可以在排序前预处理一下。

代码如下:

#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;
}

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