B. Worms(二分查找)Codeforces Round #271 (Div. 2)

原题链接:https://codeforces.com/problemset/problem/474/B

题意:给定n个堆,每个堆中都有蠕虫,其中蠕虫的数量规则是递增的,根据输入的a数组得来的,这些蠕虫的序号都是根据堆来的依次递增。然后再给定m个多汁蠕虫的序号,问这些蠕虫在哪些堆中?

解题思路:首先对于输入的a数组我们肯定要进行处理,我们需要构造结构体存储每个堆的开始下标与结束下标,然后利用a数组来实现每个堆的存储信息。那么对于给定的m个多汁蠕虫序号,我们如果直接遍历寻找自然会超时,由于这些堆已经是递增存在了,所以我们可以利用二分查找法来实现

AC代码:

/*
*邮箱:[email protected]
*blog:https://blog.csdn.net/hzf0701
*注:代码如有问题请私信我或在评论区留言,谢谢支持。
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<string>
#include<stack>
#include<queue>
#include<cstring>
#include<map>
#include<iterator>
#include<list>
#include<set>
#include<functional>
#include<memory.h>//低版本G++编译器不支持,若使用这种G++编译器此段应注释掉
#include<iomanip>
#include<vector>
#include<cstring>
#define scd(n) scanf("%d",&n)
#define scf(n) scanf("%f",&n)
#define scc(n) scanf("%c",&n)
#define scs(n) scanf("%s",n)
#define prd(n) printf("%d",n)
#define prf(n) printf("%f",n)
#define prc(n) printf("%c",n)
#define prs(n) printf("%s",n)
#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define fi first
#define se second
#define mp make_pair
using namespace std;
const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5+2;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll>  pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为代码自定义代码模板***************************************//

struct node{
	int st;
	int ed;
};
node nums[maxn];
int n,m;//n代表蠕虫的堆数,m代表多汁蠕虫的个数。
int temp[maxn];
int main(){
	//freopen("in.txt", "r", stdin);//提交的时候要注释掉
	ios::sync_with_stdio(false);//打消iostream中输入输出缓存,节省时间。
	cin.tie(0); cout.tie(0);//可以通过tie(0)(0表示NULL)来解除cin与cout的绑定,进一步加快执行效率。
	while(cin>>n){
		rep(i,0,n-1){
			cin>>temp[i];
			//根据题意填充数组。
			if(i!=0){
				nums[i].st=nums[i-1].ed+1;
				nums[i].ed=nums[i-1].ed+temp[i];
			}
			else{
				nums[i].st=1;
				nums[i].ed=temp[i];
			}
		}
		cin>>m;
		int temp;
		int low,high,mid;//二分法查找
		rep(i,0,m-1){
			cin>>temp;
			low=0;high=n-1,mid=(low+high)/2;
			while(low<=high){
				if(temp<nums[mid].st){
					high=mid-1;
				}
				else if(temp>nums[mid].ed){
					low=mid+1;
				}
				else{
					break;
				}
				mid=(low+high)/2;
			}
			cout<<mid+1<<endl;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hzf0701/article/details/107806611