ACM中的CM题(二分,牛客小白月赛)
题目来源:https://ac.nowcoder.com/acm/contest/88878/E
//
题意:n 个地雷,每个雷的位置不同,初始排雷能力 m=0,任何时刻可以把l位置将[l,l+m]雷全部排走,也可以在任何时候把排雷能力从m变成m+1,两种操作都花费1时间,问排所有雷最少时间。
//思路:“最开始写的模拟啊,找最长连续雷的位置,然后后面扫雷的次数就会更少,贪心把,但是错了。”正解是二分,枚举排雷能力x,最大就n(n<=2e5),然后去二分用x排雷能力排雷的次数,最后记录最小值。
//
代码细节:如何去模拟扫雷啊,每次l,然后把所有[l,l+m]的数字记录为ans++,就是用二分,upper_bound去找第一个大于l+m的位置,然后ans++,一直到二分的位置到了a.end(),也就是所有的雷全部扫完了。
//
题解:
点击查看代码
//#include<bits/stdc++.h>
//#define int long long
//using namespace std;
//const int N=2e3+9;
//string mp[N];
//int vis[N][N];
//int n,m,st_x,st_y;
//int ans=-1;
//int dx1[]={-1,1,0,0};
//int dy1[]={0,0,-1,1};
//
//int dx2[]={1,-1,0,0};
//int dy2[]={0,0,1,-1};
//
//struct Nod{
// int x1,y1,x2,y2,step,f1,f2;
//}temp,p;
//queue<Nod>q;
//
//void bfs(){
// q.push({st_x,st_y,st_x,st_y,0,0,0});
// while(!q.empty()){
// temp=q.front();q.pop();
//
//// if(mp[temp.x1][temp.y1]=='@'&&mp[temp.x2][temp.y2]=='@'){
//// cout<<temp.step<<endl;
//// return;
//// }
//
// if(mp[temp.x1][temp.y1]=='@'){
// ans=temp.step;
// temp.f1=1;
// }
// if(mp[temp.x2][temp.y2]=='@'){
// ans=max(ans,temp.step);
// temp.f2=1;
// }
//
// if(vis[temp.x1][temp.y1]){ continue;}
// vis[temp.x1][temp.y1]=1;
// for(int i=0;i<4;i++){
// p.x1=temp.x1+dx1[i],p.y1=temp.y1+dy1[i],p.step=temp.step+1;
// p.x2=temp.x2+dx2[i],p.y2=temp.y2+dy2[i],p.f1=temp.f1,p.f2=temp.f2;
// if(!p.f1&&!p.f2&&p.x1>=0&&p.x1<n&&p.x2>=0&&p.x2<n && p.y1>=0&&p.y1<m&&p.y2>=0&&p.y2<m && mp[p.x1][p.y1]!='#'&&mp[p.x2][p.y2]!='#'&&!vis[p.x1][p.y1]&&!vis[p.x2][p.y2]){
// q.push({p.x1,p.y1,p.x2,p.y2,p.step});
// }
// else if(p.f1&&!p.f2&&p.x1>=0&&p.x1<n&& p.y1>=0&&p.y1<m&& mp[p.x1][p.y1]!='#'&&!vis[p.x1][p.y1]){
// q.push({p.x1,p.y1,p.x2,p.y2,p.step});
// }
// else if(!p.f1&&p.f2&&p.x2>=0&&p.x2<n&&p.y2>=0&&p.y2<m&&mp[p.x2][p.y2]!='#'&&!vis[p.x2][p.y2]){
// q.push({p.x1,p.y1,p.x2,p.y2,p.step});
// }
// }
// }
// if(ans==-1){
// cout<<"-1"<<endl;
// }
// else{
// cout<<ans<<endl;
// }
//}
//
//signed main()
//{
// cin>>n>>m>>st_x>>st_y;
// st_x-=1,st_y-=1;
// for(int i=0;i<n;i++){cin>>mp[i];}
// bfs();
// return 0;
//}
#include<bits/stdc++.h>
#define int long long
using namespace std;
vector<int>a;
int check(int x){
int ans=x;//0->x
int pos=a[1];
while(true){
ans++;
pos=upper_bound(a.begin()+1,a.end(),pos+x)-a.begin();
if(pos==a.end()-a.begin()){break;}
pos=a[pos];
}
return ans;
}
signed main()
{
int n;
cin>>n;
a.push_back(0);
for(int i=1;i<=n;i++){
int x;cin>>x;
a.push_back(x);
}
sort(a.begin()+1,a.end());
int Min=1e9;
for(int i=0;i<=n;i++){
Min=min(Min,check(i));
}
cout<<Min<<endl;
return 0;
}
浙公网安备 33010602011771号