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())
B=[list(map(int,input().split())) for i in range(Q)]
from bisect import bisect_left
# def 二分探索(リスト, 要素)
def index(lst, e):
    # Step 1. bisect_left して
    i = bisect_left(lst, e)
    
    # Step 2. 変な値を ValueError で弾いて
    if i == len(lst):
        return -1
    if lst[i] != e:
        return -1
    # Step 3. 値を返す。
    return i
def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    mid = len(arr) // 2
    # ここで分割を行う
    left = arr[:mid]
    right = arr[mid:]

    # 再帰的に分割を行う
    left = merge_sort(left)
    right = merge_sort(right)

    # returnが返ってきたら、結合を行い、結合したものを次に渡す
    return merge(left, right)

def merge(left, right):
    merged = []
    l_i, r_i = 0, 0

    # ソート済み配列をマージするため、それぞれ左から見ていくだけで良い
    while l_i < len(left) and r_i < len(right):
        # ここで=をつけることで安定性を保っている
        if left[l_i] <= right[r_i]:
            merged.append(left[l_i])
            l_i += 1
        else:
            merged.append(right[r_i])
            r_i += 1

    # 上のwhile文のどちらかがFalseになった場合終了するため、あまりをextendする
    if l_i < len(left):
        merged.extend(left[l_i:])
    if r_i < len(right):
        merged.extend(right[r_i:])
    return merged

A=merge_sort(A)
for i in B:
    j=1
    while j!=-1:
        j=index(A,i[0])
        if not j==-1:
            A[j]=i[1]
        A=merge_sort(A)
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
list_a=list(map(int,input().split()))
k=int(input())
for i in range(k):
  a,b=map(int,input().split())
  for k in range(n):
    if list_a[k]==a:
      list_a[k]=b
    else:
      continue
  print(sum(list_a))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
lst = list(map(int, input().split()))
q = int(input())
for _ in range(q):
    a, b = map(int, input().split())
    summ = 0
    for i in range(n):
        if lst[i] == a:
            lst[i] = b
            summ += lst[i]
        else:
            summ += lst[i]
    print(summ)

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 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())
bc = []
for i 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=sorted(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:
      if j!=n:
        for k in range(n-j):
          if A[j+k]!=b:
            break
          else:
            A[j+k]=c
        break
      else:
        A[j]=c
  print(sum(A))

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:
        cot = ans.count(b)
        ans =[ans[j] for j in range(n) if ans[j] != b]        
        for j in range(cot):
            ans.append(c)
    print(sum(ans))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter


n = int(input())
a = list(map(int, input().split()))
counter = Counter(a)
ini_sum = sum(a)
q = int(input())
s = [0] * q

for i in range(q):
    b, c = map(int, input().split())
    counter[c] += counter[b]
    counter[b] = 0
    print(sum(key * value for key, value in counter.items()))

Submission status: Time Limit Exceeded

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

for i in range(q):
    A = [sousa[i][1] if j == sousa[i][0] else j for j in A]
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=[int(i) for i in input().split()]
arr={}
P={}
for a in A:
	if a in arr:
		arr[a]+=1
	else:
		arr[a]=1
for k,v in arr.items():
	P[k]=k*v
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]
			P[C]+=arr[B]*C
		else:
			arr[C]=arr[B]
			P[C]=arr[B]*C
		del arr[B]
		del P[B]
	print(sum([i for i in P.values()]))

Submission status: Time Limit Exceeded

Solution code:
n =int(input())
a = list(map(int,input().split()))
A =set(a)
q =int(input())
for _ in range (q):
  b, q = map(int,input().split())
  if b in A:
    a = [q if _ == b else _ for _ in a]
    A =set(a)
  print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
N = int(input().strip())
A = list(map(int, input().strip().split()))
Q = int(input())
BC = [list(map(int, input().strip().split())) for q in range(Q)]

for bc in BC:
    A = [a if a != bc[0] else bc[1] for a in A]
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
import collections

def add(c):
    return sum([int(k)*int(v) for k, v in c.items()])

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

c = collections.Counter(a)
for i in range(q):
    # 存在しないときにエラーになる
    if c.get(rep[i][0]):
        c[rep[i][1]] += c.pop(rep[i][0])
    s.append(add(c))
print('\n'.join([str(each) for each in s[1:]]))

Submission status: Time Limit Exceeded

Solution code:
import collections

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

hikaku = 0
a_wa = sum(a)

for i in range(q):
    cou = collections.Counter(a)

    a_wa += cou[b[i][0]] * b[i][1] - cou[b[i][0]] * b[i][0]
    for l in range(cou[b[i][0]]):
        a.remove(b[i][0])
        a.append(b[i][1])

    print(a_wa)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def main():
  n = int(input())
  a = np.array(list(map(int, input().split())))
  q = int(input())
  
  for _ in range(q):
    b, c = map(int, input().split())
    a = np.where(a == b, c, a)
    print(sum(a))
  
main()

Submission status: Time Limit Exceeded

Solution code:
import sys

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

N = int(input())
#print(N)

a = input().split()
A = [int(b.strip()) for b in a]
#print(A)

Q =  int(input())
#print(Q)

for i in range(Q):
  target = input()
  if i == 0:
    ret = retList(target, A)
  else:
    ret = retList(target, ret)
  print(sum(ret))

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(sum(AAA))
        pass
    else:
        how_many_changes = AAA.count(BC[0])
        sabun = BC[1] - BC[0]
        AAA = [BC[1] if m == BC[0] else m for m in AAA]
        goukei_AAA = goukei_AAA + (how_many_changes * sabun)
        print(goukei_AAA)

Submission status: Time Limit Exceeded

Solution code:
import bisect

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

Q = int(input())

for i in range(Q):
  x,y = map(int,input().split())
  search = x
  A.sort()
  b=bisect.bisect_left(A,search)
  c=bisect.bisect_right(A,search)
  for j in range(b,c):
    A[j] = y
  print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)
N=int(input())
A=list(map(int,input().split()))
Q=int(input())
BC = [list(map(int,input().split())) for _ in range(Q)]
for i in range(Q):
  A = [BC[i][1] if j == BC[i][0] else j for j in A]
  print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
#D - Replacing
import collections
N= int(input())
A= list(map(int,input().split()))
Q = int(input())
B = [list(map(int,input().split())) for i in range(Q)]

A.sort()
sub = 0
ans = sum(A)

for i in range(Q):
    if A.count(B[i][0]) > 0:
        #for j in range(A.count(B[i][0])):
        ans = ans +(B[i][1] - B[i][0])*A.count(B[i][0])
        for j in range(N):
            if A[j] == B[i][0]:
                A[j] = B[i][1]
            else:
                pass
        print(ans)

    else:
        print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
total=sum(A)
for i in range(Q):
    B, C = map(int, input().split())
    x=A.count(B)
    if x>0:
        total=total-B*x+C*x
        A.extend([C]*x)
    print(total)

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 range(q):
    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:
N=int(input())
A=list(map(int,input().split()))
Q=int(input())
B=[]
for i in range(Q):
    B.append(list(map(int,input().split())))
sum=int(0)
AA=[int(0)]
for i in range(100000):
    AA.append(int(0))
for i in range(100001):
    AA[i]=A.count(int(i))
#for i in range(5):
#    print(AA[i])
sum=int(0)
for i in range(N):
    sum += A[i]
for i in range(Q):
    sum = sum + B[i][1]*AA[(B[i][0])]-B[i][0]*AA[(B[i][0])]
    AA[(B[i][1])] = AA[(B[i][1])]+AA[(B[i][0])]
    AA[(B[i][0])] = 0
    print(sum)

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
        sum_list.append(sum)
    for value in sum_list:
        print(value)
if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

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

N=int(input().rstrip('\n'))
As = [int(x) for x in input().rstrip('\n').split()]
res = sum(As)
dis = {i:As.count(i) for i in set(As)}
Q=int(input().rstrip('\n'))
Qs=[]
for i in range(Q):
  Qs.append(tuple(int(x) for x in input().rstrip('\n').split()))
for B,C in Qs:
  if B in dis:
    res += dis[B]*(C-B)
    if C in dis:
      dis[C] += dis[B]
    else:
      dis[C] = dis[B]
    dis[B]=0
  print(res)

Submission status: Time Limit Exceeded

Solution code:
import sys
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
bc = []
for q in range(Q):
    b, c = map(int, input().split())
    A = [c if b == a else a for a 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()))

a_array = np.zeros((100001), dtype = np.int)
a_array = a_array.reshape((1, 100001))
a_val = np.arange(100001)
a_val = a_val.reshape((1, 100001))
a_val = a_val.transpose()

for i in range(len(a)):
  a_array[0, a[i]] += 1

q = int(input())

for i in range(q):
  b, c = map(int, input().split())
  if a_array[0, b] != 0:
    a_array[0, c] += a_array[0 ,b]
    a_array[0, b] = 0
  print(np.dot(a_array, a_val)[0,0])

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

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

q = int(input())

#初期化

a_dic ={}


for i in a:
    if i not in a_dic:
        a_dic[i] = 1
    else:
        a_dic[i] += 1

#a_sorted = sorted(a)
for i in range(q):
    ans = 0
    b,c = map(int, input().split())
    #print(a_dic)
    
    if b in a_dic:
        if c not in a_dic:
            a_dic[c] = a_dic[b]

        else:
            tmp_c = a_dic[c]
            tmp_c += a_dic[b]
            a_dic[c] = tmp_c
        a_dic.pop(b) 
    for k,v in a_dic.items():
        ans += k*v
    print(ans)

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] :
            ans = ans - (B[i] - C[i]) * num
        else :
            ans = ans + (C[i] - B[i]) * num
        for j in range(len(A_list)) :
            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())
list_str = input()
for a in range(int(input())):
    b, c = input().split()
    list_str = list_str.replace(b, c)
    list = list_str.split()
    list_int = [int(i) for i in list]
    print(sum(list_int))
    list_int = []

Submission status: Time Limit Exceeded

Solution code:
class Box:
  def __init__(self, line):
    self.__b = {}
    for i in map(int, line.split(' ')):
      if i not in self.__b:
        self.__b[i] = 1
      else:
        self.__b[i] += 1

  def convert(self, b, c):
    if b in self.__b:
      if c in self.__b:
        self.__b[c] += self.__b[b]
      else:
        self.__b[c] = self.__b[b]

      self.__b[b] = 0

  def sum(self):
    ret = 0
    for k, v in self.__b.items():
      ret += k * v
    return ret

if __name__ == "__main__":
  n = int(input())
  b = Box(input())
  q = int(input())
  for i in range(q):
    b.convert(*list(map(int, input().split(' '))))
    print(b.sum())

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):
  su = 0
  b,c = map(int,input().split())
  for j in range(n):
    if(a[j] == b):
      a[j] = c
    su += a[j]
  print(su)

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

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

S = [0]*Q
for i in range(Q):
    for j in range(N):
        if A[j] == B[i]:
            A[j] = C[i]
    S[i] = sum(A)

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [int(i) for i in input().split(" ")]
Q = int(input())
for i 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:
def my_index(l, x, default=False):
    if x in l:
        return l.index(x)
    else:
        return default
      
      
n = int(input())
a = [int(i) for i in input().split(' ')]
q = int(input())
b = []
c = []
#for _ in range(q):
#  temp = input().split(' ')
#  b.append(int(temp[0]))
#  c.append(int(temp[1]))

for _ in range(q):
  temp = input().split(' ')
  i = int(temp[0])
  j = int(temp[1])
  if i in a:
    while True:
      k = my_index(a, i)
      if k is False:
        break
      a[k] = j
  print(sum(a))

Submission status: Time Limit Exceeded

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

for i in range(Q):
  L, R = map(int,(input().split()))
  B_count=np.count_nonzero(npArray == L)
  sa=(R-L)*B_count
  #npArray = np.where(npArray == L,R, npArray)
  npArray[npArray == L] = R
  ans= ans+sa
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
input()
a = list(map(int, input().split()))
b = int(input())
for i in range(b):
  c = list(map(int, input().split()))
  a = [c[1] if d == c[0] else d for d in a]
  f = 0
  for e in a:
    f += e
  print(f)

Submission status: Time Limit Exceeded

Solution code:
if __name__=='__main__':
    N = int(input())
    A = input().split(" ")
    A = [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):
        if int(str_list[j][0]) in A:
            #A=[s.replace(int(str_list[j][0]),int(str_list[j][1])) for s in A]
            A=[(int(str_list[j][1])) if i == int(str_list[j][0]) else i for i in A]
        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 = LI()
Q = I()
BC_ARR = [LI() for _ in range(Q)]

for s in range(Q):
    for t in range(N):
        if A[t] == BC_ARR[s][0]:
            A[t] = BC_ARR[s][1]
    print(numpy.sum(A))

Submission status: Time Limit Exceeded

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

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

count = collections.Counter(a)

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

    sum = 0
    for i in count:
        sum += count[i] * i

    print(sum)

Submission status: Time Limit Exceeded

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

data = {}

def my_sum(d):
    retval = 0

    for i in d.keys():
        retval += d[i] * i
    return retval

for i in A:
    if i in data.keys():
        data[i] += 1
    else:
        data[i] = 1
 
for i in range(Q):
    B, C = map(int, input().split())

    if B not in data.keys():
        print(my_sum(data))
        continue
 
    if C in data.keys():
        data[C] = data[C] + data[B]
    else:
        data[C] = data[B]
    del data[B]
 
    print(my_sum(data))

Submission status: Time Limit Exceeded

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

q = int(input())
bb = []
cc = []

for i in range(q):
  b, c = map(int, input().split())
  bb.append(b)
  cc.append(c)
  
for i in range(q):
  sum = 0
  for j in range(n):
    if a[j] == bb[i]:
      a[j] = cc[i]
    sum = sum + a[j]
  print(sum)

Submission status: Time Limit Exceeded

Solution code:
hyou = [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

    # 合計を求めて出力
    total = 0
    for i,x in enumerate(hyou):
        total += i*x
    print(total)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

for j in range(Q):
    BC.append(list(map(int, input().split())))

for i in range(Q):
    if str(BC[i][0]) in str(A):
        ilst= [m for m, x in enumerate(A) if x == BC[i][0]]
#        print("ilst="+str(ilst))
        for j in ilst:
            A[j]=BC[i][1]
#            print("A[j]="+str(A))
#            print(str(BC[i][0]))
#    print("A="+str(A))
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

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

Q = int(input())

Anslist = [0] * Q

for i in range(Q):

    b, c = map(int, input().split())

    A_replace = [c if j == b else j for j in A]

    A = A_replace
    
    Anslist[i] += sum(A_replace)

for k in range(Q):
    
    print(Anslist[k])

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(str, input().split()))
Q = int(input())
S = []
c = 0


for i in range(Q):
    B, C = map(str,input().split())
    if B in A:
        string = ",".join(A)
        string_new = string.replace(B,C)
        A =  string_new.split(",")


    S.append(sum(map((lambda x: int(x)), A)))



for s in S:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
a=list(map(int,input().split()))
dic={}
for i in range(n):
  if a[i] in dic:
    dic[a[i]]+=1
  else:
    dic[a[i]]=1
q=int(input())
for i in range(q):
  b,c=map(int,input().split())
  if b in dic:
    if c in dic:
      dic[c]+=dic[b]
      del dic[b]
    else:
      dic[c]=dic[b]
      del dic[b]
  ans=0
  for key,value in dic.items():
    ans+=key*value
  print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
def run(n, seq, num, trials):
    '''
    '''
    for i in range(num):
        b, c = trials[i]
        if b not in seq:
            print(sum(seq))
            continue
        seq = [e if e != b else c for e in seq]
        print(sum(seq))


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:
import collections

N = int(input())
A = input().split()
Q = int(input())
a = collections.Counter(A)
ans2 = []
for i in range(Q):
    ans = 0
    B, C = map(str, input().split())
    if B in a and C in a:
        a[C] += a[B]
        del a[B]
    elif B in a and C not in a:
        a[C] = a[B]
        del a[B]
    for key, value in a.items():
        ans += int(key)*value
    ans2.append(ans)
[print(a) for a in ans2]

Submission status: Time Limit Exceeded

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

for i in range(Q):
  cnt = 0
  for j in range(N):
    if A[j] == pairs[i][0]:
      A[j] = pairs[i][1]
    cnt += int(A[j])

#  ret = sum(list(map(int,A)))
  print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import collections

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

dic = collections.Counter(a)
val = 0
for i in range(q):
    if b[i] in dic:
        if c[i] not in dic:
            dic[c[i]] = 0
        dic[c[i]] += dic[b[i]]
        dic[b[i]] = 0
    for key, value in dic.items():
        val +=key*value
    print(val)
    val=0

Submission status: Time Limit Exceeded

Solution code:
n=int(input())

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

z=[0]*((10**5)+1)

for i in range(n):
  z[a[i]]+=1

q=int(input())

y=[]


for i in range(q):
  b,c=map(int,input().split())
  z[c]+=z[b]
  z[b]=0
  #print(z)
  sam=0
  for j in range(len(z)):
    sam+=z[j]*j
  y.append(sam)

for i in range(len(y)):
  print(y[i])

Submission status: Time Limit Exceeded

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

for i in range(q):
  b, c = map(int,input().split())
  for i in range(n):
    if a[i] == b:
      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())
for i in range(q):
    b,c=map(int,input().split())
    for j,k in enumerate(a):
        if b == k:
            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())
changes = []
for i in range(Q):
    changes.append(tuple(map(int, input().split())))

num = {i:0 for i in range(1, 100001)}
for i in A:
    num[i] += 1

for change in changes:
    num[change[1]] += num[change[0]]
    num[change[0]] = 0
    s = sum([i * c for i, c in num.items()])
    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())
  
  a = [c if k==b else k for k in a]
  print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8

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

A.sort()

dict_a = dict()

for a in A:
    if not (a in dict_a):
        dict_a[a] = 1
    else:
        dict_a[a] += 1


Q = int(input())

B = []
C = []

sums = []
for i in range(Q):
    b, c = list(map(int, input().split()))

    if (b in dict_a):
        num = dict_a[b]
    
        if not (c in dict_a):
            dict_a[c] = num
        else:
            dict_a[c] += num

        dict_a.pop(b)

    keys = dict_a.keys()
    vals = dict_a.values()

    sumval = 0
    for k, v in zip(keys, vals):
        sumval += k * v

    print(sumval)

Submission status: Time Limit Exceeded

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

for i in range(Q):
    b, c = map(int, input().split())
    s = 0
    e = N
    h = int((s+e)/2)
    while A[h] != b and s != h :
        if A[h] < b:
            s = h
            h = int((s+e)/2)
        elif A[h] > b:
            e = h
            h = int((s+e)/2)
    for j in range(s, e):
        if A[j] == b:
            A[j] = c
    A.sort()
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
def sol():
    n=int(input())
    A=input()
    q=int(input())
    for i in range(q):
        b,c=map(str,input().split())
        A=A.replace(b,c)
        print(sum([int(i) for i in A.split()]))
if(__name__=='__main__'):
    sol()

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):
  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:
import numpy as np
n = int(input())
a =np.array([int(x) for x in input().split()])
q = int(input())
bc = [map(int, input().split()) for _ in range(q)]
b, c = [list(i) for i in zip(*bc)]

for i in range(q):
    a = np.sort(a)
    ans = 0
    for j in range(len(a)):
        if a[j] <= 10 **5:
            if a[j] == b[i]:
                a[j] = c[i]
        ans += a[j]
    print(ans)

Submission status: Time Limit Exceeded

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

aDict = dict()
for aElement in A:
    aDict.setdefault(aElement, 0)
    aDict[aElement] += 1

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

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())))
num=[0]*(10**5+1)
for i in range(n):
    x=a[i]
    num[x]+=1


for k in range (q):
    b=bc[k][0]
    c=bc[k][1]
    num[c]+=num[b]
    num[b]=0
    kk=0
    for l in range(10**5+1):
        kk+=l*num[l]
    print(kk)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())

A_list = [int(n) for n in input().split()]
A_array = np.array(A_list)

Q = int(input())

for N in range(Q):
    B, C = map(int, input().split())
    if B in A_array:
        A_array[A_array == B] = C
    print(np.sum(A_array))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
Ac = {}
for a in [ int(i) for i in input().strip().split(' ')]:
    if a in Ac:
        Ac[a] += 1
    else:
        Ac[a] = 1

Q = int(input())
for q in range(Q):
    B, C = [ int(i) for i in input().strip().split(' ')]
    
    if B in Ac:
        if C in Ac:
            Ac[C] += Ac[B]
        else:
            Ac[C] = Ac[B]
        del Ac[B]
        
    print(sum([k*v for k, v in Ac.items()]))

Submission status: Time Limit Exceeded

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

for i in range(Q):
  A = [C[i] if a == B[i] else a for a in A]
  S.append(sum(A))

for s in S:
  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)
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
    print(s)