#include<bits/stdc++.h> usingnamespace std; using ll=longlong; voidsolve() { ll n; cin>>n; int m,q; cin>>m>>q; std::vector<ll> b(m,0); for (int i = 0; i < m; ++i) { cin>>b[i]; } sort(begin(b),end(b)); for (int i = 0; i < q; ++i) { int a; cin>>a; if(a>b[m-1]) { cout<<n-b[m-1]<<"\n"; continue; } elseif(a<b[0]) { cout<<b[0]-1<<"\n"; continue; } else { int pos=lower_bound(begin(b),end(b),a)-begin(b); //直接找第一个大于的位置 int l=b[pos-1],r=b[pos]; cout<<(r-l)/2<<"\n"; } } } intmain() { int t; cin>>t; for (int i = 1; i <= t ; ++i) { //cout<<"case "<<i<<": "<<"\n"; solve(); } return0; }
Code 2
我手写的二分,比较复杂。
#include<bits/stdc++.h> usingnamespace std; using ll=longlong; voidsolve() { ll n; cin>>n; int m,q; cin>>m>>q; std::vector<ll> b(m,0); for (int i = 0; i < m; ++i) { cin>>b[i]; } sort(begin(b),end(b)); for (int i = 0; i < q; ++i) { int a; cin>>a; if(a>b[m-1]) { cout<<n-b[m-1]<<"\n"; continue; } elseif(a<b[0]) { cout<<b[0]-1<<"\n"; continue; } else { int l=0,r=m-1; while(l+1<r) { int mid=(l+r)>>1; if(b[mid]<=a) { l=mid; } else { r=mid-1; } } int pos=l; if(b[pos]<a) { if(pos+1<m) { //cerr<<"case 1: "; cout<<(b[pos+1]-b[pos])/2<<"\n"; } else { //cerr<<"case 2: "; cout<<n-b[pos]<<"\n"; } } else { if(pos>0) { //cerr<<"case 3: "; cout<<(b[pos]-b[pos-1])/2<<"\n"; } else { //cerr<<"case 4: "; cout<<b[pos]-1<<"\n"; } } }
} } intmain() { int t; cin>>t; for (int i = 1; i <= t ; ++i) { //cout<<"case "<<i<<": "<<"\n"; solve(); } return0; }