1672D - Cyclic Rotation - CodeForces Solution


constructive algorithms greedy implementation two pointers *1700

Please click on ads to support us..

Python Code:

    
    
        
        
    
    

            
def ss(a,b):
    d={i:0 for i in b}

            if a[-1]!=b[-1]:
        return "NO"
    n=len(a)
    i=n-1
    j=n-1
    
    while i>=0 and j>=0:
        while j>=1  and b[j]==b[j-1]:
            x=b[j]
            d[x]+=1
            j-=1  
        
        if a[i]==b[j]:
            i-=1 
            j-=1 
            
        
        elif d[a[i]]>0:
            x=a[i]
            i-=1 
            d[x]-=1 
        else:
            return "NO"
    
    return "YES"


    
    
import collections


def transform(a, b):
    counter = collections.Counter()
    while a:
        while len(b) > 1 and b[-1] == b[-2]:
            counter[b.pop()] += 1
        if b and a[-1] == b[-1]:
            a.pop()
            b.pop()
        elif counter[a[-1]]:
            counter[a.pop()] -= 1
        else:
            return False
    return True


for _ in range(int(input())):
    input()
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    print("YES" if transform(a, b) else "NO")

C++ Code:

#include<bits/stdc++.h>
#define MOD 1000000007
#define MAX 200000
using namespace std;
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int t;
	cin>>t;
	int cnt = 0;
	while(t--)
	{
		int n;
		cin>>n;
		vector<int> a(n),b(n);
		for(int &x:a)cin>>x;
		for(int &x:b)cin>>x;
		bool ok = 1;
		multiset<int> st;
		for(int i=0,j=0,last=0;ok&&j<n;)
		{
			if(i<n&&a[i]==b[j])
				j++, last = a[i++];
			else if(last==b[j]&&st.find(b[j])!=st.end())	
				st.erase(st.find(b[j++]));
			else if(i<n)
				st.insert(a[i++]);
			else ok = 0;
		}
		if(ok)
			cout<<"YES"<<endl;
		else cout<<"NO"<<endl;
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

714B - Filya and Homework
31A - Worms Evolution
1691A - Beat The Odds
433B - Kuriyama Mirai's Stones
892A - Greed
32A - Reconnaissance
1236D - Alice and the Doll
1207B - Square Filling
1676D - X-Sum
1679A - AvtoBus
1549A - Gregor and Cryptography
918C - The Monster
4B - Before an Exam
545B - Equidistant String
1244C - The Football Season
1696B - NIT Destroys the Universe
1674A - Number Transformation
1244E - Minimizing Difference
1688A - Cirno's Perfect Bitmasks Classroom
219A - k-String
952A - Quirky Quantifiers
451B - Sort the Array
1505H - L BREAK into program
171E - MYSTERIOUS LANGUAGE
630D - Hexagons
1690D - Black and White Stripe
1688D - The Enchanted Forest
1674C - Infinite Replacement
712A - Memory and Crow
1676C - Most Similar Words