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:
#import math
#import numpy as np
#import torch
#import torch.nn as nn
#import matplotlib.pyplot as plt
#from decimal import Decimal
#import itertools


N=int(input())
#N,K = map(int,input().split())
#B,W = map(int,input().split())
#T=int(input())
A = list(map(int,input().split()))
#S=str(input())
#A=[p for p in range(2*10**5)]
Q=int(input())
l=[]
for i in range(Q):
    #print(A)
    B,C = map(int,input().split())
    a=True
    while a==True:
        if B==C:
            a=False
        try:
            ind=A.index(B)
            A[ind]=C
            #print(A)
        except:
            a=False
    #print(A)
    l.append(sum(A))
for i in l:
    print(i)

Submission status: Time Limit Exceeded

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

for i in range(Q):
	for j in range(N):
		if A[j] == P[i][0]:
			A[j] = P[i][1]

	print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
def IL():
    return list(map(int,input().split()))

N=int(input())
A_row=IL()
Q=int(input())
B_C=[IL() for _ in range(Q)]

for i in range(Q):
    for j in range(N):
        if A_row[j]==B_C[i][0]:
            A_row[j]=B_C[i][1]
    print(sum(A_row))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
val2ind = {}
for one in list(map(int, input().split())):
    if one not in val2ind:
        val2ind[one] = 0
    val2ind[one]+=1

Q = int(input())

for _ in range(Q):
    B, C = list(map(int, input().split()))
    if B in val2ind:
        cand = val2ind[B]
        val2ind[B] = 0
        if C not in val2ind:
            val2ind[C] = cand
        else:
            val2ind[C] += cand
    print(sum([key*val2ind[key] for key in val2ind]))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
N = int(input())
raw_number = list(map(int, input().split()))
numbers = defaultdict(int)

for num in raw_number:
    numbers[num] += 1
    
Q = int(input())

for _ in range(Q):
    a, b = list(map(int, input().split()))
    numbers[b] += numbers[a]
    numbers[a] = 0
    print(sum([v*k for (k, v) in numbers.items()]))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# submission # - User: herp_sy
# https://atcoder.jp/contests/
#
# lang: Python3 (3.8.2)

import math
import statistics
import numpy as np
import queue
import itertools
import functools 

n = int(input())
a = list(int(i) for i in input().split())
psum, ncnt = sum(a), {}

for k in range(min(a), max(a) + 1):
	ncnt[k] = a.count(k)

q = int(input())
for _ in range(q):
	b, c = map(int, input().split())
	if b in ncnt:
		psum += ((c - b) * ncnt[b])
		if c in ncnt:
		  ncnt[c] += ncnt[b]
		else:
		  ncnt[c] = ncnt[b]
		ncnt[b] = 0
	print(psum)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=sorted([int(i) for i in input().split()])
m={}
for i in range(n):
    x=m.get(a[i],0)
    m[a[i]]=x+1
q=int(input())
b=[]
c=[]
for i in range(q):
    b,c=[int(i) for i in input().split()]
    x=m.get(b,0)
    y=m.get(c,0)
    m[b]=0
    m[c]=x+y
    print(sum(map(lambda x: x*m[x],m.keys())))

Submission status: Time Limit Exceeded

Solution code:
if __name__=='__main__':
    N = int(input())
    A = input().split(" ")
    #A_i = [int(s) for s in A]
    Q=int(input())
    str_list=[]
    S=[]
    for i in range(Q):
        str_list.append(list(input().split()))
        
    for j in range(Q):
        A=[s.replace(str_list[j][0],str_list[j][1]) for s in A]
        A_i = [int(s) for s in A]
        print(sum(A_i))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = sorted(int(x) for x in input().split())
Q = int(input())
for _ in range(Q):
    BC = input().split()
    B, C = int(BC[0]), int(BC[1])
    A = [C if i == B else i for i in A]
    print(sum(A))

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())
B = [list(map(int,input().split(" "))) for i in range(0,Q)]

for i in range(0,Q):
    A[A == B[i][0]] = B[i][1]
    print(np.sum(A))
#print("\n".join(list(map(str,A.tolist()))))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N = int(input())
A = [int(x) for x in input().split()]
Q = int(input())
for i in range(Q):
    B,C = [int(x) for x in input().split()]
    A = [C if a == B else a for a in A]
    print(np.sum((np.array(A))))

Submission status: Time Limit Exceeded

Solution code:
tmp=input()
list=input().split(" ")
#list = map((lambda e: int(e)), list)
#array=numpy.zeros(len(list),dtype=">i4")
#for i in range(len(list)):
#  array[i]=int(list[i])

a=int(input())

for i in range(a):
  b=input().split(" ")
  list = [s.replace(b[0],b[1]) for s in list]
  print(sum(int(j) for j in list))
  #if int(b[0]) in array:
  #  pos=numpy.where(array==int(b[0]))[0]
  #  for j in pos:
  #    array[j]=int(b[1])
  #  sum=numpy.sum(array)
  #  print(sum)
  #else:
  #  sum=numpy.sum(array)
  #  print(sum)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N=int(input())
A=list(map(int,input().split()))
Adic={}
for i in A:
  if Adic.get(i)==None:
    Adic[i]=1
  else:
    Adic[i]+=1
Q=int(input())
ope=[]

for i in range(Q):
  ope.append(list(map(int,input().split())))

A=np.array(A)

for b,c in ope:
  if Adic.get(b)!=None:
    if Adic.get(c)==None:Adic[c]=0
    Adic[c]+=Adic.pop(b)
  sum=0
  for key,value in Adic.items():
    sum+=key*value
  print(sum)

Submission status: Time Limit Exceeded

Solution code:
a = input()
sequence_integer = [int(idx) for idx in input().split()]
num = int(input())
data = []
for idx in range(num):
  data.append([int(idx) for idx in input().split()])
for idx in data:
  while idx[0] in sequence_integer:
    sequence_integer[sequence_integer.index(idx[0])] = idx[1]
  print(sum([int(idx) for idx in sequence_integer]))

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 i in range(Q)]
# print(N)
# print(A)
# print(Q)
# print(B)

total = sum(A)

for i in range(Q):
    Bi = BC[i][0]
    Ci = BC[i][1]

    diff = 0
    for j in range(len(A)):
        if A[j] == Bi:
            diff += Ci - A[j]
            A[j] = Ci

    total += diff
    print(total)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

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

q = int(input())

for i in range(q):
  b, c = map(int, input().split())
  s = [c if i == b else i for i in a_list]
  a_list = s
  print(sum(s))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
q = int(input())
bc = []
ans = []
for i in range(q):
  bc.append(list(map(int, input().split())))
for i in range(q):
  b = bc[i][0]
  c = bc[i][1]
  for j in range(n):
    if a[j] == b:
      a[j] = c
  ans.append(sum(a))
for i in range(q):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

N = int(input())
A = [int(x) for x in input().split()]
d = Counter(A)
Q = int(input())

def sum_from_counter(d):
  return sum(map(lambda k: k * d[k], d))

for i in range(Q):
  B, C = [int(x) for x in input().split()]
  d[C] = d.get(C, 0) + d[B]
  del d[B]
  print(sum_from_counter(d))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=[int(i) for i in input().split()]
arr={}
for a in A:
	if a in arr:
		arr[a]+=1
	else:
		arr[a]=1
Q=int(input())
for q in range(Q):
	B,C=[int(i) for i in input().split()]
	if B in arr:
		if C in arr:
			arr[C]+=arr[B]
		else:
			arr[C]=arr[B]
		arr[B]=0
	print(sum([i[0]*i[1] for i in arr.items()]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

if __name__ == "__main__":
    N = int(input())
    A = list(map(int, input().split()))
    Q = int(input())
    A = np.array(A)

    SUM = []
    for i in range(Q):
        B, C = list(map(int, input().split()))
        if i == 0:
            A = np.where(A == B, C, A)
            SUM.append(sum(A))
        else:
            SUM.append(SUM[i-1]+(C-B)*np.count_nonzero(A == B))
            A = np.where(A == B, C, A)

    for s in SUM:
        print(s)

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):
    BC = [int(x) for x in input().split()]
    B = BC[0]
    C = BC[1]
    A = [C if k == B else k for k in A]
    print(sum(A))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
N=int(input())
numpy_a = np.array(list(map(int, input().split())))
Q=int(input())
ans=[]
for i in range(Q):
  B,C=map(int, input().split())
  numpy_a=np.where(numpy_a == B, C, numpy_a)
  ans.append(np.sum(numpy_a))
for i in range(len(ans)):
  print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=map(int,input().split())
Q=int(input())
numbers=[]
for _ in range(Q):
    B,C=map(int,input().split())
    numbers.append([B,C])
answers=[0 for _ in range(1000001)]
for a in A:
    answers[a]+=a
for number in numbers:
    suuji=answers[number[0]]/number[0]
    answers[number[0]]=0
    answers[number[1]]+=suuji*number[1]
    print(int(sum(answers)))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

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

Q = int(input())

B = []
C = []

sums = []
for i in range(Q):
    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:
import numpy as np

N = int(input())
A = np.fromstring(input(), sep=" ", dtype=np.int64)
Q = int(input())
B = np.zeros(Q)
C = np.zeros(Q)
D = np.fromstring(" ".join([input() for q in range(Q)]), sep=" ", dtype=np.int64).reshape((Q, 2))
B = D[:, 0]
C = D[:, 1]

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

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = sorted(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() )

listA = []
for q in range(Q):
    listA.append(sum(A))
    index = index_num = [n for n, v in enumerate(A) if v == B[q]]
    for i in index:
        A[i] = C[q]

listA.append(sum(A))
for a in range(1,len(listA)):
    print(listA[a])

Submission status: Time Limit Exceeded

Solution code:
data = {}
N = int(input())
A = [int(a) for a in input().split()]
Q = int(input())

for a in A:
    data[a] = data.get(a, 0) + 1

for _ in range(Q):
    b, c = map(int, input().split())
    if data.get(b):
        data[c] = data.get(c, 0) + data.pop(b)
    print(sum([k * v for k, v in data.items()]))

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())
  sum = 0
  for j in range(n):
    if a[j]==b:
      a[j]=c
      sum=sum+c
    else:
      sum=sum+a[j]
  print(sum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = input().split()
A = [int(s) for s in A]



num = int(input())
for i in range(num):
    B, C = map(int, input().split())
    A.sort()
    for j in range(N):
        if A[j] == B:
            A[j] = C
        elif A[j] > B:
            break
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
import math
# from collections import Counter

# N = int(input()) # 1行, 単数
# arg = list(map(int, input().split())) # 1行, 配列
# D = Counter(arg) # 出現数カウント

# print('Yes')
# print('No')
# print()
import collections
N = int(input()) # 1行, 単数
A = list(map(int, input().split())) # 1行, 配列
Q = int(input()) # 1行, 単数
counter = collections.Counter(A)

while True:
  try:
    ans = 0
    B,C = list(map(int, input().split())) # 1行, 配列
    counter[C] = counter[C] + counter[B]
    del counter[B]
    for i in counter.keys():
      ans = ans + i * counter[i]
  # A = [C if i == B else i for i in A]
    print(ans)
  except:
    break;

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())

for i in range(Q):
    B, C= list(map(int, input().split()))
    A = A[np.where(A != B)]
    A = np.append(A, np.ones(N - A.shape[0])*C)

    print(int(np.sum(A)))

Submission status: Time Limit Exceeded

Solution code:
import collections

N=int(input())
A=list(map(int,input().split()))
Q=int(input())
bcs=[list(map(int,input().split())) for i in range(Q)]
total=sum(A)
c=collections.Counter(A)
ans=[0 for i in range(Q)]




for i in range(Q):
    B=bcs[i][0]
    C=bcs[i][1]
    if c[B]!=0:
        tempcounterpl=collections.Counter([C for j in range(c[B])])
        total=total+c[B]*(C-B)
        ans[i]=total
        c[B]=0
        c=c+tempcounterpl
    else:
        ans[i]=total
for i in range(Q):
    print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
num = int(input())
original = list(map(int, input().split()))
trial_num = int(input())

total = sum(original)
now_list = original

for i in range(trial_num):
    trial = list(map(int, input().split()))
    count = 0
    for i in range(num):
        if now_list[i] == trial[0]:
            now_list[i] = trial[1]
            count += 1
    total += (trial[1] - trial[0]) * count
    print(total)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
p=list(map(int,input().split()))
q=int(input())
     
for i in range(q):
        b,c=map(int,input().split())
        k=p.count(b)
        
        for j in range(0,len(p)):
            if (p[j]==b) and (k>0):
                p[j]=c
                k=k-1
            elif k==0:
              break
            
        print(sum(p))

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

readline = sys.stdin.readline
read = sys.stdin.read

n = int(readline())
a = np.array(readline().split(), dtype=np.int64)
q = int(readline())
bc = np.array(read().split(), dtype=np.int64)
ans = np.sum(a)
for i in range(q):
    x = a==bc[2*i]
    a[x] = bc[2*i+1]
    ans += np.count_nonzero(x) * (bc[2*i+1] - bc[2*i])
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A_list = list(map(int, input().split()))
Q = int(input())
list_list = []
for i in range(Q):
  list_ =  list(map(int, input().split()))
  list_list.append(list_)
  

yobi = [1]
for i in range(Q):
  if(len(list(set(A_list)))==1):
    if(A_list[0]==list_list[i][0]):
      yobi[0] = list_list[i][1]
      A_list = yobi*len(A_list)
      #print(A_list)
  else:
    for j in range(N):
      if(A_list[j] == list_list[i][0]):
        A_list[j] = list_list[i][1]
  print(sum(A_list))
  
  
  
#for i in range(Q):
  #sum_ = sum(A_list)
  #変更の個数
  #cosuu = A_list.count(list_list[i][0])
  #sa = list_list[i][1] - list_list[i][0]
  #henkou = sa*cosuu
  #print(sum_ + henkou)
  #for j in range(cosuu):
    #A_list.remove(list_list[i][0])
    #A_list.append(list_list[i][1])

Submission status: Time Limit Exceeded

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

q = int(input())
an_str = '+'.join(an_list)
for _ in range(q):
    b, c = map(str, input().split())
    an_str = an_str.replace(b, c)
    print(sum([int(x) for x in an_str.split('+')]))

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=[i for i, x in enumerate(A) if x == b]
    for j in a:
        A[j]=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 = list(set(A)) #存在する数字のリスト

#set の i 番目の数字n個数
nums = []
for n in set:
    nums.append(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):
    """
        print("i",i)
        print("set,",set)
        print("nums",nums)
        print("B",B[i],"Bnum",nums[set.index(B[i])])
        print("C",C[i],"Cnum",nums[set.index(C[i])])
        """
    if set.count(B[i]) != 0:
        Bnum = nums[set.index(B[i])]
        S += (C[i]-B[i])*Bnum
    
        if set.count(C[i]) == 0:
            set.append(C[i])
            nums.append(Bnum)
        else:
            nums[set.index(C[i])] += Bnum

        nums[set.index(B[i])] = 0
    print(S)

Submission status: Time Limit Exceeded

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

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())
    for j in range(N):
        if A[j]==B:
            A[j]=C
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
def main():
    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_list = []
    for i in range(Q):
        B[i], C[i]  = map(int, input().split())
        val_list = my_index_multi(A_list, B[i])
        for j in val_list :
            A_list[j] = C[i]
        ans_list.append(sum(A_list))
    for ans in ans_list :
        print(ans)

def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


N=int(input())
A=[str(i) for i in input().split()]
Q=int(input())

BC= [list(map(str, input().split())) for i in range(Q)]
#
# print(BC)
for i in range(Q):
    A = [s.replace(BC[i][0],BC[i][1]) for s in A]

    print(sum(int(j) for j in A))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N=int(input())
A=list(map(int, input().split()))
A=sorted(A)
Q=int(input())
B,C=map(int, input().split())
rep=[i for i, x in enumerate(A) if x == B]
for i in range(len(rep)):
    A[rep[i]]=C
ans=np.cumsum(A)
print(ans[-1])

for _ in range(Q-1):
    B,C=map(int, input().split())
    rep=[i for i, x in enumerate(A) if x == B]
    for i in range(len(rep)):
        A[rep[i]]=C
    ans[-1]+=(C-B)*len(rep)
    print(ans[-1])

Submission status: Time Limit Exceeded

Solution code:
def sums(l):
	s = 0
	for v in l:
		s += v
	return s

n = int(input())
a = list(map(int, input().split()))
ind = [ [] for x in range(10**6)]

for i in range(n):
	ind[a[i]].append(i)

q = int(input())

for _ in range(q):
	b, c = map(int, input().split())
	if len(ind[b]) == 0:
		print(sums(a))
		continue
	for i in ind[b]:
		a[i] = c
		ind[c].append(i)

	print(sums(a))

Submission status: Time Limit Exceeded

Solution code:
def _print_sum(cache):
    sum_value = 0
    for v, indices in cache.items():
        sum_value += v * len(indices)
    print(sum_value)


def _main(N, A_list, Q, BC_list):
    cache = {}
    values = set()
    for i, a in enumerate(A_list):
        cache.setdefault(a, []).append(i)
        values.add(a)

    for b, c in BC_list:
        indices = cache.get(b, [])
        cache[b] = []
        cache.setdefault(c, []).extend(indices)
        _print_sum(cache)


def _entry():
    N = int(input())
    A_list = list(map(int, input().split()))
    Q = int(input())
    BC_list = []
    for i in range(Q):
        B, C = map(int, input().split())
        BC_list.append((B, C))
    _main(N, A_list, Q, BC_list)


if __name__ == "__main__":
    _entry()

Submission status: Time Limit Exceeded

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

num_count = [0]*(10**5+1)
num_count = np.array(num_count)
tmp = np.arange(10**5+1)
for i in A:
    num_count[i] += 1

for q in range(Q):
    B,C = map(int,input().split())
    num_count[C] += num_count[B]
    num_count[B] = 0
    ans = np.dot(tmp,num_count)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = input()
Q = int(input())

for i in range(Q):
  B,C = input().split()
  A = A.replace(B,C)
  l = A.split(" ")
  an = [int(s) for s in l]
  print(sum(an))

Submission status: Time Limit Exceeded

Solution code:
import collections
N = int(input())
a = list(map(int, input().split()))
a_c = collections.Counter(a)
Q = int(input())
BC = [list(map(int, input().split())) for _ in range(Q)]
S = [0]*Q

for i, bc in enumerate(BC):
  b = bc[0]
  c = bc[1]
  s = 0
  if b in a_c:
    a_c[c]+=a_c[b]
    del a_c[b]
  for k, v in a_c.items():
    s += k*v
  S[i] = s

[print(i) for i in S]

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import Counter

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

    ans = [None] * Q
    A_Counter = Counter(A)
    for q in range(Q):
        B, C = map(int, input().split())
        A_Counter[C] += A_Counter[B]
        A_Counter[B] = 0

        ans[q] = sum(A_Counter.elements())

    print('\n'.join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

for i in range(q):
    b,c = map(int,input().split())
    if b in a:
        a = [c if j == b else j for j in a]
    s.append(str(sum(a)))

for k in range(q):
    print(s[k])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = input().split()
Q = int(input())
ans = []
for i in range(Q):
    B, C = map(int, input().split())
    A = [C if int(a2) == B else int(a2) for a2 in A]
    ans.append(sum(A))
[print(a) for a in ans]

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
p = input().split()
p_int = [int(n) for n in p]
Q = int(input())
for i in range(Q):
  B, C = map(int, input().split())
  p_int = [C if i == B else i for i in p_int]
  print(sum(p_int))

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
#数を取得
count = int(input())
seq = list(map(int, input().split()))
repeat = int(input())
#置換する
for i in range(0, repeat):
  replace = list(map(int, input().split()))
  seq = [replace[1] if l == replace[0] else l for l in seq]
  print(sum(seq))

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 i in range(q)]

A=[0]*(10**5+1)
for i in range(10**5+1):
  A[i] = a.count(i)

sum_tmp = sum(a)
for i in range(q):
  b = bc[i][0]
  c = bc[i][1]
  A[c] += A[b]
  sum_tmp += (c-b) * A[b]
  A[b] = 0
  
  print(sum_tmp)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
A=input()
q=int(input())
su=[]
for i in range(q):
    s=0
    l=''
    b,c=map(str,input().split())
    A=A.replace(b,c)
    l=A.split(' ')
    for i in l:
        s+=int(i)
    su.append(s)
for i in su:
    print(i)

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())

for i in range(q):
  b, c = map(int,input().split())
  for j in range(n):
    if alist[j]==b:
      alist[j] = c
  output = sum(alist)
  print(output)

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 = np.array(A)
    ans = sum(A)
    for i in range(q):
        b,c = map(int, input().split())
        count = np.count_nonzero(A[A==b])
        A[A==b] = c
        ans += (c-b)* count
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
a = input()
sequence_integer = [int(idx) for idx in input().split()]
num = int(input())
data = []
for idx in range(num):
  data.append([int(idx) for idx in input().split()])
for idx, jdx in data:
  while idx in sequence_integer:
    sequence_integer[sequence_integer.index(idx)] = jdx
  print(sum([int(idx) for idx in sequence_integer]))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [int(each) for each in input().split()]
q = int(input())
rep = [tuple(int(each) for each in input().split()) for i in range(q)]

s = [str(sum(a))]

for i in range(q):
    a = [rep[i][1] if x==rep[i][0] else x for x in a]
    s.append(str(sum(a)))
print('\n'.join(s[1:]))

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):
	sum=0
	Aaf=[X[i][1] if j==X[i][0] else j for j in A]
	for k in range(N):
		sum+=Aaf[k]
	print(sum)
	A=Aaf

Submission status: Time Limit Exceeded

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

def main():
    b_l = []
    c_l = []
    for i in range(0, q):
        b, c = map(str, input().split())
        b_l.append(b)
        c_l.append(c)

    new_a = []
    for j in range(0, q):
        if j==0:
            a_replace = [s.replace(b_l[j], c_l[j]) for s in a]
            new_a.append(a_replace)
            l_si_i = [int(s) for s in a_replace]
            print(sum(l_si_i))
        else:
            a_replace = [s.replace(b_l[j], c_l[j]) for s in new_a[j-1]]
            new_a.append(a_replace)
            l_si_i = [int(s) for s in a_replace]
            print(sum(l_si_i))
    return
main()

Submission status: Time Limit Exceeded

Solution code:
def sum_dict(d, b, c):
    val = 0
    sum = 0
    if b in d:
        val = d[b]
        del d[b]
        d[c] = d.get(c, 0) + val
    for i in d.items():
        sum += (i[0] * i[1])
    return sum, d
    
n = int(input())
a = [int(x) for x in input().split()]
d = {}
for i in a:
    d[i] = d.get(i, 0) + 1
s = sum(a)
q = int(input())
for i in range(q):
    b, c = map(int, input().split())
    s, d = sum_dict(d, b, c)
    print(s)

Submission status: Time Limit Exceeded

Solution code:
_n = int(input())
_list = list(map(int, input().split(" ")))
_q = int(input())
for _i in range(_q):
  [_before, _after] = list(map(int, input().split(" ")))
  _sum = 0
  for _j in range(_n):
    if _list[_j] == _before:
      _list[_j] = _after
    _sum += _list[_j]
  print(_sum)

Submission status: Time Limit Exceeded

Solution code:
import sys
NList = int(input())
NumList = list(map(int,sys.stdin.readline().rstrip().split()))

AltNum = int(input())
resultList = []
for i in range(AltNum):
    a,b = map(int,sys.stdin.readline().rstrip().split())
    for j in range(len(NumList)):
        if(NumList[j] == a):
            NumList[j] = b
    print(sum(NumList))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
lsn = list(map(int, input().split()))
Q = int(input())
res = 0
for i in range(Q):
    b, c = map(int, input().split())
    if b in lsn:
        for _ in range(lsn.count(b)):
            lsn.append(c)
            lsn.remove(b)
    print(sum(lsn))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

target_list = list(map(int, input().split()))
result = []

for i in range(int(input())):
    B, C = map(int, input().split())
    if B in target_list:
        num = target_list.count(B)
        target_list = [x for x in target_list if x != B]
        target_list.extend([C] * num)
        result.append(sum(target_list))
    else:
        result.append(sum(target_list))

for i in result:
    print(i)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = sorted(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() )
    

listA = []
for q in range(Q):
    A = sorted(A)
    listA.append(sum(A))
    index = index_num = [n for n, v in enumerate(A) if v == B[q]]
    for i in index:
        A[i] = C[q]

listA.append(sum(A))
for a in range(1,len(listA)):
    print(listA[a])

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())
    for i,v in enumerate(A):
        if v == b:
            A[i] = c
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

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

flg = False
for _ in range(Q):
    b,c = map(int,input().split())
    if(len(set(A))==1 and flg==False):
        flg = True
    if flg:
        B = A[0]
        if(B==b):
            # print('{}: {}'.format('A',c*N))
            print(c*N)
            A[0] = c
        else:
            print(B*N)
            # print('{}: {}'.format('B',B*N))
    else:
        A = [c if i == b else i for i in A]
        print(sum(A))
        # print('{}: {}'.format('C',sum(A)))