1630C - Paint the Middle - CodeForces Solution


Array Stack

Please click on ads to support us..

Python Code:

import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
Y=lambda:map(sub,Z().split())
sub=lambda x:int(x)-1
n=int(Z());a=[*Y()];L=[-1]*n
for i in range(n):L[a[i]]=i
for x in range(n):
    if x!=L[a[x]]:break
s={a[x]};ns=set();r=0
for i in range(x+1,n):
    if s:
        if i==L[a[i]]:
            if a[i]in ns:ns.remove(a[i])
            elif a[i]in s:
                s.remove(a[i])
                if not s:s,ns=ns,set();r-=1
        elif a[i]not in s:ns.add(a[i])
        r+=1
    elif i!=L[a[i]]:s.add(a[i])
print(r)

C++ Code:

#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

typedef long long ll;
typedef vector<int> veci;
typedef vector<ll> vecll;

long long mod = 998244353;

int main(){
    int n;
    cin >> n;
    vector<int> a(n, 0);
    for(auto& x : a) cin >> x;
   
    map<int, int> l, r;
    for(int i = n - 1; i >= 0; --i){
        if(r.find(a[i]) == r.end()) r[a[i]] = i;
    }

    int m = 0, begin = 0, end, pivot = 1;
    while(begin < n){
        //cerr << "begin : " << begin <<endl;
        end = r[a[begin]];
        ++m;
        //cerr << "increment " << m << endl;
        pivot = max(pivot, begin + 1);
        int new_begin = -1, new_end = -1;
        while(pivot < end){
            if(r[a[pivot]] > end){
                if(r[a[pivot]] > new_end){
                    new_end = r[a[pivot]];
                    new_begin = pivot;
                }
            }
            ++pivot;
        }
        if(new_begin == -1){
            //cerr << "next chunk" << endl;
            if(end > begin) ++m;
            //cerr << "increment " << m << endl;
            begin = end + 1;
        }
        else{
            begin = new_begin;
        }
    }
    cout << n - m << endl;
}


Comments

Submit
0 Comments
More Questions

383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements
733. Flood Fill
206. Reverse Linked List
83. Remove Duplicates from Sorted List
116. Populating Next Right Pointers in Each Node
145. Binary Tree Postorder Traversal
94. Binary Tree Inorder Traversal
101. Symmetric Tree
77. Combinations
46. Permutations
226. Invert Binary Tree
112. Path Sum
1556A - A Variety of Operations
136. Single Number
169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence