Description
Brother Er like eating meat very much. One day, he found a street full of meat. There are n room in the street. In each room there are ai unit of meat. When Brother Er in room i, he can get room i-1 or room i+1 (if exist) and use 1 unit of time. And if Brother Er eat one unit of meat ,he need one unit of time.Brother Er is very Hunger and want to eat all the meat with minimum time. First Brother Er is in room x. And he can stay at any room when he eat all the meat. Can you tell me the minimum time ?
Input
There are multiple test cases in the input file.
In each case the first line contains 2 integers n (2<=n<=100) — the number of room, x (1<=x<=n) - the initial room of Brother Er.
The second line contains n distinct space-separated integers a1, a2, ..., an (0<=ai<=1000) — the number of meat in each room.
Output
For each case print a single line with the minimum time.
Sample Input
2 1
2 3
Sample Output
6
注释:就是往两边走直到不可能再有肉,那么就得先讨论第几位开始有肉,第几位开始没肉。如0 1 1 2 0 2 0,第2位开始有肉,第6位开始没肉,那么知到开始位置,走就行了,只不过要分类讨论开始位置与有肉的区间的位置关系,可能在区间左边,区间内,区间右边,还有如果sum=0;表示没有肉,那就不用走了。
代码:
#include<bits/stdc++.h>
using namespace std;
int s[1000];
int n,x;
int main(){
while(~scanf("%d %d",&n,&x)){
int w1=1,w2=1,sum=0;
for(int i=1;i<=n;i++){
scanf("%d",&s[i]);
sum+=s[i];
}
for(int i=1;i<=n;i++){
if(s[i]!=0){
w1=i;break;}
}
for(int i=n;i>=1;i--){
if(s[i]!=0){
w2=i;break;
}
}
if(sum==0)printf("0\n");
else if(w1>=x){
printf("%d\n",sum+w2-x);
}//在区间左边
else if(w2<=x){
printf("%d\n",sum+x-w1);
}//在区间右边
else printf("%d\n",sum+min(x-w1,w2-x)+w2-w1);//在区间内
}
}