zcmu1277: Meat

题目链接:https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1277

题目大意

Er喜欢吃肉,有n个房间,每个房间ai块肉,Er从第i个房间走到第i+1和第i-1个房间需要花费1单元的时间,他吃一块肉也要花费1单位时间。他刚开始在第x个房间,问:他吃完所有肉最少花费多长时间。

范围:(2<=n<=100, 1<=x<=n,0<=ai<=1000)

思路

由于房间肉可以是0,所以先确定左右非零边界,然后来回跑就好了。

ac代码

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n, x;
    int a[105];
    while(cin >> n >> x){
        int sum = 0;
        for(int i = 1; i <= n; i ++){
            scanf("%d", &a[i]);
            sum += a[i];
        }
        int l = 1, r = n;
        while(l <= n && a[l] == 0) l ++;
        while(r >= 1 && a[r] == 0) r --;
        if(l == n + 1){ //说明都是0,那么就不用来回走了
            puts("0");
            continue;
        }
        //sum是吃肉时间,r-l是走完全程时间,r-x是往右跑回来的时间,x-l是网走跑回来的时间
        cout << sum + r - l + min(r - x, x - l) << endl; 
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43911947/article/details/113282127