1631D - Range and Partition - CodeForces Solution


binary search constructive algorithms greedy two pointers *1800

Please click on ads to support us..

C++ Code:

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

void solve(){
    int n,k;
    cin>>n>>k;
    vector<int> v(n);
    for(auto &i:v) cin>>i;
    int req = (n+k+1)/2;
    auto vv = v;
    sort(vv.begin(),vv.end());
    vector<int> ans = {n+1,-1,-1};
    for(int i=0;i<n-req+1;i++){
        int d = vv[i+req-1] - vv[i];
        ans = min(ans,{d,vv[i],vv[i+req-1]});
    }
    int x = ans[1],y = ans[2];
    int sum = 0,cnt = 0,prev = 1;
    cout<<x<<" "<<y<<endl;
    for(int i=0;i<n;i++){
        if(v[i] >= x && v[i]<= y) sum++;
        else sum--;
        if(sum > 0 && cnt < k-1){
            cout<<prev<<" "<<i+1<<endl;
            prev = i+2;
            sum = 0;
            cnt++;
        }
    }
    cout<<prev<<" "<<n<<endl;
}
signed main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t;
    cin>>t;
    while(t--){
        solve();
    }
    // for(int i=12;i<=12;i++){
    //     int n = (1<<i);
    //     for(int k = 0;k<n-1;k++){
    //         auto res = solve(n,k);
    //         int x = 0;
    //         for(auto &p:res) x = x + (p.first & p.second);
    //         if(x != k) cout<<n<<" "<<k<<" "<<x<<endl;
    //     }
    // }
}


Comments

Submit
0 Comments
More Questions

415. Add Strings
22. Generate Parentheses
13. Roman to Integer
2. Add Two Numbers
515. Find Largest Value in Each Tree Row
345. Reverse Vowels of a String
628. Maximum Product of Three Numbers
1526A - Mean Inequality
1526B - I Hate 1111
1881. Maximum Value after Insertion
237. Delete Node in a Linked List
27. Remove Element
39. Combination Sum
378. Kth Smallest Element in a Sorted Matrix
162. Find Peak Element
1529A - Eshag Loves Big Arrays
19. Remove Nth Node From End of List
925. Long Pressed Name
1051. Height Checker
695. Max Area of Island
402. Remove K Digits
97. Interleaving String
543. Diameter of Binary Tree
124. Binary Tree Maximum Path Sum
1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
501A - Contest
160A- Twins
752. Open the Lock
1535A - Fair Playoff
1538F - Interesting Function