Binary bubble sort inversions

Правка en1, от Nagasai_Gella, 2026-09-05 20:03:45

include

include

include

include

include

using namespace std;

void solve() { int n; cin >> n; vector a(n); vector P; for (int i = 0; i < n; ++i) { cin >> a[i]; if (a[i] == 1) { P.push_back(i); } } string s; cin >> s;

int k = P.size();

auto count_inversions = [&]() {
    long long inv = 0;
    for (int j = 0; j < k; ++j) {
        inv += (n - P[j] - k + j);
    }
    return inv;
};

long long current_inv = count_inversions();
cout << current_inv << " ";

for (int op = 0; op < n; ++op) {
    if (current_inv == 0) {
        cout << 0 << " ";
        continue;
    }

    if (s[op] == '1') {
        // Bubble operation
        for (int j = 0; j < k - 1; ++j) {
            P[j] = P[j + 1] - 1;
        }
        if (k > 0) {
            P[k - 1] = n - 1;
        }
    } else {
        // Reverse bubble operation
        if (k > 0) {
            P[k - 1] = min((long long)n - 1, P[k - 1] + 1);
            for (int j = k - 2; j >= 0; --j) {
                P[j] = min(P[j + 1] - 1, P[j] + 1);
            }
        }
    }

    current_inv = count_inversions();
    cout << current_inv << " ";
}
cout << "\n";

}

int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while (t--) { solve(); } return 0; }

Теги #contest, #codeforces, #c++

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский Nagasai_Gella 2026-09-05 20:03:45 1660 Initial revision (published)