Problem:


Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

 1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5} 

 B_{i} \neq C_{i} 

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

4
1 2 3 4
3
1 2
3 4
2 4

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

4
1 1 1 1
3
1 2
2 1
3 5

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000



Sample input:
4
1 2 3 4
3
1 2
3 4
2 4


Sample output:
11
12
16

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
BC = [list(map(int, input().split())) for _ in range(Q)] 
ans = [0]*(10**5+1)
for i in range (len(A)):
    ans[A[i]] += 1
maxlen = max(max(A),max(max(BC)))
for i in range(Q):
    ans[BC[i][1]] += ans[BC[i][0]]
    ans[BC[i][0]] = 0 

    S = 0
    for i in range(maxlen+1):
        S += ans [i]*i
    print(S)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A_lst =  list(input().split())
Q = int(input())
BC_lst = []
for i in range(Q):
    BC_lst += [list(input().split())]
    
for i,BC in enumerate(BC_lst):
    A_lst = [A.replace(BC[0],BC[1]) for A in A_lst]
    print(sum(list(map(int,A_lst))))

Submission status: Time Limit Exceeded

Solution code:
N = int(input()) #ここで標準入力
A = list(map(int, input().split()))
Q= int(input()) #ここで標準入力


list = []
for i in range(Q):
    a,b=input().split()
    list.append((int(a), int(b)))

for k in range(Q):
    for j in range(N):
        if list[k][0] == A[j]:
            while list[k][0] in A :
                A.remove(list[k][0])
                A.append(list[k][1])
        
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))

dicts = {}
for tmp in a:
  if tmp in dicts.keys():
    dicts[tmp] += 1
  else:
    dicts[tmp] = 1
    
m = int(input())
result = 0
for key, value in dicts.items():
  result += key*value

for _ in range(m):
  b,c = list(map(int, input().split()))
  if b in dicts.keys():
    tmp = dicts[b]
    del dicts[b]
    if c in dicts.keys():
      dicts[c] += tmp
    else:
      dicts[c] = tmp
    result = 0
    for key, value in dicts.items():
      result += key*value
    print(result)
  else:
    print(result)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int,input().split()))	
Q = int(input())
B = [0]*Q
C = [0]*Q
A = np.array(A)

for i in range(Q):
    B[i], C[i] = map(int,input().split())

for i in range(Q):
    A[A==B[i]]=C[i]
    print(np.sum(A))

Submission status: Time Limit Exceeded

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

n = int(input())
a = list(map(int, input().split()))
q = int(input())
b = [list(map(int,input().split())) for i in range(q)]

l = [0] * 100000
m = list(range(1,100001))

for i in range(n):
  l[a[i]-1] += 1
  
for j in range(q):
  l[b[j][1]-1] += l[b[j][0]-1]
  l[b[j][0]-1] = 0
  print(sum(list(map(lambda x,y: x*y, l, m))))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [int(x) for x in input().split()]
q = int(input())
for i in range(q):
  a.sort()
  su = 0
  b,c = map(int,input().split())
  if( b in a):
    for j in range(n):
      if(a[j] > b ):
        break
      if(a[j] == b):
        a[j] = c
  print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
def change_dict_key(d, old_key, new_key, default_value=None):
    d[new_key] = d.pop(old_key, default_value)

n=int(input())
a=list(map(int,input().split()))
a_cnt = Counter(a)

q=int(input())
for _ in range(q):
    b,c=map(int,input().split())
    if b in a_cnt.keys():
        if c in a_cnt.keys():
            a_cnt[c]+=a_cnt[b]
            a_cnt.pop(b)
        else:
            change_dict_key(a_cnt,b,c)
    ans=0
    for key,value in a_cnt.items():
        ans+=key*value
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n=input()
a=list(map(int, input().split()))
q=int(input())

for i in range(q):
  s=list(map(int, input().split()))
  replace = [s[1] if j==s[0] else j for j in a]
  a=replace
  print(sum(replace))

Submission status: Time Limit Exceeded

Solution code:
n, *bc = map(int, open(0).read().split())
a = [bc.pop(0) for _ in range(n)]
q = bc.pop(0)

d = {}
for x in a:
    if x in d:
        d[x] += 1
    else:
        d[x] = 1
ret = sum(a)
for i in range(0, min(q*2, len(bc)), 2):
    b = bc[i]
    c = bc[i+1]
    if b in d:
        v = d.pop(b)
        if c in d:
            d[c] += v
        else:
            d[c] = v
        ret += c * v - b * v
    #ret = sum([k * v for k, v in d.items()])
    print(ret)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
se=list(map(int,input().split()))
q=input()
s=len


for i in range((int(q))):
  inp=input().split()
  for j in range(s(se)):
    if se[j]==int(inp[0]):
      se[j]=int(inp[1])
  
  print(sum(se))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def sum(n, a):
  ans = 0
  n = int(n)
  for num in range(n):
    ans += int(a[num])
  print(ans)

n = input()
a = [e for e in input().split()]
q = input()
q = int(q)

# b = np.zeros((q, 2), dtype=int)

for num in range(q):
  # b[num][0],b[num][1] = input().split()
  b1,b2 = input().split()
  a = [s.replace(b1,b2) for s in a]
  sum(n,a)


# for num in range(q):
#   a = [s.replace(str(b[num][0]),str(b[num][1])) for s in a]
#   sum(n,a)
#   # print(int(a[0]) + int(a[1]) + int(a[2]) + int(a[3]) )

Submission status: Time Limit Exceeded

Solution code:
input()
a = list(map(int, input().split()))
for i in range(int(input())):
  z, c = list(map(int, input().split()))
  a = [c if d == z else d for d in a]
  print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N=int(input())
A=list(map(int, input().split()))
Q=int(input())
B=[list(map(int, input().split())) for _ in range(Q)]

ans=[]

for i in B:
  b=i[0]
  c=i[1]
  A=np.array(A)
  A=np.where(A!=b,A,c)
  
  ans.append(np.sum(A))
  
for i in ans:
  print(i)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(input().split())
# aa = str("".join(a))
q = int(input())
bc = []
for i in range(q):
    bc.append(list(map(int,input().split())))

for i in range(q):
    mae = str(bc[i][0])
    ato = str(bc[i][1])
    for i,k in enumerate(a):
        if mae == k:    
            a[i] = a[i].replace(mae,ato)
    s = 0
    for j in range(len(a)):
        s += int(a[j])
    print(s)

Submission status: Time Limit Exceeded

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

for _ in range(Q):
    B,C=map(int,input().split())
    A=[C if i==B else i for i in A]
    print((sum(A)))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
q = int(input())
result = []
for i in range(q):
    b = list(map(int, input().split()))
    for m, k in enumerate(a):
        if  k == b[0]:
            a[m] = b[1]
    print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
s = Counter(A)
t=[0]*(10**5+1)
for i in range(10**5+1):
    t[i] = s[i]*i
    
for i in range(Q):
    B, C = map(int, input().split())
    num = t[B]//(B)
    t[B] = 0
    t[C] += num*(C)
    print(sum(t))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from numpy import copy
N=int(input())
numpy_a = np.array(list(map(int, input().split())))
Q=int(input())
newArray = copy(numpy_a)
ans=[]
for i in np.arange(Q):
  B,C=map(int, input().split())
  newArray[newArray==B] = C
  ans.append(np.sum(newArray))
print('\n'.join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
suretu = list(input().split())
Q = int(input())
ans = []
for i in range(Q):
    x, y = input().split()
    l_replace = [s.replace(x, y) for s in suretu]
    suretu = l_replace
    print(sum(map(int, l_replace)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
 
n = int(input())
a = list(map(int, input().strip().split()))
q = int(input())
bc = [map(int, input().split()) for _ in range(q)]
b, c = [list(i) for i in zip(*bc)]
i = 0
 
for _ in b:
    for aa in range(n):
        if(a[aa]==b[i]):
            a[aa]=c[i]
    i += 1
    print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
def main():
    N = int(input())
    A = [int(a) for a in input().split(" ")]
    Q = int(input())

    sum_list = list()
    for i in range(Q):
        B, C = input().split(" ")
        # sum = 0
        for idx, value in enumerate(A):
            if value ==int(B):
                # sum += int(C)
                A[idx] = int(C)
            else: 
                # sum += value
                pass
            if not int(B) in A:
                break

        sum_list.append(sum(A))
    for value in sum_list:
        print(value)
if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
num = input()
q = int(input())
for _ in range(q):
    a, b = input().split()
    num = num.replace(a, b)
    print(sum(list(map(int, num.split()))))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
BC = [map(int, input().split()) for _ in range(Q)]
B, C = [list(i) for i in zip(*BC)]
S = sum(A)
B_count = 0

for Q_count in range(Q):
    B_count = A.count(B[Q_count])
    S = S + (C[Q_count] - B[Q_count]) * B_count
    print(S)

    while 1:
        try:
            A_idx = A.index(B[Q_count])
        except ValueError:
            break

        A[A_idx] = C[Q_count]

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))
Q=int(input())
s=0 
for k in range(len(A)):
  s=s+A[k]
  
for i in range(Q):
  B,C=map(int,input().split())
  m=0
  for j in range(len(A)):
    if A[j]==B:
      A[j]=C
      m+=1
  s=s+m*(C-B)
  print(s)

Submission status: Time Limit Exceeded

Solution code:
import sys

def retList(target, a):
  split = target.split()
  return [s.replace(split[0], split[1]) for s in a]

N = int(input())
a = input().split()
Q =  int(input())

for i in range(Q):
  target = input()
  if i == 0:
    ret = retList(target, a)
  else:
    ret = retList(target, ret)
  print(sum([int(b.strip()) for b in ret]))

Submission status: Time Limit Exceeded

Solution code:
import collections
n = int(input())
li = list(map(int,input().split()))
q = int(input())
num_li=[list(map(int,input().split())) for i in range(q)]


c = collections.Counter(li)

for i,j in num_li:
    s = 0
    if i in c:
        cnt = c.pop(i)
        c[j] += cnt
    for k, v in c.items():
        s += k * v
    print(s)

Submission status: Time Limit Exceeded

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

n = ii()
a = li()
a.sort()

s = sum(a)

q = ii()

from bisect import bisect_left, bisect_right
def bisect_find(a, x):
    i = bisect_left(a, x)
    if i == len(a):
        return -1
    elif a[i] != x:
        return -1
    return i

def bisect_r_find(a, x):
    i = bisect_right(a, x)
    # if i == len(a):
    #     return -1
    return i

for i in range(q):
    b,c = mi()


    # 左を探す
    l = bisect_find(a,b)
    # 右を探す
    if l != -1:
        r = bisect_r_find(a[l:],b) + l
        # 個数をカウント
        count = r-l
        # 前回の合計との差を求める
        s = s + (c-b)*count

        # 配列を上書き
        # a[l:r] = [c]*count

        # print('a_p',a)

        if b > c:
            # j = bisect_left(a[:l],c)
            jr = bisect_right(a[:l],c)  
            jl = bisect_left(a[:jr],c)
            a = a[:jr] + [c]*count + a[jr:l] + a[r:]
        else:
            jl = bisect_left(a[r:],c) + r
            jr = bisect_right(a[jl:],c) + jl 
            # print('j',jl,jr,l,r)
            a = a[:l] + a[r:jl] + [c]*count  + a[jl:]
            # print(a[:l] , a[r:jl] , [c]*count  , a[jl:])

        # print('a',a)

        # a.sort()
    # print('-------------ans----------------',s)
    print(s)

Submission status: Time Limit Exceeded

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

n = int(readline())
a = list(map(int, readline().split()))
q = int(readline())
L = []
for i in range(q):
  L.append(list(map(int, readline().split())))

s = sum(a)
for b, c in L:
  for i, v in enumerate(tuple(a)):
    if v == b:
      s -= (c - a[i])
      a[i] = c
  print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
#数字の個数
N = int(input())

A = list(map(int,input().split()))

#操作の回数
Q = int(input())

B = []
C = []

set = (set(A)) #存在する数字のリスト

#数値nの個数を追加
nums = {}
for n in list(set):
    nums[n] = A.count(n)

S = sum(A)

for _ in range(Q):
    b,c = map(int,input().split())
    B.append(b)
    C.append(c)


for i in range(Q):
    b = B[i]
    c = C[i]

    if b in nums:
        Bnum = nums[b]
        S += (c-b)*Bnum

        if c in nums:
            nums[c] += Bnum

        else:
            nums[c] = Bnum

        del nums[b]
    print(S)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))

q = int(input())
BCs = []
for i in range(0, q):
  b, c = list(map(int, input().split()))
  BCs.append([b, c])

for b, c in BCs:
  for i in range(0, len(a)):
    if a[i] == b:
      a[i] = c
  sum = 0
  for i in range(0, len(a)):
    sum += a[i]
  print(str(sum))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a_list = list(map(int, input().split()))
a_sum = sum(a_list)
q = int(input())

for i in range(q):
  b, c = map(int, input().split())
  if b not in set(a_list):
    print(a_sum)
    continue
  num = 0
  for j in range(len(a_list)):
    if a_list[j] == b:
      num += 1
      a_list[j] = c
  if b <= c:
    a_sum += (c - b) * num
  else:
    a_sum -= (b - c) * num
  print(a_sum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B = [0] * Q
C = [0] * Q

for i in range(Q):
    B[i], C[i] = map(int, input().split())

for j in range(Q):
    for k, _ in enumerate(A):
        if _ == B[j]:
            A[k] = C[j]
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
n, a = int(input()), sorted(list(map(int, input().split())))
for i in range(int(input())):
    b, c = map(int, input().split())
    for j in range(n):
        if a[j] == b:
            a[j] = c
        if a[j] > c:
            break
    print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
if __name__ == "__main__":
    n = int(input().strip())
    a = np.array(input().strip().split()).astype(int)
    q = int(input().strip())
    bc = np.array([input().strip().split() for i in range(q)]).astype(int)

    for i in range(q):
        a[a == bc[i][0]] = bc[i][1]
        print(np.sum(a))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(int(x) for x in input().split())
Q=int(input())
X=[list(map(int,input().split())) for i in range(Q)]

for i in range(Q):
	if X[i][0] not in A:
		print(sum(A))
	else:
		Aaf=[X[i][1] if j==X[i][0] else j for j in A]
		print(sum(Aaf))
		A=Aaf

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N = int(input())
lsn = list(map(int, input().split()))
Q = int(input())
for i in range(Q):
    b, c = map(int, input().split())
    for j in range(len(lsn)):
        if b == lsn[j]:
            lsn[j]=c
    print(sum(np.where(lsn==b,c,lsn)))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B = []
C = []
for i in range(Q):
    b, c = map(int, input().split())
    B.append(b)
    C.append(c)

for n in range(Q):
    A = [C[n] if i == B[n] else i for i in A]
    print(sum(A))

Submission status: Time Limit Exceeded

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

BC = []
i = 0
for i in range(Q):
    BC.append(input().split())

j = 0
k = 0
l = 0
S = 0
for j in range(Q):
    for k in range(N):
        if A[k] == int(BC[j][0]):
            A[k] = int(BC[j][1])
    for l in range(N):
        S = S + A[l]
    print(S)
    S = 0

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
for i in range(Q):
  B,C = map(int, input().split())
  A = [C if j == B else j for j in A]
  S = sum(A)
  print(S)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B = []
C = []
for _ in range(Q):
    b, c = map(int, input().split())
    B.append(b)
    C.append(c)

counter = Counter(A)

for i in range(Q):
    if B[i] in counter:
        counter[C[i]] = counter[C[i]] + counter.pop(B[i])
    ans = 0
    for num, count in counter.items():
        ans += num * count
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math
import sys
import itertools
from math import gcd
from math import sqrt
from sys import stdin
def input() : return stdin.readline().rstrip()
def mips():
    return map(int,input().split())
def ii():
    return int(input())
sys.setrecursionlimit(10**9)

N = ii()
A = [el for el in mips()]
Q = ii()
check = dict()
for i in range(1,max(A)+1):
    check[i] = 0
for el in A:
    check[el] += 1
for i in range(Q):
    ans = 0
    B,C = mips()
    if B in check:
        if C in check:
            check[C] += check[B]
        else:
            check[C] = check[B]
        check[B] = 0
    for key,value in check.items():
        ans += (key * value)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import collections
N = int(input())

Line = [int(s) for s in input().split()]
c = collections.Counter(Line)

# print(c)

Q = int(input())


for _ in range(Q):
    Line = [int(s) for s in input().split()]
    try:
        c[Line[1]] += c[Line[0]]
        c.pop(Line[0])
    except:
        pass
        
        # print('Error')
    # print(c)
    
    s=0
    for i in c:
        # print(i)
        s += i * c[i]
    print(s)

Submission status: Time Limit Exceeded

Solution code:
import collections


N = int(input())
A = list(map(int, input().split()))
Q = int(input())
cnt = collections.Counter(A)

s = -1
for i in range(Q):
    BC = list(map(int, input().split()))

    if BC[0] in cnt:
        if BC[1] in cnt:
            cnt[BC[1]] += cnt[BC[0]]
            del cnt[BC[0]]
        else:
            cnt[BC[1]] = cnt[BC[0]]
            del cnt[BC[0]]
        s = 0
        for k, v in cnt.items():
            s += int(k) * v
    else:
        if s == -1:
            s = 0
            for k, v in cnt.items():
                s += int(k) * v
    print(s)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import collections
    N = int(input())
    A_list = [A for A in input().split()]
    A_list = list(map(int, A_list))
    Q = int(input())
    B = [0] * Q
    C = [0] * Q
    ans = sum(A_list)
    for i in range(Q):
        B[i], C[i]  = map(int, input().split())

        #num = A_list.count(B[i])
        num_dict = collections.Counter(A_list)
        num = num_dict[B[i]]
        #print(num)
        if B[i] > C[i] and B[i] in A_list :
            ans = ans - (B[i] - C[i]) * num
        elif B[i] < C[i] and B[i] in A_list  :
            ans = ans + (C[i] - B[i]) * num
        for j in range(N) :
            if B[i] in A_list :
                rep = A_list.index(B[i])
                A_list[rep] = C[i]
            else :
                #print("in")
                break
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
q = int(input())
bc = [list(map(int,input().split())) for _ in range(q)]

# sum_first  = sum(a)

for i in bc:
    a = [i[1] if j==i[0] else j for j in a]
    # print(a)
    print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
import bisect,collections,copy,heapq,itertools,math,string
import sys
def S(): return sys.stdin.readline().rstrip()
def M(): return map(str,sys.stdin.readline().rstrip().split())
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LS(): return list(sys.stdin.readline().rstrip().split())
N = I()
A = LS()
Q = I()
for _ in range(Q):
  B, C = M()
  A = [s.replace(B, C) for s in A]
  temp = [int(s) for s in A]
  print(sum(temp))

Submission status: Time Limit Exceeded

Solution code:
def main():
    N = int(input())
    A = list(map(int, input().split()))
    Q = int(input())
    B, C = [0]*Q, [0]*Q
    for i in range(Q):
        B[i], C[i] = map(int, input().split())

    ans = sum(A)
    d = dict()
    for i, a in enumerate(A):
        if a not in d:
            d[a] = ()
        d[a] += (i,)

    for b, c in zip(B, C):
        if b not in d:
            print(ans)
            continue
        elif len(d[b]) == 0:
            print(ans)
            continue
        ans += len(d[b]) * (c-b)
        if c not in d:
            d[c] = ()
        d[c] = d[c] + d[b]
        d[b] = ()
        print(ans)

main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

a_list = [int(i) for i in input().split()]
q = int(input())

BC_list = []

for _ in range(q):
    tmp = [int(i) for i in input().split()]
    BC_list.append(tmp)

# print(BC_list)

ary = [0 for _ in range((10 ** 5)+1)]

for i in a_list:
    ary[i] += i


for i in BC_list:
    b = i[0]
    c = i[1]
    ary[c] += (ary[b]/b)*c
    ary[b] = 0
    ans = int(sum(ary))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
As = list(map(int, input().split()))
q = int(input())
Ds = [0] * (10 ** 5 + 1)
for a in As:
  Ds[a] += 1
for i in range(q):
  b, c = map(int, input().split())
  Ds[c] += Ds[b]
  Ds[b] = 0
  ans = 0
  for x, i in enumerate(Ds):
    ans += x * i
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

nums = list(map(int, input().split()))
q = int(input())

ans = []

for _ in range(q):
    b, c = map(int, input().split())
    
    nums = sorted(nums)

    if b in nums:
        nums = [(c if num == b else num) for num in nums]
    
    ans.append(sum(nums))

for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))
Q=int(input())
B=[]
C=[]
for i in range(Q):
  b,c=map(int,input().split())
  B.append(b)
  C.append(c)

for i in range(Q):
  ans = 0
  for j in range(len(A)):
    if A[j] == B[i]:
      A[j]=C[i]
      ans += A[j]
    else:
      ans += A[j] 
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int,input().split()))
q = int(input())
b = [list(map(int,input().split()))]
for i in range(q - 1):
    b.append(list(map(int,input().split())))

for i in range(q):
    a.sort()
    j = b[i][0]
    k = b[i][1]
    if j in a:
        for i in range(n):
            if a[i] <= j:
                if a[i] == j:
                    a[i] = k
            else:
                break
        print(sum(a))
    else:
        print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
import collections

num_of_numbers = int(input())
numbers = list(map(int, input().split()))
num_of_operation = int(input())

# intで初期化するため0が返る
cnt = collections.defaultdict(int)
# numbersに含まれる各数字の出現回数を保持
for i in set(numbers):
    cnt[i] = numbers.count(i)
# 初期状態の和を算出
ans = sum(numbers)

for i in range(num_of_operation):
    B, C = map(int, input().split())

    # 置換対象の数字が存在する場合
    if B in cnt:
        tmpB = cnt[B]
        tmpC = cnt[C]
        ans = ans - (B * tmpB) + (C * tmpB)

        cnt[C] = tmpC + tmpB
        cnt.pop(B)

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n= int(input())
alist = list(map(int,input().split()))
q =int(input())

def repr(x,b,c):
  if x==b:
    return c
  else:
    return x
  
for i in range(q):
  b, c = map(int,input().split())
  alist = list(map(lambda x: repr(x,b,c), alist))
  output = sum(alist)
  print(output)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B = []
C = []
for i in range(Q):
    input_q = list(map(int, input().split()))
    B.append(input_q[0])
    C.append(input_q[1])

for i in range(Q):
    A = [C[i] if j == B[i] else j for j in A]
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
import numpy as np

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
s = Counter(A)
t=[0]*(10**5+1)
for i in range(10**5+1):
    t[i] = s[i]*i
    
for i in range(Q):
    B, C = map(int, input().split())
    num = t[B]//(B)
    t[B] = 0
    t[C] += num*(C)
    print(sum(t))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=list(map(int,input().split()))

adic=dict()

for ai in a:
    if ai in adic:
        adic[ai]+=1
    else:
        adic[ai]=1
        
#for i in range(1,max(a)+1):
for i in range(1,10**5+1):
    if not i in adic:
        adic[i]=0
        
        
q=int(input())
b=[0]*(q+1)
c=[0]*(q+1)
for i in range(q):
    bi,ci=map(int,input().split())
    b[i]=bi
    c[i]=ci
    
#print(adic)    
for i in range(q):
    adic[c[i]]=adic[c[i]]+adic[b[i]]
    adic[b[i]]=0
#    print(i,adic)
    asum=0
    for i,ad in adic.items():
#    for i in range(1,10**5+1):
#        asum+=a[i]*adic[a[i]]
#        asum+=i*adic[i]
        asum+=i*ad
    print(asum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A_lst =  list(map(int,input().split()))
Q = int(input())
BC_lst = []
for i in range(Q):
    BC_lst += [list(map(int,input().split()))]
    
for i,BC in enumerate(BC_lst):
    A_lst = [str(A).replace(str(BC[0]),str(BC[1])) for A in A_lst]
    print(sum(list(map(int,A_lst))))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n=int(input())
a=np.array(list(map(int, input().split())))
q=int(input())

def func(a):
  for i in range(q):
    b,c=map(int, input().split())
    a[a==b]=c
    print(np.sum(a))

func(a)

Submission status: Time Limit Exceeded

Solution code:
def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    n = int(input())
    A = list(map(int, input().split()))
    q = int(input())
    import numpy as np
    A.sort()
    ans = sum(A)
    from bisect import bisect_left,bisect_right

    for i in range(q):
        b,c = map(int, input().split())
        insert = bisect_left(A,c)
        start = bisect_left(A,b)
        end = bisect_right(A,b)
        A = A[:insert] + [c]*(end-start) + A[insert:]
        if b > c:
            A = A[:end] + A[2*end-start:]
        else:
            A = A[:start] + A[end:]
        ans += (c-b)* (end-start)
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

N = int(input())

AAA = list(map(int, input().split()))

Q = int(input())

goukei_AAA = sum(AAA)

for i in range(0, Q):
    BC = list(map(int, input().split()))
    if not BC[0] in AAA:
        print(goukei_AAA)
        pass
    else:
        how_many_changes = AAA.count(BC[0])
        AAA = [BC[1] if m == BC[0] else m for m in AAA]
        goukei_AAA = goukei_AAA + (how_many_changes * (BC[1] - BC[0]))
        print(goukei_AAA)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(str, input().split()))
a = '+'.join(A)

Q = int(input())
for i in range(Q):
    B, C= map(str, input().split())
    a = a.replace(B, C)
    print(eval(a))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

N = int(input())
A = list(map(int, input().split()))

Q = int(input())

B = []
C = []

sums = []
for i in range(Q):
    A = sorted(A)
    b, c = list(map(int, input().split()))
    A = [c if a == b else a for a in A] 
    sums.append(sum(A))
    
for s in sums:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
 
 
for i in range(Q):
    B, C = map(int, input().split())
 
    while(1):
        try:
            A[A.index(B)] = C
        except ValueError:
            break
 
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
#d
n = int(input())
a = list(map(int, input().split()))
q = int(input())
bc = [list(map(int, input().split())) for _ in range(q)]
b, c = [list(i) for i in zip(*bc)]
old_sum = sum(a)
change = []
for i in range(q):
    print(old_sum + a.count(b[i])*(c[i]-b[i]) + change.count(b[i])*(c[i]-b[i]))
    old_sum = old_sum + a.count(b[i])*(c[i]-b[i]) + change.count(b[i])*(c[i]-b[i]) 
    change += [c[i]]*(a.count(b[i])+change.count(b[i]))

Submission status: Time Limit Exceeded

Solution code:
import bisect
N = int(input())
a = list(map(int,input().split()))
q = int(input())
sum_a = 0
output = 0
cnt = 0
a.sort()

for i in range(q):
  bc = list(map(int,input().split()))
  flag = False
  try:
    nn = a.index(bc[0])
    for j in range(nn-1, len(a)):
      if a[j] == bc[0]:
        a[j] = bc[1]
        flag = True
      else:
        if flag == True:
          break
  except ValueError:
    pass
  print(sum(a))
  a.sort()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
la=list(map(int,input().split()))
q=int(input())
lb=[0]*q
lc=[0]*q
ld=[0]*q
for i in range(q):
  lb[i],lc[i]=map(int,input().split())
  ld[i]=lc[i]-lb[i]
s = sum(la)
for i in range(q):
  m=la.count(lb[i])
  s=s+ld[i]*m
  print(s)
  if m!=0:
    la.remove(lb[i])
    for j in range(m):
      la.append(lc[i])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N = int(input())
A = list(map(int,input().split()))	
Q = int(input())
B = [0]*Q
C = [0]*Q
A = np.array(A)

for i in range(Q):
    B[i], C[i] = map(int,input().split())

for i in range(Q):
    A[A==B[i]]=C[i]
    print(np.sum(A))

Submission status: Time Limit Exceeded

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

import numpy as np

n = int(input())
a = list(map(int, input().split()))
q = int(input())
b = [list(map(int,input().split())) for i in range(q)]

l = np.array([0] * 100000)
m = np.array(list(range(1,100001)))

for i in range(n):
  l[a[i]-1] += 1
  
for j in range(q):
  l[b[j][1]-1] += l[b[j][0]-1]
  l[b[j][0]-1] = 0
  print(sum(l*m))