Problem:


Score : 700 points

Problem Statement

There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.

Snuke will perform the following operation zero or more times:

Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.

Find the number of possible final sequences of colors of the stones, modulo 10^9+7.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq C_i \leq 2\times 10^5(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
C_1
:
C_N

Output

Print the number of possible final sequences of colors of the stones, modulo 10^9+7.

Sample Input 1

5
1
2
1
2
2

Sample Output 1

3

We can make three sequences of colors of stones, as follows:

(1,2,1,2,2), by doing nothing.

(1,1,1,2,2), by choosing the first and third stones to perform the operation.

(1,2,2,2,2), by choosing the second and fourth stones to perform the operation.

Sample Input 2

6
4
2
5
4
2
4

Sample Output 2

5

Sample Input 3

7
1
3
1
2
3
3
2

Sample Output 3

5



Sample input:
5
1
2
1
2
2


Sample output:
3

Submission status: Accepted

Solution code:
from collections import Counter


def main():
    n = int(input())
    c = [input()]
    for _ in range(n - 1):
        now = input()
        if now != c[-1]:
            c.append(now)
    mod = 10 ** 9 + 7
    memo = Counter(c)
    # memo[i] := 色がiであるような石jについてのdp[j]の値の合計値（適宜更新する）
    for k in memo.keys():
        memo[k] = 0
    dp = [0 for _ in range(2 * 10 ** 5 + 10)]
    dp[0] = 1
    for i in range(len(c)):
        dp[i + 1] += memo[c[i]] + dp[i]
        # それ以前のdp[i]通りに加えて，c[i] -- (0 <= j < i and c[i] == c[j])間の
        # memo[c[i]]通りの区間の両端を定めることができるから，この遷移式が成り立つ．
        memo[c[i]] += dp[i]
        dp[i + 1] %= mod
        memo[c[i]] %= mod
    print(dp[len(c)])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
##import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect
mod=10**9+7
n=int(input())
res=[0]*(2*10**5+1)
d=[0]*(n+1)
c_b=0
d[0]=1
for i in range(n):
    c=int(input())
    if c_b==c:
        d[i+1]=d[i]
    else:
        d[i+1]=d[i]+res[c]
        res[c]+=d[i]
        res[c]%=mod
    d[i+1]%=mod
    c_b=c
print(d[n])

Submission status: Accepted

Solution code:
MOD = 10**9 + 7
N = int(input())
C = [int(input()) for _ in range(N)]

L = [-1]*(2*10**5+10)
dp = [-1]*(2*10**5+10)
dp[0] = 1

for i in range(N):
    if L[C[i]] == -1:
        dp[i+1] = dp[i]
    elif C[i] == C[i-1]:
        dp[i+1] = dp[i]
    else:
        dp[i+1] = dp[i]+dp[L[C[i]]]
    dp[i+1] %= MOD
    L[C[i]] = i+1
print(dp[N])

Submission status: Accepted

Solution code:
'''
研究室PCでの解答
'''
import math
#import numpy as np
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 #998244353
dir = [(-1,0),(1,0),(0,-1),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"


def main():
    n = int(ipt())
    cp = [-1 for i in range(2*10**5+1)]
    dp = [0]*(n+1)
    dp[0] = 1
    for i in range(1,n+1):
        dp[i] += dp[i-1]
        c = int(ipt())
        pc = cp[c]
        if pc != -1 and pc != i-1:
            dp[i] += dp[pc]
        cp[c] = i
        dp[i] %= mod

    print(dp[-1])


    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import math
import copy
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)


def solve():
    n = getN()
    li = []
    for i in range(n):
        li.append(getN())

    last = dict()
    ans = [0 for i in range(n+1)]
    ans[0] = 1
    for i in range(1, n+1):
        tgt = li[i-1]
        if i >= 2 and tgt == li[i-2]:
            last[tgt] = i
            ans[i] = ans[i-1]
            continue
        if tgt not in last:
            ans[i] = ans[i-1]
            last[tgt] = i
        else:
            ans[i] = ans[i-1] + ans[last[tgt]]
            last[tgt] = i

    print(max(ans) % MOD)


def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
n=int(input())
cc=[int(input()) for _ in range(n)]


c=[cc[0]]
for i in range(1,n):
    if cc[i]!=cc[i-1]:
        c.append(cc[i])

n=len(c)

right_index=[-1]*n
tmp_right_index=[-1]*(max(c)+1)

for i in range(n):
    if tmp_right_index[c[i]]==-1:
        tmp_right_index[c[i]]=i
    else:
        right_index[i]=tmp_right_index[c[i]]
        tmp_right_index[c[i]]=i

dp=[0]*n
mod=10**9+7
#print(0,c)
for i in range(n):
    if i==0:
        dp[i]=1
    else:
        if right_index[i]==-1:
            dp[i]+=dp[i-1]%mod
        else:
            dp[i]+=dp[i-1]+dp[right_index[i]]%mod

print(dp[-1]%mod)

Submission status: Accepted

Solution code:
import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

n = int(input())
C = [int(input()) for i in range(n)]
pairs = [-1]*(n+1)
data = [-1]*(2*10**5+1)
for i,ci in enumerate(C):
  if data[ci] != -1 and abs(i-data[ci]) != 1:
    pairs[data[ci]] = i
  data[ci] = i
imos = [0] * (n+1)
for i in range(n-1,-1,-1):
  # ペアを持たないとき
  if pairs[i] == -1:
    imos[i] = imos[i+1]
    # print(i,imos[i],imos[i+1])
  else:
    j = pairs[i]
    imos[i] = imos[i+1] + imos[j] + 1
    imos[i] %= mod
  # ans += imos[i] + imos[j]
  # ans %= mod
  # imos[i-1] += imos[i]
print((imos[0]+1)%mod)
# print((ans+1)%mod)
# print(imos)

Submission status: Accepted

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
# list(map(int, list(input()))) # スペースがない数字リストを読み込み
import math
import fractions
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
import collections
from collections import Counter
from collections import deque
import pprint
import itertools

sr = lambda: input()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""


def factorization(n):
    arr = []
    temp = n
    if n == 1:
        return arr

    for i in range(2, int(-(-n ** 0.5 // 1)) + 1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr.append([i, cnt])

    if temp != 1:
        arr.append([temp, 1])

    if arr == []:
        arr.append([n, 1])

    return arr


# a^n
def power(a, n, mod):
    x = 1
    while n:
        if n & 1:
            x *= a % mod
        n >>= 1
        a *= a % mod
    return x % mod


# n*(n-1)*...*(l+1)*l
def kaijo(n, l, mod):
    if n == 0:
        return 1
    a = n
    tmp = n - 1
    while (tmp >= l):
        a = a * tmp % mod
        tmp -= 1
    return a

# Union Find
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# 約数生成
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    divisors.sort()
    return divisors

inf = 10 ** 18
mod = 10 ** 9 + 7

n = ir()
c = [ir() for i in range(n)]
dp = [0 for i in range(n+1)]
dp[0] = 1
pre_ind = [-inf for i in range(2*(10**5)+1)]
num_ind = [0 for i in range(2*(10**5)+1)]
for i in range(n):
    now = c[i]
    if pre_ind[now] == -inf or pre_ind[now] == i-1:
        dp[i+1]=dp[i]
        if pre_ind[now] == -inf:
            num_ind[now] = dp[i+1]
        pre_ind[now] = i
    else:
        dp[i+1]=(dp[i]+num_ind[now])%mod
        num_ind[now] = dp[i+1]
        pre_ind[now] = i
print(dp[n])

Submission status: Accepted

Solution code:
import sys

input = sys.stdin.readline
P = 10 ** 9 + 7


def main():
    N = int(input())
    C = [None] * N
    for i in range(N):
        C[i] = int(input())

    MAX_C = 2 * 10 ** 5
    C = [-1] + C
    D = [-1] * (MAX_C + 1)
    dp = [0] * (N + 1)
    dp[0] = 1
    for i in range(N):
        if C[i + 1] == C[i]:
            dp[i + 1] = dp[i]
        else:
            j = D[C[i + 1]]
            if j != -1:
                dp[i + 1] = dp[i] + dp[j]
            else:
                dp[i + 1] = dp[i]
        dp[i + 1] %= P
        D[C[i + 1]] = i + 1

    ans = dp[N]
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys,math,collections,itertools
input = sys.stdin.readline

N = int(input())
ans = 1
m=10**9+7
c=[]
for _ in range(N):
    c.append(int(input()))
dp = [1]*(N+1)#dp[i] i番目までの並び替え総数
last_color = [-1]*(max(c)+1)#最後にその色が出たindexの保存
last_color[c[0]] =0
for i in range(1,N):
    if c[i]==c[i-1]:#同じ色が続くとリバーシできない
        dp[i] = dp[i-1]
    else:
        if last_color[c[i]]==-1:#初めての色はリバーシできない
            dp[i] = dp[i-1]
            last_color[c[i]]=i
        else:#挟める石があるし色が連続してない
            dp[i] = dp[i-1]+dp[last_color[c[i]]]#最後に出た石と挟むか挟まないk
            last_color[c[i]]=i
print(dp[N-1]%m)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
C = [INT() for _ in range(N)]

dp = [0]*(N+1)
dp[0] = 1
dp2 = [-1]*(max(C)+1) #前に色iが出てきたインデックスの保存

for i in range(1, N+1):
	p = dp2[C[i-1]]
	if 1 < i-p and p != -1:
		dp[i] += dp[p]
	dp[i] += dp[i-1]
	dp2[C[i-1]] = i
	dp[i] %= mod

print(dp[N])

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
C = [INT() for _ in range(N)]

dp = [0]*(N+1)
dp[0] = 1
dp2 = [-1]*(max(C)+1) #前に色iが出てきたインデックスの保存

for i in range(1, N+1):
	p = dp2[C[i-1]]  # 色C[i-1]が前に出てきたインデックス
	if 1 < i-p and p != -1:
		dp[i] += dp[p]
	dp2[C[i-1]] = i
	dp[i] += dp[i-1]
	dp[i] %= mod

print(dp[N])

Submission status: Accepted

Solution code:
MOD = 10**9 + 7
N = int(input())
C = [int(input()) for i in range(N)]
dp = [0] * (N+1)
dp_c = [0] * (2*10**5+1)
pred_ci = 0
dp[0] = 1
for i, ci in enumerate(C, 1):
    if pred_ci == ci:
        dp[i] += dp[i-1]
        continue
    dp[i] = (dp[i-1] + dp_c[ci]) % MOD
    dp_c[ci] = dp[i]
    pred_ci = ci

print(dp[N])

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
tmp = -1
c = []
for _ in range(N):
	C = INT()
	if C != tmp:
		c.append(C)
	tmp = C

n = len(c)
dic = defaultdict(int)

dp = [0]*(n+1)
dp[0] = 1

for i in range(n):
	dp[i+1] = (dp[i] + dic[c[i]])%mod
	dic[c[i]] = (dic[c[i]] + dp[i])%mod

print(dp[-1])

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n = int(readline())
    c = [-1]
    prev = -1
    for i in range(n):
        x = int(readline())
        if x != prev:
            c.append(x)
            prev = x

    l = len(c)

    dp = [0] * l
    dp[0] = 1

    idx = dict()

    for i in range(1, l):
        char = c[i]
        dp[i] += dp[i - 1]
        if idx.get(char):
            p = idx[char]
            dp[i] += dp[p]
        idx[char] = i
        dp[i] %= MOD

    print(dp[l - 1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())
mod = 10**9+7

last = {}
dp = [0]*(N+1)
dp[0] = 1
for i in range(1, N+1):
    dp[i] = dp[i-1]
    c = int(input())
    if c in last and last[c]+1<i:
        dp[i] += dp[last[c]]
        dp[i] %= mod
    last[c] = i

print(dp[N])

Submission status: Accepted

Solution code:
import sys

mod = 10**9 + 7
N = int(sys.stdin.readline())

stones = []
for _ in range(N):
    stones.append(int(sys.stdin.readline()))

left = {}
dp = [0 for _ in range(N+5)]
dp[0] = 1
for i in range(N):
    dp[i+1] = dp[i]
    # 同じ色が前回出現した位置
    c = stones[i]
    if c in left and 0 <= left[c] < i - 1:
        dp[i+1] += dp[left[c] + 1]
    
    dp[i+1] %= mod
    left[c] = i

print(dp[N])

Submission status: Accepted

Solution code:
import sys

mod = 10**9 + 7
N = int(sys.stdin.readline())

stones = []
for _ in range(N):
    stones.append(int(sys.stdin.readline()))

left = [-1 for _ in range(2*10**5+1)]
dp = [0 for _ in range(N+5)]
dp[0] = 1
for i in range(N):
    dp[i+1] = dp[i]
    # 同じ色が前回出現した位置
    c = stones[i]
    if 0 <= left[c] < i - 1:
        dp[i+1] += dp[left[c] + 1]
    
    dp[i+1] %= mod
    left[c] = i

print(dp[N])

Submission status: Accepted

Solution code:
import bisect
N = int(input())
MOD = pow(10,9)+7
C = []
dic = {}
for i in range(N):
  temp = int(input())
  C.append(temp)
  if temp not in dic:
    dic[temp] = [i]
  else:
    dic[temp].append(i)  
#print(C)
#print(dic)
dp = [0 for _ in range(N)]
dp[0] = 1
for i in range(N):
  #print(dp)
  if i>= 1 and C[i] == C[i-1]:
    dp[i] = dp[i-1]
    continue
  if i >= 1:
    dp[i] += dp[i-1]%MOD
  #print(dp,i)
  color = C[i]
  temp = bisect.bisect_left(dic[color],i)
  if temp == 0:
    continue
  loc = dic[color][temp-1]
  #print(i,temp,dp[loc])
  dp[i] += dp[loc]%MOD
print(dp[-1]%MOD)

Submission status: Accepted

Solution code:
import numpy as np

n = int(input())
tmp = [int(input()) for _ in range(n)]

c = [tmp[0]]
for x in tmp[1:]:
    if x != c[-1]:
        c.append(x)

c = np.array(c)

MOD = 10**9 + 7

# dpテーブル
dp = np.zeros(c.shape[0], dtype=np.int64)
dp[0] = 1

used = np.full(c.max() + 1, -1, dtype=np.int64)
used[c[0]] = 1

for i in range(1, c.shape[0]):
    if used[c[i]] == -1:
        dp[i] = dp[i - 1]
    else:
        dp[i] = (dp[i - 1] + dp[used[c[i]]]) % MOD
    used[c[i]] = i

print(dp[-1])

Submission status: Accepted

Solution code:
from collections import deque
from heapq import heappush, heappop
import sys
input = sys.stdin.readline


def main():
    mod = 10**9 + 7
    n = int(input())
    colors = [int(input()) for _ in range(n)]
    pos_dict = {}
    for i, color in enumerate(colors):
        if color not in pos_dict:
            pos_dict[color] = deque([])
            continue
        pos_dict[color].append(i)

    branches = []
    base = 1
    for i, color in enumerate(colors):
        if branches and branches[0][0] == i:
            _, add = heappop(branches)
            base += add
            base %= mod

        if pos_dict[color]:
            next = pos_dict[color].popleft()
            if next == i+1:
                continue
            add = base
            heappush(branches, (next, add))

    print(base % mod)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left
MOD = 10 ** 9 + 7

n = int(input())
clst = []
last = [-1 for _ in range(2 * 10 ** 5)]
before = [-1 for _ in range(2 * 10 ** 5)]
for i in range(n):
    c = int(input())
    clst.append(c - 1)
    before[i] = last[c - 1]
    last[c - 1] = i
dp = [0 for _ in range(n)]
dp[0] = 1

for i in range(1, n):
    dp[i] = dp[i - 1]
    if before[i] != -1 and before[i] != i - 1:
        pos = before[i]
        dp[i] += dp[pos]
    dp[i] %= MOD
print(dp[-1])

Submission status: Accepted

Solution code:
import bisect
MOD = 1_000_000_007
n = int(input())
b = [int(input()) - 1 for _ in range(n)]

idx = 0
a = []
while idx < n:
    a.append(b[idx])
    while idx + 1 < n and b[idx] == b[idx + 1]:
        idx += 1
    idx += 1
n = len(a)


pos = [[] for _ in range(200001)]
for i in range(n):
    pos[a[i]].append(i)

dp = [0] * (n + 1)
dp[0] = 1
for i in range(n):
    j = bisect.bisect_right(pos[a[i]], i)
    if j < len(pos[a[i]]):
        dp[pos[a[i]][j]] += dp[i]
        dp[pos[a[i]][j]] %= MOD
    dp[i+1] += dp[i]
    dp[i+1] %= MOD

print(dp[n])

Submission status: Accepted

Solution code:
mod=10**9+7
import sys
input=sys.stdin.readline
n=int(input())
c=[int(input())for i in range(n)]
last=[-1]*max(c)
last[c[0]-1]=0
dp=[0]*n
dp[0]=1
for i in range(1,n):
	dp[i]=dp[i-1]
	if c[i-1]!=c[i] and last[c[i]-1]!=-1:
		dp[i]+=dp[last[c[i]-1]]
		dp[i]%=mod
	last[c[i]-1]=i
print(dp[-1])

Submission status: Accepted

Solution code:
MOD = 10**9+7
N = int(input())
C = []
C.append(int(input()))
for i in range(N-1):
    c = int(input())
    if c == C[-1]:
        continue
    C.append(c)
#print(C)
N = len(C)
lis = [[0] for i in range(max(C)+1)]
for i in range(N):
    lis[C[i]].append(i+1)
for i in range(len(lis)):
    lis[i].append(MOD)

def binary_search(lis,i):
    ok = 0
    ng = len(lis)-1
    while ng-ok > 1:
        mid = (ok + ng)// 2
        if lis[mid] < i:
            ok = mid
        else:
            ng = mid
    return lis[ok]
#print(binary_search([0,1,2,3,4],3))
#print(lis)
dp = [0] * (N+1)
dp[0] = 1
for i in range(1,N+1):
    dp[i] += dp[i-1]
    p = binary_search(lis[C[i-1]],i)
    if p != 0:
        dp[i] += dp[p]
    dp[i] %= MOD
    #print(p)
print(dp[-1])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from bisect import bisect_left

def main():
    N, *C = map(int,open(0))
    M = max(C)
    m = 10**9+7
    # place[j]: i番目の石の位置を保持(1-index)
    place = [[] for _ in range(M+1)]
    for i in range(N):
        place[C[i]].append(i+1)
    # dp[i]: 最初からi個の石までで条件を満たす塗り方の総数
    dp = [0] * (N+1)
    dp[0] = 1
    for i in range(1,N+1):
        # 特に操作しない場合
        dp[i] += dp[i-1]
        dp[i] %= m
        
        # 操作する場合
        # 今見ているi番目の石が同じ色の石の集まりの中で何番目か
        j = bisect_left(place[C[i-1]],i)
        if j > 0:
            k = place[C[i-1]][j-1]# 同色でjより１つ前の石の位置
            if i-k > 1:
                dp[i] += dp[k]
                dp[i] %= m
    print(dp[N])

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N=I()
    C=[]
    
    #連番無視
    for i in range(N):
        c=I()
        c-=1
        if C==[]:
            C.append(c)
        else:
            if C[-1]!=c:
                C.append(c)         
            
    """
    i番目の通り数をf(i)とする．
    今，i番目までを見てて，i番目と同じ数はj,kにあるとする．
    f(i)=
         f(i-1) #iを使わない
        +f(j-1) #i-jのみ
        +f(k-1) #i-kのみ
    かな，各色ごとに，f(j-1)+f(k-1)みたいなのをまとめておく
    """    
    S=[0]*(2*10**5 + 5)
    
    ans=1
    for c in C:
        temp=ans
        ans=(ans+S[c])%mod
        S[c]=(S[c]+temp)%mod
        
    print(ans)
        
        
        
        
    

main()

Submission status: Accepted

Solution code:
def main():
    MOD = 10**9 + 7
    N = int(input())
    C = [int(input()) - 1 for _ in range(N)]
    if N == 1:
        print(1)
        return
    # |---|
    # 1-2-1-2-2
    #   |---|
    latest_indices = [-1] * (2 * (10**5))
    next_indices = [-1] * N
    for cur_index, c in enumerate(C):
        latest_index = latest_indices[c]
        if latest_index >= 0:
            next_indices[latest_index] = cur_index
        latest_indices[c] = cur_index
    dp = [0] * N
    dp[0] = 1
    for cur_index in range(N - 1):
        next_index = next_indices[cur_index]
        if next_index > cur_index + 1:
            dp[next_index] += dp[cur_index]
            dp[next_index] %= MOD
        dp[cur_index + 1] += dp[cur_index]
        dp[cur_index + 1] %= MOD
    print(dp[N - 1])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import groupby

n = int(input())
C = [key for key, _ in groupby([int(input()) for _ in range(n)])]

N = len(C)

MOD = 10 ** 9 + 7

dp = [0 for _ in range(N)]
dp[0] = 1

T = {}
T[C[0]] = 0

for i in range(1, N):
  if i == 0 or C[i - 1] == C[i] or C[i] not in T:
    dp[i] = dp[i - 1]
  else:
    j = T[C[i]]
    dp[i] = dp[i - 1] + dp[j]
  dp[i] %= MOD
  T[C[i]] = i

print(dp[N - 1])

Submission status: Accepted

Solution code:
import sys
import math
import collections
import bisect
import copy

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===


def main():
    n = ni()
    last = [-1 for _ in range(2 * 10 ** 5 + 1)]
    d = []
    dp = [INF for _ in range(n + 1)]
    dp[0] = 1

    prev = -1
    for i in range(n):
        di = ni()
        di -= 1
        if i > 0:
            if prev == di:
                d.append(-1)
                prev = di
                continue
        d.append(di)
        prev = di

    for i, di in enumerate(d):
        dp[i + 1] = dp[i]
        if di == -1:
            last[di] = i
            continue
        if last[di] != -1:
            if i - last[di] != -1:
                dp[i + 1] += dp[last[di] + 1]
                dp[i + 1] %= MOD
        last[di] = i

    print(dp[n])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import math
import collections
import bisect
import copy

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===


def main():
    n = ni()
    last = [-1 for _ in range(2 * 10 ** 5 + 1)]
    dp = [INF for _ in range(n + 1)]
    dp[0] = 1

    d = [ni()-1 for _ in range(n)]

    for i, di in enumerate(d):
        dp[i + 1] = dp[i]
        if last[di] != -1:
            if i - last[di] != 1:
                dp[i + 1] += dp[last[di] + 1]
                dp[i + 1] %= MOD
        last[di] = i

    print(dp[n])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

mod = 10**9+7
n = int(input())
seen = {}
# dp[i]: 左からi番目まで見た際の場合の数

dp = [0] * (n+1)
dp[0] = 1

for i in range(1, n+1):
    ci = input()
    j = seen.get(ci, 0)
    if j == 0:          #新しい色の追加
        dp[i]+=dp[i-1]
    elif j == i-1:      #直前と同じ
        dp[i]+=dp[i-1]
    else:
        dp[i]+=dp[i-1]  #新しい色の左以前を変える
        dp[i]+=dp[j]    #新しい色の左側を変える
        dp[i]%=mod
    seen[ci] = i
#    print(i,ci,dp,seen)
print(dp[n])

Submission status: Accepted

Solution code:
#AGC032-B
"""
dp解法。
そこまでにその色で出来た組み合わせの総和がいくつかを保持する配列を
持っておく。
"""
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0
n = int(readline())
lst1 = []
bef = -1
for i in range(n):
    res = int(readline())
    if bef == res:
        continue
    else:
        lst1.append(res)
        bef = res

n = len(lst1)
lst2 = [-1]*(2*10**5+1)
dp = [0]*(n+1)
dp[0] = 1
for i in range(1,n+1):
    c = lst1[i-1]
    if lst2[c]==-1:
        lst2[c] = i
        dp[i] = dp[i-1]
    else:
        dp[i] = (dp[i-1] + dp[lst2[c]])%(10**9+7)
        lst2[c] = i

print(dp[-1])

Submission status: Accepted

Solution code:
n,*cc = map(int, open(0).read().split())
MOD = 10**9+7

from collections import defaultdict
d = {}
dp = defaultdict(lambda: 1)

for i,c in enumerate(cc):
    dp[i] = dp[i-1]
    if c in d:
        j = d[c]
        if i - j > 1:
            dp[i] += dp[j]
            dp[i] %= MOD
    d[c] = i

print(dp[n-1])

Submission status: Accepted

Solution code:
from collections import defaultdict
def solve():
  ans = 0
  N = int(input())
  C = [int(input()) for _ in range(N)]
  d = defaultdict(lambda: -1)
  dp = [1]*N
  d[C[0]] = 0
  mod = 10**9+7
  for i in range(1,N):
    dp[i] = dp[i-1]
    if d[C[i]]>-1 and d[C[i]]!=i-1:
      dp[i] += dp[d[C[i]]]
      dp[i] %= mod
    d[C[i]] = i
  return dp[-1]
print(solve())

Submission status: Accepted

Solution code:
from collections import defaultdict
def main():
    N = int(input())
    C = [int(input()) for _ in range(N)]
    MOD = 10 ** 9 + 7
    color = defaultdict(int)
    dp = [0] * (N+1)
    dp[0] = 1
    color[C[0]] = 0
    for i in range(1,N):
        if color.get(C[i]) == None or C[i] == C[i-1]:
            dp[i] = dp[i-1]
        else:
            dp[i] = dp[i-1] + dp[color[C[i]]]
        color[C[i]] = i
        dp[i] %= MOD
    print(dp[N-1])


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
n=int(input())
c=[int(input()) for _ in range(n)]
mod=10**9+7

dp=[0]*(n+1)

dp[0]=1
last=[-1]*(2*10**5+1)
last[c[0]]=0

for i in range(1,n):
    if c[i]==c[i-1] or last[c[i]]==-1:
        dp[i]=dp[i-1]
    else:
        dp[i]=(dp[i-1]+dp[last[c[i]]])%mod
    last[c[i]]=i

print(dp[n-1])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
cs = [int(input()) for _ in range(n)]

from collections import defaultdict
prev = -1
c_comp = []
# 連続する色はまとめて良い
for c in cs:
    if prev != c:
        c_comp.append(c)
    prev = c

d = defaultdict(list)
for i,c in enumerate(c_comp):
    d[c].append(i)


dp = [0] * 220000
mod = 10**9 + 7

# 何個目まで見たか
inds = defaultdict(int)
ans = 0
dp[0] = 1
for i,c in enumerate(c_comp):
    i_prev = d[c][inds[c]-1]
    if inds[c] >= 1:
        # かぶっていないそれ以前の場合の数を足す
        dp[i+1] += dp[i] + dp[i_prev+1]
    else:
        # 前の色が無い or 異なる場合はなにもしない
        dp[i+1] = dp[i]
    dp[i+1] %= mod
    inds[c] += 1
print(dp[len(c_comp)])

Submission status: Accepted

Solution code:
n = int(input())
c = []
for _ in range(n):
    c.append(int(input()))

mod = 10**9+7
dp = [0] * n
dp[0] = 1

pre = [-1] * n
tmp = [-1] * (2*10**5+10)

for i in range(n):
    pre[i] = tmp[c[i]-1]
    tmp[c[i]-1] = i

for i in range(1,n):
    dp[i] = dp[i-1]
    if pre[i] != -1 and c[i] != c[i-1]:
        dp[i] += dp[pre[i]]
        dp[i] %= mod

print(dp[-1])

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    n = int(input())
    C = list(int(input()) for _ in range(n))
    MAX_C = max(C)

    dp = [0] * (n + 1)
    dp[0] = 1
    dp2 = [-1] * (MAX_C + 1)
    for i in range(n):
        c = C[i]
        if dp2[c] >= 0 and dp2[c] < i - 1:
            dp[i + 1] = dp[i] + dp[dp2[c] + 1]
        else:
            dp[i + 1] = dp[i]
        dp[i + 1] %= mod
        dp2[c] = i

    print(dp[-1] % mod)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
n=int(input())
c=[int(input())for i in range(n)]
l=[-1]*(max(c)+1)
d=[0]*(n+1)
d[0]=1
for i in range(1,n+1):
 d[i]=d[i-1];C=l[c[i-1]]
 if i-1!=C!=-1:d[i]+=d[C]
 l[c[i-1]]=i;d[i]%=(10**9+7)
print(d[n])

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    N = in_n()
    C = list(in_all())

    mod = 10**9 + 7

    d = defaultdict(lambda: -1)
    d[C[0]] = 0
    dp = [0] * N
    dp[0] = 1

    for i in range(1, N):
        j = d[C[i]]
        if j == -1:
            dp[i] = dp[i - 1]
        elif j == i - 1:
            dp[i] = dp[i - 1]
        else:
            dp[i] = dp[i - 1] + dp[j]

        dp[i] %= mod

        d[C[i]] = i

    print(dp[-1])


if __name__ == '__main__':
    main()