Блог пользователя arjunarora_17

Автор arjunarora_17, 8 месяцев назад, По-английски

340785689 Problem link : link
Editorial Solution : link


My Solution

Intuition:
For an array of size n, the maximum number of possible subsets of indices is $$$2^n$$$. My approach is to consider two adjacent pairs at a time.

Example:
$$$a = {2,1,4}, \quad b = {1,3,4}$$$

We check adjacent pairs $$$(a_{i-1}, a_i)$$$ and $$$(b_{i-1}, b_i)$$$. For these two positions, there are four possible swap choices:

  • No swaps : {}
  • Swap at first index : {1} : swap(a[i-1], b[i-1])
  • Swap at second index : {2} : swap(a[a[i], b[i]])
  • Swap both indices : {1,2} : swap(a[i-1], b[i-1]) and swap(a[a[i], b[i]])

Observation:We know that a valid swap means after swapping both the adjacent pairs are sorted. The number of valid swaps can be either 2 or 4. Let's call them "2-valid" and "4-valid". It can't be zero as mentioned in the question itself and can't be 1 or 3 either.

If we calculate this for all adjacent pairs $$$(a_{i-1},a_i)$$$ and $$$(b_{i-1},b_i)$$$, where $$$1 \leq i \lt n$$$, then each time we encounter a “2-valid” situation, the total number of global possibilities is cut in half.

Thus, starting from $$$2^n$$$, the final answer becomes $$$2^{n-x}$$$,
where $$$x$$$ is the number of indices that are “2-valid.”

All calculations are done modulo $$$998244353$$$.

The code

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

int check(int a1,int a2,int b1,int b2){
    // a = {a1, a2}
    // b = {b1, b2}
    int ans = 0;
    if(a1<=a2 && b1<= b2) ans+=2;
    if(a1<=b2 && b1<=a2) ans+=2;
    if(ans == 4) return 1;
    else return 0;

}

int main() {
    int t;
    cin>>t;
    while(t--){
        int n; cin>>n;
        vector<int> a, b;
        for(int i=0;i<n;i++){
            int x; cin>>x;
            a.push_back(x);
        }
        for(int i=0;i<n;i++){
            int x; cin>>x;
            b.push_back(x);
        }
        int val = 0;
        for(int i=1; i<n; i++){
            if(!check(a[i-1],a[i], b[i-1],b[i])){
                val++;
            }
        }

        long long ans = 1;
        for(int i = 0; i < n - val; i++) ans = (ans * 2) % 998244353;
        if(n!=1) cout << ans << endl; else cout << 2 << endl;
    }    
    return 0;
}

Полный текст и комментарии »

  • Проголосовать: нравится
  • -2
  • Проголосовать: не нравится