843A - Sorting by Subsequences - CodeForces Solution


dfs and similar dsu implementation math sortings *1400

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int main(){


        int n , temp;
        cin>>n;

        vector<pair<long long int,int>>vec(n);
        int arr[n]={0};

        for(int x=0;x<n;x++){

            cin>>temp;

            vec[x] = {temp , x};
        }

        sort(vec.begin(),vec.end());

        for(int x=0;x<n;x++){

            int h = vec[x].second;

            arr[h] = x;
        }

        vector<vector<int>>ans;
        vector<int>tmp;

        int visited[n]={0};

        for(int x=0;x<n;x++){
  
            if(visited[x]==0){

                if(arr[x]==x){

                    vector<int>k;

                    visited[x] = 1;

                    k.push_back(x+1);
                    ans.push_back(k);

                }else{

                    int l = x;

                    while(visited[arr[l]]!=1){

                        tmp.push_back(arr[l]+1);

                        visited[arr[l]]=1;

                        l = arr[l];
                        

                    }

                    ans.push_back(tmp);
                    tmp.clear();

                }
            }
            

        }

        cout<<ans.size()<<endl;

        for(auto z:ans){

            cout<<z.size()<<" ";

            for(auto y:z){
                cout<<y<<" ";
            }
            cout<<'\n';
        }    


    return 0;
}


Comments

Submit
0 Comments
More Questions

32. Longest Valid Parentheses
Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations
Removal of vertices
Happy segments
Cyclic shifts
Zoos
Build a graph
Almost correct bracket sequence
Count of integers
Differences of the permutations
Doctor's Secret
Back to School
I am Easy
Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement