zcmu1277: Meat

Title link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1277

Topic

Er likes to eat meat. There are n rooms, and each room is a piece of meat. It takes 1 unit of time for Er to walk from the i-th room to the i+1-th and i-1th rooms, and it takes him to eat a piece of meat. 1 unit of time. He just started in the xth room and asked: How long will it take him to eat all the meat at least?

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

Ideas

Since the room meat can be 0, first determine the left and right non-zero boundaries, and then just run back and forth.

ac code

#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;
}

 

Guess you like

Origin blog.csdn.net/weixin_43911947/article/details/113282127