Shayan's blog

By Shayan, 3 hours ago, In English

Note: The text editorials will be provided by the authors of the round. This video tutorial acts as an additional resource for those who prefer video over text, not as a substitute for the text editorial.

2034A — King Keykhosrow's Mystery

Video

2034B — Rakhsh's Revival

Video

2034C — Trapped in the Witch's Labyrinth

Video

2034D — Darius' Wisdom

Video

2034E — Permutations Harmony

Video
  • Vote: I like it
  • -17
  • Vote: I do not like it

»
96 minutes ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

@Update: I figured it out what was wrong, after resolving, I found that it is a wrong approach, as it is taking care of only three cycles which will fail for below test case.

0 2 0 2 1 0 1 0

Can anyone tell me why I'm getting TLE, For Problem D.

Idea behind the solution is to sort first 1 and 2, using two pointer approach, then sort 0 and 1 using two pointer approach and then one more time check again 1 and 2 if they are sorted or not using same approach.

So, in worst case I'm traversing the whole array 3 times and it is given that sum of n over all test cases do not exceed 2*10^5.

So, maximum number of iteration for worst test case will be 3*2*10^5 < 10^8, then how tle is coming as response. Below is my code.

#include<iostream>
#include<vector>
using namespace std;
int main() {
//     #ifndef ONLINE_JUDGE
// 	freopen("input.txt", "r", stdin);
// 	freopen("output.txt", "w", stdout);
// 	#endif
    ios_base::sync_with_stdio(false);
    int t, n;
    cin>>t;
    vector<pair<int,int>> ans(200000, {0,0});
    while(t--) {
        cin>>n;
        int arr[n], i = 0, j = n-1, k = 0;
        for(int i=0;i<n;i++) cin>>arr[i];
        i = 0, j = n-1;
        while(i < j) {
            if(arr[i] == 0 || arr[i] == 1) i++;
            else if(arr[j] == 2 || arr[j] == 0) j--;
            else if(arr[i] == 2 && arr[j] == 1) {
                ans[k].first = i+1;
                ans[k].second = j+1;
                k++;                
                swap(arr[i], arr[j]);
                i++, j--;
            }
        }
        i = 0, j = n-1;
        while(i < j) {
            if(arr[i] == 0) i++;
            else if(arr[j] == 1 || arr[j] == 2) j--;
            else if(arr[i] == 1 && arr[j] == 0) {
                ans[k].first = i+1;
                ans[k].second = j+1;
                k++;
                swap(arr[i], arr[j]);
                i++, j--;
            }
        }
        i = 0, j = n-1;
        while(i < j) {
            if(arr[i] == 0 || arr[i] == 1) i++;
            else if(arr[j] == 2 || arr[j] == 0) j--;
            else if(arr[i] == 2 && arr[j] == 1) {
                ans[k].first = i+1;
                ans[k].second = j+1;
                k++;
                swap(arr[i], arr[j]);
                i++, j--;
            }
        }
        cout<<k<<'\n';
        for(i=0;i<k;i++) {
            cout<<ans[i].first<<' '<<ans[i].second<<'\n';
        }
    }
    
}