1102B - Array K-Coloring - CodeForces Solution


greedy sortings *1400

Please click on ads to support us..

Python Code:

from collections import defaultdict
import math

n, k = map(int, input().split())

values = list(map(int, input().split()))

def K_colors(nums, k):
    values = sorted([(val, i) for i, val in enumerate(nums)])
    i = 0
    color = 1
    res = [0] * len(values)

    while i < len(values):
        j = i
        count = 0
        while j < len(values) and values[i][0] == values[j][0]:
            
            if count == k:
                return []
            res[values[j][1]] = color 
            count += 1
            color += 1
            if color == k+1:
                color = 1
            j += 1
        i = j

    return res


result = K_colors(values, k)
if result:
    print("YES")
    for val in result:
        print(val, end = " ")
else:
    print("NO")

C++ Code:

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

int32_t main(){
  int n, k;
  cin>>n>>k;
  vector<int> v(n);
  map<int, vector<int>> mp;
  for(int i=0;i<n;i++){
    cin>>v[i];
    mp[v[i]].push_back(i);
  }
  bool flag=false;
  for(auto it: mp)
     if(it.second.size()>k)
        flag=true;
  if(k>n)
     cout<<"NO"<<'\n';
  else if(flag)
     cout<<"NO"<<'\n';
  else{
     cout<<"YES"<<'\n';
     int start=1;
     if(k==1){
        for(int i=0;i<n;i++)
          cout<<1<<" ";
          cout<<'\n';
     }
     else{
     for(auto it: mp){
        for(auto itr: it.second){
            if(start>k)
              start%=k;
            v[itr]=start;
            start++;
        }
     }
        for(auto it: v)
          cout<<it<<" ";
        cout<<'\n';
    }
  }
  return 0;
}


Comments

Submit
0 Comments
More Questions

1326B - Maximums
1635C - Differential Sorting
961A - Tetris
1635B - Avoid Local Maximums
20A - BerOS file system
1637A - Sorting Parts
509A - Maximum in Table
1647C - Madoka and Childish Pranks
689B - Mike and Shortcuts
379B - New Year Present
1498A - GCD Sum
1277C - As Simple as One and Two
1301A - Three Strings
460A - Vasya and Socks
1624C - Division by Two and Permutation
1288A - Deadline
1617A - Forbidden Subsequence
914A - Perfect Squares
873D - Merge Sort
1251A - Broken Keyboard
463B - Caisa and Pylons
584A - Olesya and Rodion
799A - Carrot Cakes
1569B - Chess Tournament
1047B - Cover Points
1381B - Unmerge
1256A - Payment Without Change
908B - New Year and Buggy Bot
979A - Pizza Pizza Pizza
731A - Night at the Museum