Problem Author: | Hadi Takla |
Prepared by: | Hadi Takla |
Edited by: | Hadi Takla |
First , instead of choosing n-1 arrays , we will take all arrays and then try to remove one.
Since we need to obtain Mex() = , should not be present in any chosen prefix.
Let p_i be the longest prefix from the array a_i that does not contain , and let b = p_1 + p_2 + ... + p_n , and freq_x is the frequency of integer in the array .
if we can't obtain a Mex equal to using all arrays answer is "NO".
Otherwise , we have all integers between and k-1 present in the array .
Now , for each we will try to remove p_i from to see what happens.
for each integer x \in p_i we will decrease freq_x , if we got freq_x = 0 and 0 \le x \le k-1 then the array is necessary and we can't remove p_i.
after that increase freq_x again and move to the next array.
if all arrays are necessary answer is "NO" ,otherwise answer is "YES".
Time complexity \mathcal{O}(m \cdot \log(\max(x))) using map to track frequencies , using frequency array.
m=\displaystyle \sum_{i=1}^n \text{sz}_i=\text{sz}_1+\text{sz}_2+\text{sz}_3+...+\text{sz}_n.
#include<bits/stdc++.h>
#define endl '\n'
#define int long long
#define F first
#define S second
using namespace std;
const int N = 2e5 + 1;
const int M = 1e9 + 7;
signed main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int tc = 1;
cin>>tc;
while(tc--)
{
int n,k;
cin>>n>>k;
vector<int>p[n+1];
for(int i=1;i<=n;i++)
{
int m;
cin>>m;
bool ok = 1;
for(int j=1;j<=m;j++)
{
int x;
cin>>x;
if(x == k)
ok = 0;
if(ok)
p[i].push_back(x);
}
}
map<int,int>freq;
for(int i=1;i<=n;i++)
{
for(auto it:p[i])
freq[it]++;
}
int mex = 0;
while(freq[mex])
mex++;
if(mex != k)
{
cout<<"NO"<<endl;
continue;
}
int cnt = 0; //count of necessary arrays
for(int i=1;i<=n;i++)
{
bool nec = 0;
for(auto it:p[i])
{
freq[it]--;
if(freq[it] == 0 && it < k)
nec = 1;
}
cnt += nec;
for(auto it:p[i])
freq[it]++;
}
cout<<(cnt == n ? "NO" : "YES")<<endl;
}
}