Analysis of USACO past bronze group real questions | February 2018 HoofBall

Learn C++ from a young age! Record the questions in the study process of preparing for the USACO (American Informatics Olympiad) bronze category competition and record every moment.

Attached is a summary post:Analysis of USACO past bronze group real questions | Summary-CSDN Blog


[Title description]

In preparation for an upcoming hoofball championship, Farmer John is training his N cows (numbered 1...N, for convenience, where 1 ≤ N ≤ 100) to pass the ball. These cows are arranged in a straight line on one side of the cowshed, and the i-th cow is located at a distance xi from the cowshed (1≤xi≤1000). Each cow is in a different position.

At the beginning of training, Farmer John will pass several balls to different cows. When cow i receives the ball, whether it is from Farmer John or another cow, she will pass the ball to the nearest cow (if there are multiple cows at the same distance from her, she will pass the ball to the middle cow) The cow farthest to the left). To give all cows a chance to practice passing, Farmer John wants to make sure each cow holds the ball at least once. Help him find the minimum number of passes he must initially pass to achieve this goal. Suppose he can pass the ball to the most appropriate group of cows at the beginning.

【enter】

The first line of input contains N. The second line contains N space-separated integers, where the i-th integer is xi.

【Output】

Output the minimum number of balls that Farmer John needs to pass at the beginning so that all cows hold the ball at least once.

【Input sample】

5
7 1 3 11 4

【Output sample】

2

[Detailed code explanation]

#include <bits/stdc++.h>
using namespace std;
int n, a[105], cnt[105], nxt[105], ans=0;
ifstream filein("hoofball.in");
ofstream fileout("hoofball.out");
int main()
{
    filein >> n;  // 输入n
    for (int i=1; i<=n; i++) {  // 依次输入n个数
        filein >> a[i];
    }
    sort(a+1, a+n+1);  // 对数进行排序
    nxt[1] = 2;  // 默认左端点放一个球
    cnt[2] = 1;  // 指向右边一个端点
    nxt[n] = n-1;  // 默认右端点放一个球
    cnt[n-1] = 1;  // 指向左边一个端点
    for (int i=2; i<n; i++) {  // 从第2个球开始遍历
        if (a[i]-a[i-1] > a[i+1]-a[i]) {  // 比较向左的距离和向右的距离,如果向右距离更短
            nxt[i] = i+1;  // 则向右移动
            cnt[i+1]++;  // 右边那个球的计数器自增1
        } else {  // 如果向左距离更短
            nxt[i] = i-1;  // 则向左移动
            cnt[i-1]++;  // 左边那个球的计数器自增1
        }
    }
    for (int i=1; i<=n; i++) {  // 先遍历一遍n个奶牛
        if (cnt[i]==0) ans++;  // 哪些计数为0的奶牛就是把球放这个位置后不再回头的位置(即可以放球的位置)
    }
    for (int i=1; i<n; i++) {  // 再遍历一遍n-1个奶牛(因为要判断i+1,所以i不能等于n)
        if (cnt[i]==1 && cnt[i+1]==1 && nxt[i]==i+1 && nxt[i+1]==i) ans++;  // 对于两个奶牛的nxt互相指向对方的,且cnt均为1(表示一上来就互相指向对方,而不是经历多轮遍历后才互相指向对方的),这样的一对奶牛需要单独再放一个球
    }
    fileout << ans << endl;  // 打印结果
    return 0;
}

【operation result】

5
7 1 3 11 4
2

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/134923397