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())
ais = list(map(str, input().split()))
q = int(input())
bcs = [list(map(int, input().split())) for i in range(q)]
for b, c in bcs:
#  new = "-".join(ais)
#  change = new.replace(str(b),str(c))
#  ais = change.split('-')
  sum = 0
  l_new = []
  for i in ais:
    if int(i)==int(b):
      sum+=int(c)
      l_new.append(int(c))
    else:
      sum+=int(i)
      l_new.append(int(i))

  ais = l_new[:]
  print(sum)

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

num = []

res = 0

for i in range(Q):
    for n in range(N):
        if A[n] == B[i][0]:
            num.append(B[i][1])
        else:
            num.append(A[n])
    A.clear()
    for l in num:
        A.append(l)
    num.clear()
    for m in range(N):
        res += A[m] 
    print(res)
    res = 0

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import copy

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

B = []
C = []
for _ in range(Q):
    B_i, C_i = map(int, input().split())
    
    B.append(B_i)
    C.append(C_i)

for i in range(Q):
    A_ = []
    for j in range(N):
        A_.append(A[j] if A[j] != B[i] else C[i])
    print(sum(A_), flush=True)
    
    A = copy.deepcopy(A_)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
lsn = list(map(int,input().split()))
Q = int(input())
ls2 = []
for i in range(Q):
    Bi,Ci = map(int,input().split())
    ls2.append([Bi,Ci])
index = [0]*(10**5+1)
for i in range(10**5+1):
    index[i] = lsn.count(i)
sum1 = sum(lsn)
for l in ls2:
    index[l[1]] += index[l[0]]
    sum1 = sum1 - l[0]*index[l[0]] + l[1]*index[l[0]]  
    index[l[0]] = 0
    print(sum1)

Submission status: Time Limit Exceeded

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

dic = {}
for num in A:
    if num in dic:
        dic[num] += 1
    else:
        dic[num] = 1

for _ in range(Q):
    total = 0
    B, C = map(int, input().split())
    if B in dic and C in dic:
        dic[C] += dic[B]
        del dic[B]
    elif B in dic and C not in dic:
        dic[C] = dic[B]
        del dic[B]
    for mykey, myvalue in dic.items():
        total += mykey * myvalue
    print(total)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

hyou = [0]*100001
keisuu = np.array(list(range(0,100001)))

N =  int(input())
a_data = [int(x) for x in input().split()]
Q = int(input())
b_data = [[int(x) for x in input().split()] for _ in range(Q)]

# 数列を分類
for x in a_data:
    hyou[x] += 1
# 操作と合計
for before_value,after_value in b_data:
    # 数値の入れ替え
    hyou[after_value] = hyou[before_value] + hyou[after_value] 
    hyou[before_value] = 0

    # 合計を求めて出力
    hyou_array = np.array(hyou)
    total = np.dot(hyou_array,keisuu)
    print(total)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
ls = list(map(int,input().split()))
q = int(input())
freqlist = dict()
for i in range(n):
	if ls[i] not in freqlist:
		freqlist[ls[i]] = 1
	else:
		freqlist[ls[i]] += 1


total = sum(ls)
setls = list(set(ls))

for i in setls:
	freqlist[i] = ls.count(i)

for i in range(q):
	a,b = input().split()
	a,b = int(a), int(b)
	if a in freqlist:
		temp = total - freqlist[a]*a
		temp += b * freqlist[a]
		print(temp)
		total = temp
		if b in freqlist:
			freqlist[b] += freqlist[a]
			freqlist.pop(a)
		else:
			k = freqlist.pop(a)
			freqlist[b] = k
	else:
		print(total)

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)

A_new = {}
for a in A:
    if not a in A_new:
        A_new[a] = 1
    else:
        A_new[a] += 1

for i in range(Q):
    b = B[i]
    c = C[i]
    if b in A_new:
        n = A_new[b]
        A_new[b] = 0
        if c in A_new:
            A_new[c] += n
        else:
            A_new[c] = n
    key_list = A_new.keys()
    res = 0
    for k in key_list:
        res += A_new[k] * k
    print(res)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
q = int(input())
xy = [map(int, input().split()) for _ in range(q)]
b, c = [list(i) for i in zip(*xy)]

stuck_b = []
stuck_c = []
stuck_sum = []

sum = 0

for cnt_q in range(q):
    sum = 0
    if len(stuck_b) > 0:
        if stuck_b[cnt_q] == b[cnt_q] and stuck_c[cnt_q] == c[cnt_q]:
            print(stuck_sum[cnt_q])
        else:
            for cnt_n in range(n):
                if a[cnt_n] == b[cnt_q]:
                    a[cnt_n] = c[cnt_q]
            for num in range(n):
                sum += a[num]
            print(sum)
    else:
        for cnt_n in range(n):
            if a[cnt_n] == b[cnt_q]:
                a[cnt_n] = c[cnt_q]
        for num in range(n):
            sum += a[num]
        print(sum)

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
        
q=int(input())
b=[0]*(q+1)
c=[0]*(q+1)
for i in range(q):
    b[i],c[i]=map(int,input().split())
    
#print(adic)    
for i in range(q):
    if b[i] in adic and c[i] in adic:
        adic[c[i]]=adic[c[i]]+adic[b[i]]
        del adic[b[i]]
    elif b[i] in adic and (not c[i] in adic):
        adic[c[i]]=adic[b[i]]
        del adic[b[i]]
#        adic[b[i]]=0
#    print(i,adic)
    asum=0
    for i,ad in adic.items():
        asum+=i*ad
    print(asum)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int, input().split()))
q = int(input())
b = []
c = []
ans = sum(a)
for i in range(q):
    bi,ci = map(int, input().split())
    b.append(bi)
    c.append(ci)
for i in range(q):
    ans += a.count(b[i]) * (c[i]-b[i])
    for j in range(a.count(b[i])):
        a.append(c[i])
    a = [j for j in a if j != b[i]]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = input()
A = input()
Q = int(input())
BC = [input().split() for _ in range(Q)]

for i in range(Q):
    A = A.replace(BC[i][0], BC[i][1])
    num_list = list(map(int, A.split()))
    print(sum(num_list))

Submission status: Time Limit Exceeded

Solution code:
def run(n, seq, num, trials):
    '''
    '''
    _sum = sum(seq)
    for i in range(num):
        b, c = trials[i]
        if seq.count(b) == 0:
            print(_sum)
            continue

        _sum += (c-b)*seq.count(b)
        print(_sum)
        for i in range(seq.count(b)):
            seq.remove(b)
            seq.append(c)


if __name__ == '__main__':
    n = int(input())
    seq = list(map(int, input().split()))
    num = int(input())
    trials = [map(int, input().split()) for _ in range(num)]
    run(n, seq, num, trials)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
target = list(map(int, input().split()))
lst = [list(map(int, input().split())) for i in range(int(input()))]
a = []
for l in lst:
    target = [l[1] if t == l[0] else t for t in target]
    print(sum(target))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def resolve():
    n = int(input())
    A = np.array(list(map(int, input().split())))
    q = int(input())
    bc = []
    for _ in range(q):
        bc.append(list(map(int, input().split())))
    bc = np.array(bc)
    
    for i in range(q):
        A = np.where(A == bc[i][0], bc[i][1], A)
        print(np.sum(A))
        
resolve()

Submission status: Time Limit Exceeded

Solution code:
import collections
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())
    
A_dict=collections.Counter(A)
for i in range(Q):
    ANS=0
    if B[i] in A_dict.keys():
        if C[i] in A_dict.keys():
            A_dict[C[i]]+=A_dict[B[i]]
            del A_dict[B[i]]
        else:
            A_dict[C[i]] = A_dict[B[i]]
            del A_dict[B[i]]
    for j in A_dict.keys():
        ANS=ANS+j*A_dict[j]
    print(ANS)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

N = int(input())
data = list(map(int,input().split()))
Q = int(input())
pala = list()
for i in range(Q):
    b = list(map(int,input().split()))
    pala.append(b)

count = Counter(data)
flag = 0

for B,C in pala:
    res = 0
    for k , v in count.items():
        if k == B:
            k = C
            flag = 1
        res += (k * v)
    if flag == 1:
  #    print(count)
      count[C] += count.pop(B)
 #     print(count)
      flag = 0
    
    print(res)

Submission status: Time Limit Exceeded

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

dp=[0 for n in range(100000)]
for n in range(len(A)):
    dp[A[n]-1]+=1

for n in range(Q):
    B,C=map(int,input().strip().split())
    dp[C-1]+=dp[B-1]
    dp[B-1]=0

    ans=0
    for n in range(1,len(dp)):
        ans+=n*dp[n-1]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import copy

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

B = []
C = []
for _ in range(Q):
    B_i, C_i = map(int, input().split())
    
    B.append(B_i)
    C.append(C_i)

for i in range(Q):
    A_ = []
    for j in range(N):
        A_.append((A[j] if A[j] != B[i] else C[i]))
    print(sum(A_))
    
    A = copy.deepcopy(A_)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n=int(input())
a=list(map(int,input().split()))
q=int(input())
table = [[int(i) for i in input().split()] for q in range(q)]

b=np.array(table)

for i in range(q):
 a = [b[i,1] if k == b[i,0] else k for k in a]
 print(sum(a))

Submission status: Time Limit Exceeded

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

for i in range(q):
    b,c = list(map(int,input().split()))
    co = a.count(b)
    for j in range(co):
        a[a.index(b)] = c
        a_sum += (c - b)
    
    res.append(a_sum)
        
for i in res:
    
    print(i)

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
s=[0]*(q+1)
for i in range(q):
	b[i],c[i]=map(int,input().split())
f={}
for i in range(n):
	f.setdefault(a[i],[])
for i in range(n):
	f[a[i]].append(i)
for g,h in f.items():
	#print(len(h)*g)
	s[0]=s[0]+len(h)*g
#print(f)
for i in range(1,q+1):
	if b[i-1] in f:
		if c[i-1] in f:
			f[c[i-1]]=f[c[i-1]]+f[b[i-1]]
			s[i]=s[i-1]-len(f[b[i-1]])*b[i-1]
			#print(s[i])
			
			s[i]=s[i]+len(f[b[i-1]])*c[i-1]
			f.pop(b[i-1])
		else:
			f.setdefault(c[i-1],[])
			f[c[i-1]]=f[c[i-1]]+f[b[i-1]]
			s[i]=s[i-1]-len(f[b[i-1]])*b[i-1]
			#print(s[i])
			
			s[i]+=len(f[b[i-1]])*c[i-1]
			f.pop(b[i-1])
	#print(f)
	#for g,h in f.items():
		#print(len(h)*g)
		#s[i]=s[i]+len(h)*g
	else:
		s[i]=s[i-1]
	print(s[i])

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=[int(_) for _ in 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 D():
    import numpy as np
    n= int(input())
    Alist = list(map(int,input().split()))
    Anp = np.array(Alist)
    q = int(input())
    l = []
    for i in range(q):
        b,c= map(int,input().split())
        Anp = np.where(Anp==b,c,Anp)
        print(np.sum(Anp))




D()

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()
ans = ''
def keta(N):
    for i in range(1,15):
        if 26**i 
K = keta(N)
alpha = 0
for i in range(26):
    if 26**(K-1) + (26*i) + 1 <= N and N <= (26**(K-1)) + (26*(i+1)):
        alpha = i
        break
table = [chr(i) for i in range(97,123)]
alpha = table[i]
ans += (K-1) * alpha
last = (N-26**(K-1) - (26*memo) - 1)%26
last = table[last]
ans += last
print(ans)
'''

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):
    B,C = mips()
    if B in check:
        #ans -= check[B] * B
        if C in check:
            check[C] += check[B]
        else:
            check[C] = check[B]
        #ans += check[C] * C
        A.append(-(B*check[B]))
        A.append(C*check[B])
        check[B] = 0
    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())

num_A = [A.count(i) for i in range(10**5+1)]
first = sum(np.array(num_A)*np.array([j for j in range(10**5+1)]))

for i in range(Q):
    b, c = map(int, input().split())
    first += c*num_A[b]
    first -= b*num_A[b]
    num_A[c] += num_A[b]
    num_A[b] = 0
    print(first)

Submission status: Time Limit Exceeded

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

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

Q = int(input())

li = [list(map(int,input().split())) for i in range(Q)]


memo2=0

S = sum(A)
cou = Counter(A)

for i in range(Q):
    global ohno
    S+=cou[li[i][0]]*(li[i][1]-li[i][0])
    print(S)
    a = cou[li[i][0]]
    cou[li[i][1]]+=a
    cou[li[i][0]]=0
    
    if set(cou.values())==1:
        global ohno
        memo1=i
        memo2=cou[max(cou.values())]
        for i in range(memo1+1,Q):
            if li[i][0]==memo2:
                print(N*li[i][1])
                memo2=li[i][1]
            else:
                print(memo2*N)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=list(map(int,input().split()))
sa=set(a)
a2=[]
for ii in sa:
  ca=a.count(ii)
  a2.append([ii,ca])
  for jj in range(ca):
    a.remove(ii)
#import numpy as np
#a2=np.array(a2)
#print(a2)
q=int(input())
for ii in range(q):
  b,c=map(int,input().split())
  s=0
  idx=[]
  for jj in range(len(a2)):
    if a2[jj][0]==b or a2[jj][0]==c:
      idx.append(jj)
      s+=a2[jj][1]
      a2[jj][0]=0
      a2[jj][1]=0
  a2.append([c,s])
  #print(a2)
  r=0
  for jj in range(len(a2)):
     r+= a2[jj][0]*a2[jj][1]
  print(r)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
lsn = list(map(int,input().split()))
Q = int(input())
ls2 = []
for i in range(Q):
    Bi,Ci = map(int,input().split())
    ls2.append([Bi,Ci])
index = [0]*(10**5+1)
for i in range(10**5+1):
    index[i] = lsn.count(i)
sum1 = sum(lsn)
for l in ls2:
    index[l[1]] += index[l[0]]
    sum1 = sum1 - l[0]*index[l[0]] + l[1]*index[l[0]]  
    index[l[0]] = 0
    
    print(sum1)

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 idx, item in enumerate(a):
    if item == b:
        a[idx] = c
  print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import collections
import copy
import heapq
import itertools
import math
import numpy
import string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())


N = I()
A = LS()
Q = I()
BC_ARR = [LS() for _ in range(Q)]

for s in range(Q):
    str1 = ",".join(A)
    A = str1.replace(BC_ARR[s][0], BC_ARR[s][1]).split(",")
    print(
        numpy.sum(list(map(int, A))))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = input().split()
a = [int(x) for x in a]
q = int(input())
for i in range(q):
    bc = input().split()
    bc = [int(x) for x in bc]
    for l in range(len(a)):
        if a[l] == bc[0]:
            a[l] = bc[1]
    print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

N =int(input())
A_n =list(map(int,input().split()))
Q =int(input())
B_n ,C_n=[],[]
for i in range(Q):
    B,C =map(int,input().split())
    B_n.append(B)
    C_n.append(C)

sum0 =sum(A_n)
for i in range(Q):
    count =Counter(A_n)[B_n[i]]
    sum0 += (C_n[i]-B_n[i])*count
    A_n  =list(filter(lambda x: x != B_n[i] ,A_n))
    A_n.extend([C_n[i] for j in range(count)])
    print(sum0)

Submission status: Time Limit Exceeded

Solution code:
import bisect
n = int(input())
a = list(map(int,input().split()))
q = int(input())
b=[]
c=[]
aa=[]
sum=0
for i in range(n):
    sum+= a[i]
for i in range(q):
    bb,cc = map(int,input().split())
    b.append(bb)
    c.append(cc)
a.sort()

for i in range(q):
    bb,cc=b[i],c[i]
    l= bisect.bisect_left(a,bb)
    h= bisect.bisect_right(a,bb)
    ll=bisect.bisect_left(a,cc)
    hh= bisect.bisect_right(a,cc)
    if bb>cc:
        a[ll+h-l:h],a[ll:ll+h-l] = a[ll:l],[cc]*(h-l)
    else:
        a[l+hh-h:hh],a[l:l+hh-h] = [cc]*(h-l),a[h:hh]
    sum=sum + (cc-bb)*(h-l)
    print(sum)

Submission status: Time Limit Exceeded

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

ans = sum(A)
for i in range(q):
    b, c = map(int, input().split())
    if b in A:
        pos = A.index(b)
        count = A.count(b)
        ans += ((c - b) * count)
        A = A[:pos] + [c] * count + A[pos + count:]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
asses_list = list(map(str, input().split()))
Q = int(input())
for i in range(Q):
    B, C = input().split()

    for k in range(N):
        if asses_list[k] == B:
            asses_list[k] = C
    total = 0
    for s in asses_list:
        s_int = int(s)
        total += s_int
        
    print(total)

Submission status: Time Limit Exceeded

Solution code:
def ans():
    N=int(input())
    A=str(input())
    Q=int(input())
    BC=[list(input().split()) for _ in range(Q)]
    B_i=[0]*N
    for i in range(Q):
        if BC[i][0] in A:
            A=A.replace(BC[i][0],BC[i][1])
            B_i = [int(s) for s in A.split(' ')]
        print(sum(B_i))

ans()

Submission status: Time Limit Exceeded

Solution code:
N = input()
A = input()
Q = int(input())
BC = [input().split() for _ in range(Q)]

for i in range(Q):
    A = A.replace(BC[i][0], BC[i][1])

    num_list = list(map(int, A.split()))
    print(sum(num_list))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

n = int(input())
A = list(map(int, input().split()))
q = int(input())
BC = [ list(map(int, input().split())) for _ in range(q)]

d = defaultdict(int)
for a in A:
    d[a] += 1

for (b,c) in BC:
    d[c] += d[b]
    d[b] = 0
    print(sum([d[k]*k for k in d]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

ans = []
b= []
for c1 in range (q):
    b.append( list(map(int, input().split())) )
    c2=a.count(b[c1][0])

    if (c2!=0):
        for c3 in range(c2):
            a.remove(b[c1][0])
            a.append(b[c1][1])
        
    ans.append(np.sum(a) )
    print(ans[c1])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = sorted(list(map(int, input().split())))
q = int(input())
bc = [list(map(int, input().split())) for i in range(q)]
j = 0
for i in range(q):
    if n > j:
        while bc[i][0] >= a[j]:
            if a[j] == bc[i][0]:
                a[j] = bc[i][1]
            j += 1
            if n == j:
                break
    while True:
        if bc[i][0] in a:
            a[a.index(bc[i][0])] = bc[i][1]
        else:
            break
    print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
#D
def sumdic(dic):
    tmp = 0
    for i in dic:
        tmp += int(i)*dic[i]
    print(tmp)
N = int(input())
A = list(map(int, input().split()))
num = {}
for i in A:
    if i in num:
        num[i] += 1
    else:
        num[i] = 1
#print(num)

Q = int(input())
for j in range(Q):
    B, C = map(int, input().split())
    if B in num and C not in num:
        num[C] = num[B]
        del num[B]
    if B in num and C in num:
        num[C] += num[B]
        del num[B]
    #print(num)
    sumdic(num)
#print(num)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
from sys import stdin
from operator import itemgetter
from collections import deque, Counter
import math
import pprint
from functools import reduce
# stdin = open("sample.txt")

MOD = 1000000007
INF = float('inf')
alpha = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
def keta(kazu): # 入力されたintを桁ごとに分解，リストで出力
    kazu_str = str(kazu)
    kazu_list = [int(kazu_str[i]) for i in range(0, len(kazu_str))]
    return kazu_list

def gcd(*numbers): # 最小公倍数
    return reduce(math.gcd, numbers)

def combination(m,n): # mCn
    
    if n > m:
        return 'すまん'
    return math.factorial(m) // (math.factorial(m-n) * math.factorial(n))

def pow_k(x,n):  # (x**n)の計算の高速化
    if n == 0:
        return 1
    K = 1
    while n > 1:
        if n % 2 != 0:
            K *= x
        x *= x
        n //= 2
    return K * x

def main():
    n = int(stdin.readline().rstrip())
    a = list(map(int,[int(x) for x in stdin.readline().rstrip().split()]))
    dic = {}
    ans = 0
    for i in range(len(a)):
        if a[i] in dic:
            dic[a[i]] += 1
        else:
            dic[a[i]] = 1
    q = int(stdin.readline().rstrip())
    for i in range(q):
        b, c = [int(x) for x in stdin.readline().rstrip().split()]
        if b in dic:
            if c in dic:
                dic[c] += dic[b]
                dic[b] = 0
            else:
                dic[c] = dic[b]
                dic[b] = 0
        ans = 0
        for k, v in dic.items():
            if v != 0:
                ans += k*v
        print(ans)
main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

a = input()
#print(a)
q = int(input())

b = []
for _ in range(q):
    b.append(list(input().split(" ")))
#print(b)

d = a.split(' ')
l = len(d)
for i in range(q):
    c = a.replace(b[i][0],b[i][1],100000)
    a = c
    d = a.split(' ')
    s = 0
    for j in range(l):
        s += int(d[j]) 
    print(s)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a_lst = list(map(int, input().split()))
q = int(input())
# b_lst = []
# c_lst = []
cnt = []
ans = []
# ans = a_lst.copy()
for i in range(q):
    x, y = map(int, input().split())

    # b_lst.append(x)
    # c_lst.append(y)
    a_lst = [y if j == x else j for j in a_lst]
    ans.append(a_lst)
    
len_ans = len(ans)
for i in range(len_ans):
    print(sum(ans[i]))
# for i in range(q):

#     for j in range(len(a_lst)):
#         if a_lst[j] == b_lst[i]:
#             a_lst[j] = c_lst[i]
#     cnt.append(sum(a_lst))
#     print(cnt[i])

# print(cnt)
# for i in range()
# print(b_lst)

Submission status: Time Limit Exceeded

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



def replace_seq(key):
  if key not in query_dict:
    return key
  else:
    return query_dict[key]

for i in range(q):
  b, c = map(int, input().split())
  query_dict = {}
  query_dict[b] = c
  a_list = [replace_seq(a) for a in a_list]
  print(sum(a_list))

Submission status: Time Limit Exceeded

Solution code:
def main():
    N=int(input())
    l=[0]*10**5
    A=map(int, input().split())
    for a in A:
        l[a-1]+=a
    Q=int(input())
    BC=[list(map(int,input().split())) for _ in range(Q)]
    for bc in BC:
        cnt=l[bc[0]-1]//bc[0]
        l[bc[0]-1]=0
        l[bc[1]-1]+=bc[1]*cnt
        print(sum(l))
    return

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

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

g = []
t = sum(a)
s = []

for j in range(100001):
    h = a.count(j)
    g.append(h)

for i in range(q):
    b,c = map(int,input().split())
    if g[b] != 0:
        t = t + c*g[b] - b*g[b]
        g[c] = g[c] + g[b]
        g[b] = 0
        s.append(t)
    else:
        s.append(t)

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

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 = a
for i in range(q):
    s = [s[q] if s[q] != b[i] else c[i] for q in range(n)]
    print(sum(s))

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

sum = sum(A)

for i in range(Q):
    B[i], C[i] = map(int, input().split())
    
    time = 0
    for k in range(N):
        if A[k] == B[i]:
            A[k] = C[i]
            time += 1
        
    sum += (C[i]-B[i])*time

    print(sum)

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
        else :
            print(ans)
            continue
        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 = []
for i in range(q):
    bc.append(list(map(int, input().split())))

dic = {}
for i in range(n):
    if str(a[i]) not in dic:
        dic[str(a[i])] = 1
    else:
        dic[str(a[i])] += 1

for i in range(q):
    ans = 0
    if str(bc[i][0]) in dic:
        buf = dic[str(bc[i][0])]
        dic[str(bc[i][0])] = 0
        if str(bc[i][1]) in dic:
            dic[str(bc[i][1])] += buf
        else:
            dic[str(bc[i][1])] = buf

    for j in dic:
        ans += int(j) * dic[j]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
from typing import List


def main() -> None:
    N = int(input())
    A = sorted([int(_) for _ in input().split(' ')])
    Q = int(input())

    for i in range(Q):
        _1, _2 = map(int, input().split(' '))
        for j in range(N):
            if A[j] < _1:
                continue
            if A[j] == _1:
                A[j] = _2
            else:  # A[j] > _1
                A = sorted(A)
                break

        print(sum(A))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

for i in range(Q):
  BC = list(map(int, input().split()))
  B_i = BC[0]
  C_i = BC[1]
  for j in range(len(A)):
    if A[j] == B_i:
      A[j] = C_i
  A = sorted(A)
  print(sum(A))

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):
    if b[i] in adic and c[i] in adic:
        adic[c[i]]=adic[c[i]]+adic[b[i]]
        adic[b[i]]=0
    elif b[i] in adic and (not c[i] in adic):
        adic[c[i]]=adic[b[i]]
        adic[b[i]]=0
#    print(i,adic)
    asum=0
    for i,ad in adic.items():
        asum+=i*ad
    print(asum)

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 for _ in range(q)]
c = [0 for _ in range(q)]
for i in range(q):
    b[i], c[i] = map(int, input().split())

a = np.array(a)
for num, rep in zip(b, c):
    if num in set(a):
        a = np.where(a == num, rep, a)
        print(sum(a))
    else:
        print(sum(a))
        continue

Submission status: Time Limit Exceeded

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

for i in range(Q):
    b,c=map(int,input().split())
    if b in li:
        for j in range(N):
            if li[j] == b:
                li [j] = c
    li2.append(sum(li))

for i in range(Q):
    print(li2[i])

Submission status: Time Limit Exceeded

Solution code:
s = int(input()) 

dict={}
num_list = list(map(int, input().split()))

length=len(num_list)
count=[0]*(s+1000)
for i in range(length):
    count[num_list[i]]+=1
    dict[num_list[i]]=count[num_list[i]]
    
#print(dict)


sum=0
count=0
n = int(input()) 
for i in range(n):
    a,b = map(int, input().split())  
    if dict.get(a)!=None:
        if dict.get(b)!=None:
            count=dict[b]
            dict[b]=dict[a]+dict[b]
        else:
            dict[b]=dict[a]
        dict[a]=0
    else:
        pass
    #print(dict)
    for k, v in dict.items():
        sum+=k*v
    print(sum)
    sum=0

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import numpy as np
readline = sys.stdin.buffer.readline

N = int(readline())
A = np.array(list(map(int, readline().split())))
Q = int(readline())

answer = [0] * Q

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

    A = np.where(A == B, C, A)
    print(np.sum(A))