题解:AT_abc466_c [ABC466C] Count Close Pairs

· · 题解

题目链接:AT_abc466_c

C 就出交互题何意味。

题目大意

已知数轴上有 N 个点,从左到右分别编号为 1,2,\cdots,N。现在你能够提出至多 2N 次问题,设 \text{dist}(i,j) 表示编号为 i,j 的点之间的距离,你每次可以知道 \text{dist}(i,j) 是否大于 1。

求有多少个点对之间的距离不超过 1。

大致思路

点的编号是从左往右单调递增的,故考虑双指针,枚举右端点 R,相应地移动左端点 L,在此过程中处理答案。

具体地,初始时我们令 L=1,R=2。接下来对于每个 R,先不断让 L 自增,直至 \text{dist}(L,R)\le 1 或 L=R。此时编号为 [L,R-1] 的点均能与 R 形成合法的点对,故答案增加 R-L。最后 R\leftarrow R+1,以尝试下一个右端点。

最终代码

#include <bits/stdc++.h>
using namespace std;
int n,ans;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin>>n;
    int l=1;
    for(int r=2;r<=n;r++)
    {
        while(l<r)
        {
            cout<<"? "<<l<<' '<<r<<endl;
            string s;cin>>s;
            if(s=="Yes") break;
            l++;
        }
        ans+=r-l;
    }
    cout<<"! "<<ans<<endl;
    return 0;
}

时间复杂度:\mathcal{O}(n)
空间复杂度:\mathcal{O}(1)