比赛链接:ABC364
全是二分?
#include <bits/stdc++.h>
using namespace std;
string S[105];
int main(){
int N;
cin>>N;
for(int i=1;i<=N;i++){
cin>>S[i];
if(S[i-1]=="sweet" && S[i]=="sweet" && i!=N){
cout<<"NO"<<endl;
return 0;
}
}
cout<<"YES"<<endl;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
char C[55][55];
int H,W;
bool check(int x,int y){
if(x>=1 && x<=H && y>=1 && y<=W && C[x][y]=='.')
return true;
return false;
}
int main(){
cin>>H>>W;
int Si,Sj;
cin>>Si>>Sj;
for(int i=1;i<=H;i++){
for(int j=1;j<=W;j++)
cin>>C[i][j];
}
string X;
cin>>X;
int x=Si,y=Sj;
for(int i=0;i<X.size();i++){
if(X[i]=='L' && check(x,y-1))
y--;
if(X[i]=='R' && check(x,y+1))
y++;
if(X[i]=='U' && check(x-1,y))
x--;
if(X[i]=='D' && check(x+1,y))
x++;
cout<<x<<' '<<y<<endl;
}
cout<<x<<' '<<y<<endl;
return 0;
}
二分。先求出和
的前缀和,然后用upper_bound二分即可。注意找不到的情况(如果找不到lower_bound和upper_bound会返回n+1)。
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn=200005;
int A[maxn],B[maxn],suma[maxn],sumb[maxn];
bool cmp(int x,int y){
return x>y;
}
signed main(){
int N,X,Y;
cin>>N>>X>>Y;
for(int i=1;i<=N;i++)
cin>>A[i];
sort(A+1,A+N+1,cmp);
for(int i=1;i<=N;i++)
suma[i]=suma[i-1]+A[i];
for(int i=1;i<=N;i++)
cin>>B[i];
sort(B+1,B+N+1,cmp);
for(int i=1;i<=N;i++)
sumb[i]=sumb[i-1]+B[i];
int x=upper_bound(suma+1,suma+N+1,X)-suma;
int y=upper_bound(sumb+1,sumb+N+1,Y)-sumb;
cout<<min(x,y)<<endl;
return 0;
}
还是二分。我们二分往两边的距离。如果这个范围内a的数量小于k,那就扩大范围,否则就缩小范围。
#include <bits/stdc++.h>
using namespace std;
int a[100005];
int main(){
int n,q;
cin>>n>>q;
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+1+n);
while(q--){
int b,k;
cin>>b>>k;
int l=0,r=2e8+5;
while(l<r){
int mid=(l+r)>>1;
int x=lower_bound(a+1,a+1+n,b-mid)-a;
int y=upper_bound(a+1,a+1+n,b+mid)-a;
if((y-x+1)>=k)
r=mid;
else
l=mid+1;
}
cout<<l<<endl;
}
return 0;
}
友情提醒:不要Ctrl C+Ctrl V