Problem:


Score : 600 points

Problem Statement

We have 3N cards arranged in a row from left to right, where each card has an integer between 1 and N (inclusive) written on it. The integer written on the i-th card from the left is A_i.

You will do the following operation N-1 times:

Rearrange the five leftmost cards in any order you like, then remove the three leftmost cards. If the integers written on those three cards are all equal, you gain 1 point.

After these N-1 operations, if the integers written on the remaining three cards are all equal, you will gain 1 additional point.

Find the maximum number of points you can gain.

Constraints

1 \leq N \leq 2000

1 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_{3N}

Output

Print the maximum number of points you can gain.

Sample Input 1

2
1 2 1 2 2 1

Sample Output 1

2

Let us rearrange the five leftmost cards so that the integers written on the six cards will be 2\ 2\ 2\ 1\ 1\ 1 from left to right.

Then, remove the three leftmost cards, all of which have the same integer 2, gaining 1 point.

Now, the integers written on the remaining cards are 1\ 1\ 1.

Since these three cards have the same integer 1, we gain 1 more point.

In this way, we can gain 2 points - which is the maximum possible.

Sample Input 2

3
1 1 2 2 3 3 3 2 1

Sample Output 2

1

Sample Input 3

3
1 1 2 2 2 3 3 3 1

Sample Output 3

3



Sample input:
2
1 2 1 2 2 1


Sample output:
2

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
#from numba import jit

INF = 1 << 50

def check_triple(L):
    ret = L[:]
    for l in L:
        if L.count(l) >= 3:
            for i in range(3):
                ret.remove(l)
            return True, ret
    return False, ret

def run():
    N, *A = map(int, read().split())
    dic = defaultdict(lambda : 0)
    for a in A:
        dic[a] += 1
    dp = [defaultdict(lambda:0) for i in range(N)]
    prim = sorted(A[:2])
    prim = tuple(prim)
    dp[0][prim] = 0
    for i in range(N-1):
        for key, score in dp[i].items():
            a, b = key
            temp_lis = [a,b] + A[2 + i * 3: 5 + i * 3]
            temp_lis = sorted(temp_lis)

            #print(temp_lis, '--->')
            ANS, temp_lis = check_triple(temp_lis)
            #print(temp_lis)
            if ANS:
                temp_lis = tuple(temp_lis)
                dp[i+1][temp_lis] = max(score + 1, dp[i+1][temp_lis])
            else:
                app = []
                for val in temp_lis:
                    if dic[val] > 2:
                        app.append(val)
                if len(app) < 2:
                    for v in temp_lis:
                        if not v in app:
                            app.append(v)
                            break
                app = sorted(app)
                for idx, a in enumerate(app):
                    for b in app[idx+1:]:
                        dp[i+1][(a, b)] = max(dp[i+1][(a,b)], score)

    ans = max(dp[N-1].values())

    for key, score in dp[N-1].items():
        a, b = key
        if a == b and a == A[-1]:
            ans = max(ans, score + 1)

    print(ans)



if __name__ == "__main__":
    #a = (1,2,3,4,5)
    #for i in range(1000000):
    #    check_triple(a)
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
#from numba import jit

INF = 1 << 50

def check_triple(L):
    ret = L[:]
    for l in L:
        if L.count(l) >= 3:
            val = l
            for i in range(3):
                ret.remove(l)
            return True, ret
    return False, ret

def run():
    N, *A = map(int, read().split())

    dp = [defaultdict(lambda:0) for i in range(N)]
    prim = sorted(A[:2])
    prim = tuple(prim)
    dp[0][prim] = 0
    for i in range(N-1):
        for key, score in dp[i].items():
            a, b = key
            temp_lis = [a,b] + A[2 + i * 3: 5 + i * 3]
            temp_lis = sorted(temp_lis)

            #print(temp_lis, '--->')
            ANS, temp_lis = check_triple(temp_lis)
            #print(temp_lis)
            if ANS:
                dp[i+1][tuple(temp_lis)] = max(score + 1, dp[i+1][temp_lis])
            else:
                for idx, a in enumerate(temp_lis):
                    for b in temp_lis[idx+1:]:
                        dp[i+1][(a, b)] = max(dp[i+1][(a,b)], score)

    ans = max(dp[N-1].values())

    for key, score in dp[N-1].items():
        a, b = key
        if a == b and a == A[-1]:
            ans = max(ans, score + 1)

    print(ans)



if __name__ == "__main__":
    #a = [1,2,3,4,5]
    #for i in range(1000000):
    #    check_triple(a)
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.buffer.readline
read = sys.stdin.buffer.read
#from heapq import heappop, heappush
from collections import defaultdict
sys.setrecursionlimit(10**7)
#import math
#from itertools import product, accumulate, combinations, product
#import bisect
#import numpy as np
#from copy import deepcopy
#from collections import deque
#from decimal import Decimal
#from numba import jit

INF = 1 << 50

def check_triple(L):
    ret = L[:]
    for l in L:
        if L.count(l) >= 3:
            val = l
            for i in range(3):
                ret.remove(l)
            return True, ret
    return False, ret

def run():
    N, *A = map(int, read().split())

    dp = [defaultdict(lambda:0) for i in range(N)]
    prim = sorted(A[:2])
    prim = tuple(prim)
    dp[0][prim] = 0
    for i in range(N-1):
        for key, score in dp[i].items():
            a, b = key
            temp_lis = [a,b] + A[2 + i * 3: 5 + i * 3]
            temp_lis = sorted(temp_lis)

            #print(temp_lis, '--->')
            ANS, temp_lis = check_triple(temp_lis)
            #print(temp_lis)
            if ANS:
                dp[i+1][temp_lis] = max(score + 1, dp[i+1][temp_lis])
            else:
                for idx, a in enumerate(temp_lis):
                    for b in temp_lis[idx+1:]:
                        dp[i+1][(a, b)] = max(dp[i+1][(a,b)], score)

    ans = max(dp[N-1].values())

    for key, score in dp[N-1].items():
        a, b = key
        if a == b and a == A[-1]:
            ans = max(ans, score + 1)

    print(ans)



if __name__ == "__main__":
    #a = [1,2,3,4,5]
    #for i in range(1000000):
    #    check_triple(a)
    run()

Submission status: Runtime Error

Solution code:
N = int(input())
A = [int(a) for a in input().split()] + [0] * 2
X = [[-10**10] * (N+1) for _ in range(N+1)]
X[A[0]][A[1]] = 0
ans = 0
ma = 0
MA = [-10**10] * (N+1)
MA[A[0]] = MA[A[1]] = 0
for i in range(N):
    B = A[i*3+2:i*3+5]
    cnt = len(set(B))
    if cnt == 1:
        ans += 1
    elif cnt == 2:
        a1 = B[0]^B[1]^B[2]
        a2 = (sum(B) - a1) // 2
        X[a1], X[a1][a2], X[a2][a2] = [max(X[a2][j] + 1, X[j][a2] + 1, X[a1][j], X[j][a1]) for j in range(N+1)], max(X[a1][a2], X[a2][a2] + 1, ma), max(ma, X[a2][a2], X[a1][a1] + 1)
        ma = max(ma, X[a2][a2], max(X[a1]))
        MA = [max(MA[j], X[a1][j]) for j in range(N+1)]
        MA[a1] = max(MA[a1], max(X[a1]))
        MA[a2] = max(MA[a2], X[a2][a2])
    else:
        a, b, c = B
        X[a][b], X[a][c], X[b][c] = max(X[a][b], ma, X[c][c] + 1), max(X[a][c], ma, X[b][b] + 1), max(X[b][c], ma, X[a][a] + 1)
        X[a], X[b], X[c] = [max(A[a][j], MA[j]) for j in range(N+1)], [max(A[b][j], MA[j]) for j in range(N+1)], [max(A[c][j], MA[j]) for j in range(N+1)]
        MA[a] = max(MA[a], X[a][b], X[a][c])
        MA[b] = max(MA[b], X[a][b], X[b][c])
        MA[c] = max(MA[c], X[a][c], X[b][c])
        ma = max(ma, X[a][b], X[a][c], X[b][c])

print(ans + max(ma, max(max(x) for x in X)))

Submission status: Runtime Error

Solution code:
import sys
from collections import Counter


def giveup(count, thr):
    for i in range(n):
        if count[i] >= thr:
            count[i] = 3


n, *aaa = map(int, sys.stdin.buffer.read().split())
aaa = [a - 1 for a in aaa]
count = [0] * n
ans = 0
for i in range(5):
    a = aaa[i]
    c = count[a]
    count[a] += 1
    if c == 2:
        ans += 1
        continue

for j in range(n - 2):
    cnt = Counter(aaa[5 + j * 3:8 + j * 3])
    if len(cnt) == 1:
        count[aaa[5 + j * 3]] = 3
        ans += 1
    elif len(cnt) == 2:
        (a2, _), (a1, _) = cnt.most_common()
        if count[a2] == 1:
            ans += 1
            giveup(count, 2)
        elif count[a1] == 2:
            ans += 1
            giveup(count, 1)
        count[a2] += 2
        count[a1] += 1
    else:
        for a in cnt:
            if count[a] == 2:
                ans += 1
                giveup(count, 1)
            count[a] += 1

if count[aaa[-1]] == 2:
    ans += 1

print(ans)

Submission status: Runtime Error

Solution code:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.NoSuchElementException;
import java.util.function.IntUnaryOperator;
import java.util.function.LongUnaryOperator;


public class Main {
    public static void main(String[] args) throws Exception {
        Field f = System.out.getClass().getDeclaredField("autoFlush");
        f.setAccessible(true);
        f.set(System.out, false);
        execute(System.in, System.out);
    }

    public static void execute(InputStream in, OutputStream out) {
        ExtendedScanner s = new ExtendedScanner(in);
        Out o = new Out(out);
        solve(s, o);
        o.flush();
        o.close();
    }

    public static void solve(ExtendedScanner sc, Out out) {
        int n = sc.nextInt();
        int[] a = sc.ints(3 * n);
        if (n == 1) {
            out.writeln(a[0] == a[1] && a[1] == a[2] ? 1 : 0);
            return;
        }
        int[][][] ft = new int[5][5][5];
        int[][][] sd = new int[5][5][5];
        for (int i = 0; i < 3; i++) {
            for (int j = i + 1; j < 4; j++) {
                for (int k = j + 1; k < 5; k++) {
                    ft[i][j][k] = -1;
                    sd[i][j][k] = -1;
                    for (int l = 0; l < 5; l++) {
                        if (l != i && l != j && l != k) {
                            if (ft[i][j][k] < 0) ft[i][j][k] = l;
                            else sd[i][j][k] = l;
                        }
                    }
                }
            }
        }
        int max = 0;
        HashMap<IntPair, Integer> set = new HashMap<>();
        for (int i = 0; i < 3; i++) {
            for (int j = i + 1; j < 4; j++) {
                for (int k = j + 1; k < 5; k++) {
                    int s = 0;
                    if (a[i] == a[j] && a[j] == a[k]) {
                        max = 1;
                        s = 1;
                    }
                    IntPair p = new IntPair(a[ft[i][j][k]], a[sd[i][j][k]]);
                    if (set.getOrDefault(p, 0) <= s) set.put(p, s);
                }
            }
        }
        
        for (int x = 1; x < n - 1; x++) {
            HashMap<IntPair, Integer> nxt = new HashMap<>();
            int m = max;
            for (var e : set.entrySet()) {
                IntPair p = e.getKey();
                int score = e.getValue();
                if (score <= m - 1 || score + 1 <= max - 1) continue;
                for (int i = 0; i < 3; i++) {
                    int vi = i == 0 ? p.fst : i == 1 ? p.snd : a[3 * x + i];
                    for (int j = i + 1; j < 4; j++) {
                        int vj = j == 1 ? p.snd : a[3 * x + j];
                        for (int k = j + 1; k < 5; k++) {
                            int vk = a[3 * x + k];
                            int s = score;
                            if (vi == vj && vj == vk) {
                                max = Math.max(max, ++s);
                            }
                            int fs = ft[i][j][k];
                            int sn = sd[i][j][k];
                            int vf = fs == 0 ? p.fst : fs == 1 ? p.snd : a[3 * x + fs];
                            int vs = sn == 0 ? p.fst : sn == 1 ? p.snd : a[3 * x + sn];
                            IntPair q = new IntPair(vf, vs);
                            if (nxt.getOrDefault(q, 0) <= s && s >= max - 1) nxt.put(q, s);
                        }
                    }
                }
            }
            var tmp = nxt; nxt = set; set = tmp;
        }
        for (var e : set.entrySet()) {
            IntPair p = e.getKey();
            int s = e.getValue();
            max = Math.max(max, s + (p.fst == p.snd && p.fst == a[3 * n - 1] ? 1 : 0));
        }
        out.writeln(max);
    }
}


/**
 * @author https://atcoder.jp/users/suisen
 */
class BasicScanner {
    private final InputStream in;
    private final byte[] buf = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;
    public BasicScanner(InputStream in) {this.in = in;}
    private boolean hasNextByte() {
        if (ptr < buflen) return true;
        ptr = 0;
        try {buflen = in.read(buf);}
        catch (final IOException e) {e.printStackTrace();}
        return buflen > 0;
    }
    private int readByte() {return hasNextByte() ? buf[ptr++] : -1;}
    public boolean hasNext() {
        while (hasNextByte() && !(33 <= buf[ptr] && buf[ptr] <= 126)) ptr++;
        return hasNextByte();
    }
    private StringBuilder nextSequence() {
        if (!hasNext()) throw new NoSuchElementException();
        final StringBuilder sb = new StringBuilder();
        int b = readByte();
        while (33 <= b && b <= 126) {sb.appendCodePoint(b); b = readByte();}
        return sb;
    }
    public char nextChar() {
        return (char) readByte();
    }
    public String next() {
        return nextSequence().toString();
    }
    public String next(int len) {
        return new String(nextChars(len));
    }
    public char[] nextChars() {
        final StringBuilder sb = nextSequence();
        int l = sb.length();
        char[] dst = new char[l];
        sb.getChars(0, l, dst, 0);
        return dst;
    }
    public char[] nextChars(int len) {
        if (!hasNext()) throw new NoSuchElementException();
        char[] s = new char[len];
        int i = 0;
        int b = readByte();
        while (33 <= b && b <= 126 && i < len) {s[i++] = (char) b; b = readByte();}
        if (i != len) throw new NoSuchElementException(String.format("length %d is longer than the sequence.", len));
        return s;
    }
    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {minus = true; b = readByte();}
        if (b < '0' || '9' < b) throw new NumberFormatException();
        while (true) {
            if ('0' <= b && b <= '9') n = n * 10 + b - '0';
            else if (b == -1 || !(33 <= b && b <= 126)) return minus ? -n : n;
            else throw new NumberFormatException();
            b = readByte();
        }
    }
    public int nextInt() {return Math.toIntExact(nextLong());}
    public double nextDouble() {return Double.parseDouble(next());}
}


/**
 * @author https://atcoder.jp/users/suisen
 */
class Out {
    private final OutputStream out;
    private byte[] buf = new byte[1024];
    private int ptr = 0;
    private static final int AUTO_FLUSH_THRETHOLD = 1 << 17;

    public Out(OutputStream out) {
        this.out = out;
    }

    public void flush() {
        try {
            out.write(buf, 0, ptr);
            out.flush();
            ptr = 0;
        } catch (IOException e) {e.printStackTrace();}
    }

    public void close() {
        try {out.close();} catch (IOException e) {e.printStackTrace();}
    }

    public Out writeln() {return write('\n');}
    public Out writeln(Object o) {return write(o).write('\n');}
    public Out writeln(String s) {return write(s).write('\n');}
    public Out writeln(char[] c) {return write(c).write('\n');}
    public Out writeln(char   c) {return write(c).write('\n');}
    public Out writeln(byte   b) {return write(b).write('\n');}
    public Out writeln(int    x) {return write(x).write('\n');}
    public Out writeln(long   x) {return write(x).write('\n');}
    public Out writeln(double d) {return write(d).write('\n');}

    public Out writeSpace() {return write(' ');}
    
    public Out write(Object o) {
        return write(o.toString());
    }

    public Out write(String s) {
        try {
            Field strValueField = s.getClass().getDeclaredField("value");
            strValueField.setAccessible(true);
            byte[] b = (byte[]) strValueField.get(s);
            int l = s.length();
            if (l > AUTO_FLUSH_THRETHOLD) {
                flush();
                int i = 0;
                while (i + AUTO_FLUSH_THRETHOLD < l) {
                    out.write(b, i, AUTO_FLUSH_THRETHOLD);
                    out.flush();
                    i += AUTO_FLUSH_THRETHOLD;
                }
                ensureCapacity(l - i);
                System.arraycopy(b, i, buf, 0, l - i);
                ptr = l - i;
            } else {
                ensureCapacity(ptr + l);
                System.arraycopy(b, 0, buf, ptr, l);
                ptr += l;
            }
        } catch (Exception e) {e.printStackTrace();}
        return this;
    }

    public Out write(char[] c) {
        int l = c.length;
        if (l > AUTO_FLUSH_THRETHOLD) {
            flush();
            ensureCapacity(AUTO_FLUSH_THRETHOLD);
            int i = 0;
            while (i + AUTO_FLUSH_THRETHOLD < l) {
                for (int j = 0; j < AUTO_FLUSH_THRETHOLD; j++) {
                    buf[ptr++] = (byte) c[i + j];
                }
                flush();
                i += AUTO_FLUSH_THRETHOLD;
            }
            for (; i < l; i++) {
                buf[ptr++] = (byte) c[i];
            }
        } else {
            ensureCapacity(ptr + l);
            for (char ch : c) buf[ptr++] = (byte) ch;
        }
        return this;
    }

    public Out write(char c) {
        ensureCapacity(ptr + 1);
        buf[ptr++] = (byte) c;
        return this;
    }

    public Out write(byte b) {
        ensureCapacity(ptr + 1);
        buf[ptr++] = b;
        return this;
    }

    public Out write(int x) {
        if (x == 0) {
            ensureCapacity(ptr + 1);
            buf[ptr++] = '0';
            return this;
        }
        int d = stringSize(x);
        ensureCapacity(ptr + d);
        if (x < 0) {
            buf[ptr++] = '-';
            x = -x;
            d--;
        }
        int j = ptr + d; 
        while (x > 0) {
            buf[--j] = (byte) ('0' + (x % 10));
            x /= 10;
        }
        ptr += d;
        return this;
    }

    public Out write(long x) {
        if (x == 0) {
            ensureCapacity(ptr + 1);
            buf[ptr++] = '0';
            return this;
        }
        int d = stringSize(x);
        ensureCapacity(ptr + d);
        if (x < 0) {
            buf[ptr++] = '-';
            x = -x;
            d--;
        }
        int j = ptr + d; 
        while (x > 0) {
            buf[--j] = (byte) ('0' + (x % 10));
            x /= 10;
        }
        ptr += d;
        return this;
    }

    public Out write(double d) {
        return write(Double.toString(d));
    }

    private void ensureCapacity(int cap) {
        if (cap > AUTO_FLUSH_THRETHOLD) {
            flush();
        }
        if (cap >= buf.length) {
            int newLength = buf.length;
            while (newLength < cap) newLength <<= 1;
            byte[] newBuf = new byte[newLength];
            System.arraycopy(buf, 0, newBuf, 0, buf.length);
            buf = newBuf;
        }
    }
    private static int stringSize(long x) {
        int d = 1;
        if (x >= 0) {d = 0; x = -x;}
        long p = -10;
        for (int i = 1; i < 19; i++, p *= 10) if (x > p) return i + d;
        return 19 + d;
    }
    private static int stringSize(int x) {
        int d = 1;
        if (x >= 0) {d = 0; x = -x;}
        int p = -10;
        for (int i = 1; i < 10; i++, p *= 10) if (x > p) return i + d;
        return 10 + d;
    }
}


/**
 * @author https://atcoder.jp/users/suisen
 */
final class IntPair {
    public int fst, snd;
    public IntPair(final int fst, final int snd) {this.fst = fst; this.snd = snd;}
    @Override @SuppressWarnings("all")
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (!(o instanceof IntPair)) return false;
        final IntPair p = (IntPair) o;
        return this.fst == p.fst && this.snd == p.snd;
    }
    @Override
    public int hashCode() {
        return fst * 10000 + snd;
    }
    @Override
    public String toString() {return "(" + this.fst + ", " + this.snd + ")";}
}


/**
 * @author https://atcoder.jp/users/suisen
 */
final class ExtendedScanner extends BasicScanner {
    public ExtendedScanner(InputStream in) {super(in);}
    public int[] ints(final int n) {
        final int[] a = new int[n];
        Arrays.setAll(a, $ -> nextInt());
        return a;
    }
    public int[] ints(final int n, final IntUnaryOperator f) {
        final int[] a = new int[n];
        Arrays.setAll(a, $ -> f.applyAsInt(nextInt()));
        return a;
    }
    public int[][] ints(final int n, final int m) {
        final int[][] a = new int[n][];
        Arrays.setAll(a, $ -> ints(m));
        return a;
    }
    public int[][] ints(final int n, final int m, final IntUnaryOperator f) {
        final int[][] a = new int[n][];
        Arrays.setAll(a, $ -> ints(m, f));
        return a;
    }
    public long[] longs(final int n) {
        final long[] a = new long[n];
        Arrays.setAll(a, $ -> nextLong());
        return a;
    }
    public long[] longs(final int n, final LongUnaryOperator f) {
        final long[] a = new long[n];
        Arrays.setAll(a, $ -> f.applyAsLong(nextLong()));
        return a;
    }
    public long[][] longs(final int n, final int m) {
        final long[][] a = new long[n][];
        Arrays.setAll(a, $ -> longs(m));
        return a;
    }
    public long[][] longs(final int n, final int m, final LongUnaryOperator f) {
        final long[][] a = new long[n][];
        Arrays.setAll(a, $ -> longs(m, f));
        return a;
    }
    public char[][] charArrays(final int n) {
        final char[][] c = new char[n][];
        Arrays.setAll(c, $ -> nextChars());
        return c;
    }
    public char[][] charArrays(final int n, final int m) {
        final char[][] c = new char[n][];
        Arrays.setAll(c, $ -> nextChars(m));
        return c;
    }
    public double[] doubles(final int n) {
        final double[] a = new double[n];
        Arrays.setAll(a, $ -> nextDouble());
        return a;
    }
    public double[][] doubles(final int n, final int m) {
        final double[][] a = new double[n][];
        Arrays.setAll(a, $ -> doubles(m));
        return a;
    }
    public String[] strings(final int n) {
        final String[] s = new String[n];
        Arrays.setAll(s, $ -> next());
        return s;
    }
    public String[] strings(final int n, final int m) {
        final String[] s = new String[n];
        Arrays.setAll(s, $ -> next(m));
        return s;
    }
}

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.append(0)
A.append(0)

ans = 0
doubles = set()
singles = set()
if A[0] == A[1]:
  doubles.add(A[0])
  singles.add(A[0])
else:
  singles.add(A[0])
  singles.add(A[1])
  
for i in range(0, N):
  a = A[2+3*i] 
  b = A[2+3*i+1]
  c = A[2+3*i+2]
  #print(ans, doubles, singles, a, b, c)
  if a == b == c:
    ans += 1
    continue
  d = None
  if a == b or b == c:
    d = b
  if  c == a:
    d = a
  #print(d)
  if d == None:
    match = False
    for x in (a, b, c):
      if x in doubles:
        match = True
        break
    if match:
      doubles.clear()
      singles.remove(x)
      for x2 in (a, b, c):
        if x2 != x:
          singles.append(x2)
      
      ans += 1
      continue
    else:
      for x in (a, b, c):
        singles.append(x)
  else:
    for x in (a, b, c):
      if x != d:
        s = x
    if d in singles:
      if s in singles:
        doubles.add(s)
      singles.add(s)
      if d in doubles:
        doubles.clear()
        ans+=1
        continue
      else:
        doubles.clear()
        singles.remove(d)
        ans += 1
        continue
        
    if s in doubles:
        doubles.clear()
        singles.remove(s)
        singles.add(d)
        doubles.add(d)
        ans+=1
        continue
    if s in singles:
        doubles.add(s)
        singles.add(s)
    else:
        singles.add(s)
    singles.add(d)
    doubles.add(d)
#print(doubles)
print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split()))
A.append(0)
A.append(0)

ans = 0
doubles = set()
singles = set()
if A[0] == A[1]:
  doubles.add(A[0])
  singles.add(A[0])
else:
  singles.add(A[0])
  singles.add(A[1])
  
for i in range(0, N):
  a = A[2+3*i] 
  b = A[2+3*i+1]
  c = A[2+3*i+2]
  #print(ans, doubles, singles, a, b, c)
  if a == b == c:
    ans += 1
    continue
  d = None
  if a == b or b == c:
    d = b
  if  c == a:
    d = a
  #print(d)
  if d == None:
    match = False
    for x in (a, b, c):
      if x in doubles:
        match = True
        break
    if match:
      doubles.clear()
      singles.remove(x)
      for x2 in (a, b, c):
        if x2 != x:
          singles.append(x2)
      
      ans += 1
      continue
    else:
      for x in (a, b, c):
        singles.append(x)
  else:
    for x in (a, b, c):
      if x != d:
        s = x
    if d in singles:
      if s in singles:
        doubles.add(s)
      singles.add(s)
      if d in doubles:
        doubles.clear()
        ans+=1
        continue
      else:
        doubles.clear()
        singles.remove(d)
        ans += 1
        continue
        
    if s in doubles:
        doubles.clear()
        singles.remove(s)
        singles.add(d)
        doubles.add(d)
        ans+=1
        continue
    if s in singles:
        doubles.add(s)
    else:
        singles.add(s)
    singles.add(d)
    doubles.add(d)
#print(doubles)
print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())
num = list(map(int, input().split()))
ans = 0
frag = 0
A = 0
B = 0
C = 0
for i in range(n - 1):
    for a in range(5):
        for b in range(a + 1, 5):
            for c in range(b + 1, 5):
                if num[a] == num[b] == num[c]:
                    frag = 1
                    A = a
                    B = b
                    C = c
                    ans += 1
                    break
            if frag == 1:
                break
        if frag == 1:
            break
    if frag == 1:
        del num[A]
        del num[B]
        del num[C]
        frag = 0
    else:
        for a in range(5):
            for b in range(a + 1, 8):
                for c in range(b + 1, 8):
                    if num[a] == num[b] == num[c]:
                        frag = 1
                        A = a
                        B = b
                        C = c
                        ans += 1
                        break
                if frag == 1:
                    break
            if frag == 1:
                break
if num[0] == num[1] == num[2]:
    ans += 1
print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())
num = list(map(int, input().split()))
ans = 0
frag = 0
A = 0
B = 0
C = 0
for i in range(n - 1):
    for a in range(i, i + 5):
        for b in range(a, i + 5):
            for c in range(b, i + 5):
                if num[a] == num[b] == num[c]:
                    frag = 1
                    A = a
                    B = b
                    C = c
                    ans += 1
                    break
            if frag == 1:
                break
        if frag == 1:
            break
    if frag == 1:
        del num[A]
        del num[B]
        del num[C]
        frag = 0
if num[0] == num[1] == num[2]:
    ans += 1
print(ans)

Submission status: Runtime Error

Solution code:
#途中まで
N = int(input())
A = list(map(int, input().split()))

DP = [[-1] * (N + 1) for _ in range(N + 1)]

R = {}
for i in range(5):
  a = A[i]
  if a in R:
    R[a] += 1
  else:
    R[a] = 1

Flag = 0
for i in R.keys():
  if R[i] >= 3:
    Flag = 1
    R[i] -= 3

L = []
for i in R.keys():
  if R[i] == 2:
    DP[i][i] = Flag
  elif R[i] == 1:
    L.append(R[i])

for i in range(len(L) - 1):
  for j in range(i + 1, len(L)):
    DP[L[i]][L[j]] = Flag

print(DP)

for i in range(5, N * 3, 3):
  R = {}
  for j in range(i, i + 3):
    pass

Submission status: Runtime Error

Solution code:
from collections import deque
N=int(input())
A=list(map(int,input().split()))
A = deque(A)
P=[0 for i in range(N+1)]
count=0
for i in A:
    P[i]=(P[i]+1)%3
for i in range(N-1):
    B=dict()
    D=[]
    for j in range(5):
        a=A.popleft()
        if a not in B:
            B[a]=1
            P[a]=(P[a]+2)%3
        else:
            B[a]+=1
            P[a]=(P[a]+2)%3
    for k in B:
        if B[k]+P[k]>=3 and B[k]<3:
            D.append([3-P[k],k])
    D.sort()
    capa=0
    for l,x in D:
        for m in range(l):
            if capa<2:
                A.appendleft(x)
                P[x]=(P[x]+1)%3
                B[x]-=1
                capa+=1
    for r in B:
        if B[r]==3:
            count+=1
        elif B[r]<3 and capa<2:
            for s in range(min(2-capa,B[r])):
                A.appendleft(r)
                P[r]=(P[r]+1)%3
                capa+=1
if A[0]==A[1]==A[2]:
    count+=1
print(count)

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split()))
count = [0] * N
last = [0] * N
used = [0] * N

if A == [1, 1, 1]:
  print(1)
  quit()

for i in range(3 * N):
  now = A[i] - 1
  count[now] += 1
  if count[now] == 3:
    last[now] = i
  #print(now)  
#print(count, last)    

score = 0
now = [A[0], A[1], A[2], A[3], A[4]]
for i in range(N - 1):
  L = [0] * 5
  for j in range(5):
    L[j] = [last[now[j] - 1], j, used[now[j] - 1]]
  L = sorted(L)
  #print(L)
  if L[1][0] == L[2][0]:
    if L[0][0] == L[1][0]:
      score += 1
      one, two = L[3][1], L[4][1]
    elif L[2][0] == L[3][0]:
      score += 1
      one, two = L[0][1], L[4][1]
    else:
      L = sorted(L, key = lambda x:x[2])
      one, two = L[0][1], L[1][1]
      used[L[0][2]] = 1
      used[L[0][3]] = 1
      used[L[0][4]] = 1
  elif (L[2][0] == L[3][0]) and (L[3][0] == L[4][0]):
    score += 1
    one, two = L[0][1], L[1][1]
  else:
    L = sorted(L, key = lambda x:x[2])
    one, two = L[0][1], L[1][1]
    used[L[0][2]] = 1
    used[L[0][3]] = 1
    used[L[0][4]] = 1
    
  if i != N - 2:
    now = [A[one], A[two], A[5 + 3 * i], A[6 + 3 * i], A[7 + 3 * i]]
  else:
    now = [A[one], A[two], A[-1]]
  
if now[0] == now[1] and now[1] == now[2]:
  score += 1
    
print(score)