每个苹果编号1到n;
第二堆苹果的虚拟总数量是前面的和;
for(int i=1;i<=n;i++){
scanf("%d",&sz[i]);
sz[i]+=sz[i-1];
}
对原输入数组做一个累加处理。
---------------------------------------------------------------------------------------------
2 7 3 4 9
累加后
2 9 12 16 25
----------------------------------------------------------------------------------------------
这个数组是第一个递增数组
用二分法解决
--------------------------------------------------------------------------------------------
#include<stdio.h>
int main()
{
int n,m;
scanf("%d",&n);
int sz[n+1];
sz[0]=0;
for(int i=1;i<=n;i++){
scanf("%d",&sz[i]);
sz[i]+=sz[i-1];
}//输入n堆苹果
scanf("%d",&m);
int szsz[m];
for(int i=0;i<m;i++){
scanf("%d",&szsz[i]);
}//输入想知道那一个苹果
for(int i=0;i<m;i++){
int right=0,left=n,tmp=szsz[i];
if(tmp>sz[n]){printf("%d\n",-1);break;}
while(right<left-1){//下标折半后没有+-1,所以这里的right最后比left小1
if(tmp==sz[(left+right)/2]){left=(left+right)/2;break;}
else if(tmp>sz[(left+right)/2]){right=(left+right)/2;}
else if(tmp<sz[(left+right)/2]){left=(left+right)/2;}
}
printf("%d\n",left);
}
return 0;
}
int main()
{
int n,m;
scanf("%d",&n);
int sz[n+1];
sz[0]=0;
for(int i=1;i<=n;i++){
scanf("%d",&sz[i]);
sz[i]+=sz[i-1];
}//输入n堆苹果
scanf("%d",&m);
int szsz[m];
for(int i=0;i<m;i++){
scanf("%d",&szsz[i]);
}//输入想知道那一个苹果
for(int i=0;i<m;i++){
int right=0,left=n,tmp=szsz[i];
if(tmp>sz[n]){printf("%d\n",-1);break;}
while(right<left-1){//下标折半后没有+-1,所以这里的right最后比left小1
if(tmp==sz[(left+right)/2]){left=(left+right)/2;break;}
else if(tmp>sz[(left+right)/2]){right=(left+right)/2;}
else if(tmp<sz[(left+right)/2]){left=(left+right)/2;}
}
printf("%d\n",left);
}
return 0;
}