48D - Permutations - CodeForces Solution


greedy *1500

Please click on ads to support us..

Python Code:

from collections import *
input()
p = list(map(int, input().split()))
a = sorted(p)
mx = max(p)
c = [0]*(mx+1)
for i in a:
	c[i] += 1

if not all(c[a]>=c[a+1] for a in range(1, mx)):
	print(-1)
	exit(0)

print(max(c))
for i in p:
	print(c[i], end=' ')
	c[i] -= 1
print()

C++ Code:

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
        int n;
        cin>>n;
        int arr[n];
        vector<pair<int,int>>dp;
        for(int i=0;i<n;i++){
                cin>>arr[i];
                dp.push_back({arr[i],i});

        }
        sort(dp.begin(),dp.end());
        int ans=1;
        bool flag=true;
        int cnt=1;
        int p=1;
        arr[0]=1;
        if(dp[0].first!=1){
                cout<<-1<<endl;

        }
        else{

        
        for(int i=1;i<n;i++){
                if(dp[i].first==1){
                        ans++;
                        p++;
                        cnt++;
                        arr[dp[i].second]=ans;
                        continue;
                        
                }
                if(dp[i].first-dp[i-1].first>1){
                        flag=false;
                }
                if(dp[i].first!=dp[i-1].first){
                     if(cnt>p){
                        flag=false;
                        break;
                     } 
                     else{
                        p=cnt;
                        cnt=0;
                     }
                     
                }  
                cnt++;
                arr[dp[i].second]=cnt;
                
                

        }
         if(cnt>p||flag==false){
                cout<<-1<<endl;

        }
        else{
                cout<<ans<<endl;
                for(int i=0;i<n;i++)
                cout<<arr[i]<<" ";
                cout<<endl;
        }

        }
       


        
return 0;
}


Comments

Submit
0 Comments
More Questions

987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
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