A. CHONG of the ring pigeon (dfs)
Question: Give you a sequence, if all the strings in this sequence are good sequences, then output chong chongc h o n g , otherwise outputfuchong fuchongf u c h o n g , the definition of a good sequence is that a unique element can be found in the sequence.
Solution: My previous approach is to enumerate the interval, if the elements in this interval are not unique, output fuchong fuchongf u c h o n g , but it is obviously timed out,o (n ∗ n) o(n*n)o ( n∗n ) complexity, the correct solution (from Niuke) is to find an element that is unique, then if the sequence on the left is a good sequence and the sequence on the right is also a good sequence, then this sequence is a good sequence , This is somewhat similar to the idea of divide and conquer. The specific approach depends on the code.
#include<bits/stdc++.h>
#define mk make_pair
#define pi pair<int,int>
#define pb push_back
#define pp pop_back
using namespace std;
const int maxn = 1e5+100,inf = 1e9+100;
int l[maxn],r[maxn],a[maxn];
map<int,int>mp;
int dfs(int ll,int rr)
{
if(ll >= rr)return 1;
int i = ll ,j = rr;
while(i <= j)
{
if(l[i] < ll && r[i] > rr)return dfs(ll,i-1)&&dfs(i+1,rr);
if(l[j] < ll && r[j] > rr)return dfs(ll,j-1)&&dfs(j+1,rr);
i++,j--;
}
return 0;
}
int main()
{
int n;
cin >> n;
for(int i=1;i<=n;i++)
{
cin >> a[i];
l[i] = mp[a[i]];
mp[a[i]] = i;
}
mp.clear();
for(int i=n;i>0;i--)
{
if(mp[a[i]]==0)r[i] = inf;
else r[i] = mp[a[i]];
mp[a[i]] = i;
}
int flag = dfs(1,n);
if(!flag)puts("fuchong");
else puts("chong");
return 0;
}