1. 程式人生 > 其它 >codeforces 252 C. Points on Line 列舉+思維

codeforces 252 C. Points on Line 列舉+思維

要求最遠的不能超過d;

又因為保證了遞增

那我們固定一個點,找到數列裡第一個剛好<=該點+d的位置

然後區間中任意挑兩個數都是合法的;

c(2,m)√

#

如何找到第一個剛好<=?

不手寫二分的話用

ll r=upper_bound(a+1,a+n+1,tmp)-a;
        r--;

注意是upper,和lower的區別是它可以==,我們要的就是==;

注意-=1;

#

到後面會溢位,沒開longlong見祖宗系列;

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[
100005]; int main( ) { ll n,d; ll ans=0; cin>>n>>d; for(ll i=1;i<=n;i++) { cin>>a[i]; } for(ll i=1;i<=n;i++) { ll tmp; tmp=a[i]+d; ll r=upper_bound(a+1,a+n+1,tmp)-a; r--; //cout<<r<<endl;
if(r<=n&&r-i>=2&&a[r]-a[i]<=d) { ans+=(r-i)*(r-i-1)/2; //cout<<r<<" "<<i<<endl; } else if(r>n&&n-i>=2&&a[n]-a[i]<=d) { ans
+=(n-i)*(n-i-1)/2; //cout<<r<<" "<<i<<endl; } } /* 31 0 36 0 43 1 47 1 48 0 50 0 56 0 */ //cout<<a[i]<<" "<<tmp<<" "<<r<<endl cout<<ans; }