Lanterns with One Repair#13115

Lanterns with One Repair (ამოხსნის განხილვა)

Solution

Let cnt_i denote the number of lanterns illuminating house .

First, calculate cnt_i for every house. Let be the number of houses illuminated by exactly one lantern in the initial configuration:

ans = \sum_{i=1}^{n} [cnt_i = 1].

Here, equals if condition is true, and otherwise.

Consider reversing the lantern next to house . Let be the house illuminated before the reversal, and be the house illuminated afterwards.

Only two houses are affected: cnt_l decreases by , while cnt_r increases by . All other illumination counts remain unchanged.

The contribution of house changes from [cnt_l = 1] to [cnt_l = 2], while the contribution of house changes from [cnt_r = 1] to [cnt_r = 0].

Therefore, the number of houses illuminated by exactly one lantern after the reversal is

cur = ans - [cnt_l = 1] + [cnt_l = 2] - [cnt_r = 1] + [cnt_r = 0].

We can calculate this value in time for each lantern without modifying the array .

We consider all possible reversals and take the maximum result. Since we may reverse at most one lantern, we also consider the initial configuration.

Complexity Analysis

Calculating the initial illumination counts takes time. Each of the possible reversals is processed in time.

The total time complexity is , and the space complexity is .

Implementation

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

void solve() {
    int n;
    cin >> n;

    string s;
    cin >> s;

    vector<int> cnt(n);

    for (int i = 0; i < n; i++) {
        int j = (s[i] == 'L' ? (i + n - 1) % n : (i + 1) % n);
        cnt[j]++;
    }

    int ans = 0;
    for (int i = 0; i < n; i++) {
        ans += (cnt[i] == 1);
    }

    int res = ans;

    for (int i = 0; i < n; i++) {
        int l = (i + n - 1) % n;
        int r = (i + 1) % n;

        if (s[i] == 'R') {
            swap(l, r);
        }

        int cur = ans;
        cur -= (cnt[l] == 1);
        cur += (cnt[l] == 2);
        cur -= (cnt[r] == 1);
        cur += (cnt[r] == 0);

        res = max(res, cur);
    }

    cout << res << '\n';
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();
}