Problem Author: | Hasan Saleh (MathModel) |
Prepared by: | Hadi Takla (TaklaOI) |
Edited by: | Hadi Takla (TaklaOI) |
Solution
Fact 1 : since we can apply the operation any number of times , we can rearrange both arrays as we want.
The condition [a_1 , a_2 , ... , a_n] = [b_1 , b_2 , ... , b_i] for each (1 \le i \le \text{min}(n,m)) means that the length of the longest common prefix between and should be equal to \text{min}(n,m).
Now , let be the length of the longest common prefix , freq[x][0] be the frequency of the number in the array and freq[x][1] be the frequency of the number in the array .
Now if we want to increase by using a value , we should take elements with value from array , and elements with value from array , the maximum we can obtain is \text{min}(freq[x][0] , freq[x][1]) , so each number will increase by \text{min}(freq[x][0] , freq[x][1]).
After using all numbers where (1 \le x \le n+m) , if is equal to \text{min}(n,m) , answer is "YES" otherwise "NO".
Time complexity : \mathcal{O}(n+m).
#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,m;
cin>>n>>m;
int freq[n+m+1][2] , len = 0;
memset(freq , 0 , sizeof freq);
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
freq[x][0]++;
}
for(int i=1;i<=m;i++)
{
int x;
cin>>x;
freq[x][1]++;
}
for(int i=1;i<=n+m;i++)
{
len += min(freq[i][0] , freq[i][1]);
}
cout<<(len == min(n , m) ? "YES" : "NO")<<endl;
}
}