题解:P12663 [KOI 2023 Round 2] 湖边的蚁穴

· · 题解

P12663 [KOI 2023 Round 2] 湖边的蚁穴 题解

原题传送门

题目思路

对于有小房间的房间,优先选择小房间,它的大房间就不选。剩下的房间里每相邻的两个有小房间的房间之间的房间(就是连续的没有小房间的房间)里选择最多的,数量是 \lceil\frac{s}{2}\rceil,其中 s 是指连续的没有小房间的房间的个数。

这题不是很难,但细节较多,要注意以下几点。

代码

#include <bits/stdc++.h>
#define int long long
using namespace std;

int n;
int c[250005];
int x, p;

int ans = 0;

signed main() {
    cin >> n;
    x = 0;
    for (int i = 1; i <= n; i++) {
        cin >> c[i];
        if (c[i] != 0) {
            //有小房间的房间
            ans += c[i]; //优先选择小房间
            if (x == 0) {
                p = i - 1; //开头连续没有小房间的房间的个数
            } else {
                ans += (i - x - 1) / 2 + (i - x - 1) % 2; //连续没有小房间的房间的选择最多的
            }
            x = i; //记录上一个有小房间的房间,用来计算连续的没有小房间的房间的个数
        }
    }
    if (ans == 0) ans += n / 2; //当全是没有小房间的房间是,答案为房间数量的二分之一向下取整
    else ans += (n - x + p) / 2 + (n - x + p) % 2; //n-x+2+p为头和尾连接起来的连续没有小房间的房间的个数
    cout << ans;
    return 0;
}