Analysis of USACO past bronze group real questions | December 2020 Daisy Chains

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]

Every day, as part of her walk around the farm, Bessie the cow passes her favorite meadow, which contains N flowers (colorful daisies), numbered 1…N (1≤N≤100), arranged in a row. Flower i has pi petals (1≤pi≤1000).

As a budding photographer, Bessie decided to take some photos of the flowers. Specifically, for each pair of flowers (i,j) satisfying 1≤i≤j≤N, Bessie will take a photo of all flowers from flower i to flower j (including i and j).

When Bessie later looked at the photos, she noticed that in some of them there was an "average" flower—a flower with exactly P petals, where P equals the average number of petals of all the flowers in the photo.

How many of Bessie's photos have average flowers?

【enter】

The first line of input contains N. The second line contains N space-separated integers p1…pN.

【Output】

Output the average number of flower photos present.

【Input sample】

4
1 1 2 3

【Output sample】

6

[Detailed code explanation]

#include <bits/stdc++.h>
using namespace std;
int n, a[105], ans=0;
int main()
{
    cin >> n;  // 输入n
    for (int i=1; i<=n; i++) {  // 遍历n朵花
        cin >> a[i];  // 记录每朵花的花瓣数量
    }
    for (int i=1; i<=n; i++) {  // 从1开始遍历
        int avg=0, sum=0;  // 每次初始化花瓣平均数和总数为0
        for (int j=i; j<=n; j++) {  // j从i开始向后遍历
            sum += a[j];  // 计算花瓣总数
            if (sum % (j-i+1)!=0) continue;  // 如果平均数不为整数直接跳过(花的花瓣数不可能是小数)
            avg = sum / (j-i+1);  // 计算平均花瓣数
            for (int k=i; k<=j; k++) {  // 从i遍历到j
                if (a[k]==avg) {  // 如果有任一朵花恰好有p朵花瓣的花
                    ans += 1;  // 照片数自增1
                    break;  // 无需判断该照片中的其他花,直接结束循环
                }
            }
        }
    }
    cout << ans << endl;  // 打印结果
    return 0;
}

【operation result】

4
1 1 2 3
6

Guess you like

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