GRPASSN - EDITORIAL

PROBLEM LINK:

Contest Division 1
Contest Division 2
Contest Division 3
Contest Division 4
Practice

Setter: Utkarsh Darolia
Testers: Nishank Suresh and Abhinav sharma
Editorialist: Utkarsh Darolia

DIFFICULTY

1092

PREREQUISITES

None

PROBLEM

There are N people and the group size preference of i^{th} person is A_{i}. The objective is to find out if we can assign every person to a group of their preferred size.

EXPLANATION

To solve this problem, let’s first try solving a subproblem, which is to find if all the people with a particular value of group size preference can remain happy.

Let’s define happy(r) as a boolean, which is true if all people with group size preference r can remain happy, and false otherwise. And define count(r) as the count of people which have group size preference r.

Let k=count(r) and k\gt 0. Then, every one with group size preference r can remain happy only —

  • If they can be distributed into groups of size r where each of the k people is in exactly 1 group, or
  • If k=r or k=2 \times r or k=3 \times r…, or
  • If k is a multiple of r, or
  • If k \% r=0

So, if k > 0 and k \%r =0, then happy(r)=true, otherwise happy(r)=false. And we can say that everyone remains happy, if for all values of r from 2 to n (where count(r) \gt 0) happy(r) is true.

We’re only checking values of r with count(r)>0 as when count(r)=0 there is no sense in saying that people with group size preference r are happy or not as there are no people!

TIME COMPLEXITY

The time complexity is O(N) per test case.

SOLUTIONS

Editorialist's Solution
// author: Utkarsh Darolia
#include <bits/stdc++.h>
using namespace std;

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    for (int i = 1; i <= t; ++i)
    {
        int n;
        cin >> n;

        bool happy = true;
        int count[n+1] = {};

        for (int j = 1; j <= n; ++j)
        {
            int groupSizePreference;
            cin >> groupSizePreference;
            count[groupSizePreference]++;
        }

        for (int j = 2; j <= n; ++j)
        {
            if ((count[j]%j) != 0)
            {
                happy = false;
            }
        }
    
        if (happy == true)
        {
            cout << "YES" << endl;
        }
        else
        {
            cout << "NO" << endl;
        }
    }
    return 0;
}

Feel free to share your approach. Suggestions are welcome. :smile:

1 Like