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())
ls = list(map(int,input().split()))
q = int(input())
qls = []
for i in range(q):
	a, b = input().split()
	a, b = int(a), int(b)
	subls = []
	subls.append(a)
	subls.append(b)
	qls.append(subls)

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

freqlist = dict()

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

for i in range(q):
	a = qls[i][0]
	b = qls[i][1]
	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())
for j 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:
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) )
    
for c1 in range (q):
    print(ans[c1])

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)]
for f in bc:
    a = [f[1] if j == f[0] 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(str,input().split())
    a = [str(s) for s in a]
    a=[s.replace(b,c) for s in a]
    a = [int(s) for s in a]
    print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
A = map(int, input().split())
q = int(input())
move = []
l={}
for _ in range(q):
    b, c = map(int, input().split())
    move.append((b,c))
for i in A:
    if i in l:
        l[i]+=1
    else:
        l[i]=1
sum = 0
sumflag=False
for (f,t) in move:
    if f in l:
        if t in l:
            l[t]+=l[f]
            l[f]=0
        else:
            l[t]=l[f]
            l[f]=0
        sum = 0
        for k,v in l.items():
            sum += k*v
        print(sum)
        sumflag=True
    else:
        if sumflag:
            print(sum)
        else:
            for k,v in l.items():
                sum += k*v
                print(sum)
                sumflag=True

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

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

ans = []

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

    if b in nums:
        cnt = 0
        is_b = True
        while is_b:
            nums.remove(b)
            cnt += 1
            if not b in nums:
                is_b = False
                nums = nums + [c] * cnt


    ans.append(sum(nums))

for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
import sys
import collections

ri = lambda: int(sys.stdin.readline())
rl = lambda: list(map(int, sys.stdin.readline().split()))

n = ri()
a = rl()
il = list(set(a))
li = collections.Counter(a)
q = ri()
res = []
bc = [rl() for _ in range(q)]
for vvv in bc:
    b, c = vvv
    if b in il:
        if c in il:
            li[c] += li[b]
        else:
            li[c] = li[b]
            il.append(c)
        li[b] = 0
        il.remove(b)
    ans = 0
    for k, v in li.items():
        ans += k*v
    res.append(ans)
for aaa in res:
    print(aaa)

Submission status: Time Limit Exceeded

Solution code:
import sys

def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def main():
    n = I()
    a = LI()
    q = I()
    b = [0]*q
    c = [0]*q
    for i in range(q):
        b[i], c[i] = MI()
    a_sum = sum(a)
    a_dict = dict()
    for ai in a:
        a_dict[str(ai)] = a.count(ai)
    for i in range(q):
        temp1 = 0
        if str(b[i]) in a_dict:
            temp1 = a_dict[str(b[i])]
        temp2 = 0
        if str(c[i]) in a_dict:
            temp2 = a_dict[str(c[i])]
        a_dict[str(c[i])] = temp1+temp2
        a_sum += (c[i]-b[i])*temp1
        print(a_sum)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
l=[int(k) for k in input().split()]
lnew={}
for i in l:
  if i in lnew:
    lnew[i]+=1
  else:lnew[i]=1

k=int(input())
for i in range(k):
  a,b=input().split()
  a=int(a)
  b=int(b)
  if a in lnew:
    c=0
    if b in lnew:
      c=lnew[b]
    lnew[b]=c+lnew[a]
  lnew.pop(a,None)
  Sum=0
  for num,val in lnew.items():
    Sum+=num*val
  print(Sum)

Submission status: Time Limit Exceeded

Solution code:
import collections

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

aCount = dict(collections.Counter(A))

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [0 for i in range(n)]
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:
a = input()
A = list(map(int,input().split()))
N = int(input())
for i in range(N):
    b,c = map(int,input().split())
    ind = [i for i, x in enumerate(A) if x == b]
    for j in ind:
        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=[list(map(int,input().split())) for i in range(Q)]
from bisect import bisect_left,bisect_right
# 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 index2(lst, e):
    # Step 1. bisect_left して
    i = bisect_right(lst, e)
    
    # Step 2. 変な値を ValueError で弾いて
    if i == len(lst)+1:
        return -1
    if lst[i-1] != e:
        return -1
    # Step 3. 値を返す。
    return i
def count_sort(arr):
    max_num = max(arr)
    min_num = min(arr)
    count = [0] * (max_num - min_num + 1)
    for ele in arr:
        count[ele - min_num] += 1

    return [ele for ele, cnt in enumerate(count, start=min_num) for __ in range(cnt)]

A=count_sort(A)

for i in B:
    j=index(A,i[0])
    if not j==-1:
        k=index2(A,i[0])
        for l in range(j,k):
            A[l]=i[1]
    A=count_sort(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())
    if b in A:
        for i in range(len(A)):
            if b == A[i]:
                A[i] = c
    print(sum(A))

Submission status: Time Limit Exceeded

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



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

Submission status: Time Limit Exceeded

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

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])
    str_list = A.split()
    num_list = list(map(int, str_list))
    print(sum(num_list))

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import Counter
readline = sys.stdin.buffer.readline

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

for b, c in L:
  # print(a)
  if b in a:
    a[c] += a[b]
    del a[b]
  print(sum(x * y for x, y in a.items()))

Submission status: Time Limit Exceeded

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


N = int(input())
A_list = input().split()
Q = int(input())
num_list = [input().split() for _ in range(Q)]

A_cha = ",".join(A_list)
for i in num_list:
    B = i[0]
    C = i[1]
    A_cha = A_cha.replace(B, C)
    A_result = sum([int(A) for A in A_cha.split(",")])
    print(A_result)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
n = int(input())
a = list(map(int, input().split()))
a.sort()
counter = Counter(a)
key = list(counter.keys())
value = list(counter.values())

s = sum(a)
q = int(input())

for i in range(q):
  b, c = map(int, input().split())
  if b in key:
    x = key.index(b)
    if c in key:
      y = key.index(c)
      s += (c - b) * value[x]
      value[y] += value[x]
      del key[x]
      del value[x]
    else:
      key[x] = c
      s += (c - b) * value[x]
  else:
    pass
  print(s)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

n = int(input())

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

a_array = np.zeros((max(a)+1), dtype = np.int)
a_array = a_array.reshape((1, max(a)+1))
a_val = np.arange(max(a)+1)
a_val = a_val.reshape((1, max(a)+1))
a_val = a_val.transpose()

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

q = int(input())

ans = np.dot(a_array, a_val)[0,0]
max_a = max(a)

for i in range(q):
  b, c = map(int, input().split())
  if b < a_array.shape[1]:
    if a_array[0, b] != 0:
      if c > max_a:
        a_array = np.append(a_array, np.zeros((1, c - max_a)), axis = 1)
        a_val = np.arange(c+1)
        a_val = a_val.reshape((1, c+1))
        a_val = a_val.transpose()
        max_a = c
      a_array[0, c] += a_array[0 ,b]
      a_array[0, b] = 0
      ans = np.dot(a_array, a_val)[0,0]
  print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
l=list(map(int,input().split()))
freq={}
for i in range(n):
	freq[l[i]]=0
for i in range(n):
	freq[l[i]]+=1
t=int(input())
for i in range(t):
	a,b=map(int,input().split())
	if(a not in freq.keys()):
		sm=0
		for x, y in freq.items():
			sm+=(x*y)
		print(sm)
	else:
		if(b not in freq.keys()):
			freq[b]=0
		freq[b]+=freq[a]
		freq[a]=0
		sm=0
		for x, y in freq.items():
			sm+=(x*y)
		print(sm)

Submission status: Time Limit Exceeded

Solution code:
import collections
n = int(input())
l = list(map(int, input().split()))
a = int(input())
c = collections.Counter(l)
for i in range(a):
    j,k =  map(int, input().split())
    save = c[j]
    del c[j]
    c[k] += save
    answer = 0
    for q,r in c.items():
        answer += int(q)*int(r)
    print(answer)

Submission status: Time Limit Exceeded

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

A_counter = Counter(A)
for b in B:
    cnt = A_counter[b[0]]
    A_counter[b[1]] += cnt
    del A_counter[b[0]]
    print(sum([num * cnt for num, cnt in A_counter.items()]))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
ans = sum(A)
for i in range(Q):
  b,c = map(int, input().split())
  cnt = A.count(b)
  for i in range(cnt):
    A.remove(b)
    A.append(c)
  ans += (c-b) * cnt
  print(ans)

Submission status: Time Limit Exceeded

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

def list1(n):
  if n == b:
    return c
  else:
    return n
  
for i in range(q):
  b, c = map(int, input().split())
  a = list(map(list1, a))
  print(sum(a))

Submission status: Time Limit Exceeded

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

for i in range(q):
  s=input().split()
  a=[int(s[1]) if j==int(s[0]) 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())
b = [0] * q
c = [0] * q

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

Submission status: Time Limit Exceeded

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

    sum_list = list()
    for i in range(Q):
        B, C = input().split(" ")
        # sum = 0
        # breakpoint()
        A[A==int(B)] = int(C)
        sum_list.append(sum(A))

    for value in sum_list:
        print(value)
if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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


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

Submission status: Time Limit Exceeded

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

d = {}
for i in a:
    if not i in d.keys():
        d[i] = 1
    else:
        d[i] += 1

q = int(input())

for _ in range(q):
    b, c = map(str, input().split())
    if b in d.keys():
        if c in d.keys():
            d[c] += d[b]
        else:
            d[c] = d[b]
        d.pop(b)
    ans = 0
    for k, v in d.items():
        ans += int(k) * v
    print(ans)

Submission status: Time Limit Exceeded

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

for i in range(Q):
    if B[i] in A:        
        string = ",".join(A)
        string_new = string.replace(B[i],C[i])
        A =  string_new.split(",")
        s = sum(list(map(int,A)))
    
    print(s)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

#---------------------------------
#2分探索
def binary_search(array, target):
    lower = 0                               
    upper = len(array) -1

    while lower < upper:#上限と下限が反転するまで探索
        mid = (lower + upper) // 2
        result = array[mid] #真ん中の要素を調べる

        if array[mid] < target:#小さければ下限を変更
            lower = mid + 1 
        else:#その他はここ
            upper = mid

    if array[lower] == target:#最後にtargetとlowerが一致しているか判定
        return(lower)
    else:
        return(None)

#------------------------------------
#重複要素の検索
def Duplication_search(result,arry):
    #Noneなら何もしない 要素があれば次の要素を検索する
    if result is None:
        pass
    else:
        result_list = []        
        #探索した要素があればさらに重複要素がないか調べていく
        for i in range(len(arry)):
            if b == arry[i]:
                result_list.append(result)
                result = result + 1
        return(result_list)

def func2(l, value):
    i = -1
    c = len(l)
    result = []
    while i < c:
        try:
            i = l.index(value, i + 1)
            result.append(i)
        except:
            return result
    return result

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

for i in range(q):
    a_li = np.sort(a_li)
    b,c = map(int,input().split())
    result = binary_search(a_li, b)
    indexes = Duplication_search(result,a_li)
    if indexes is None:
        print(sum(a_li))
        continue
    for i in indexes:
        a_li[i] = c
    print(sum(a_li))

Submission status: Time Limit Exceeded

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

l.sort()
m = []
count = [0 for i in range(Q)]
flag = [0 for i in range(Q)]

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

ans = sum(l)

for i in range(Q):
    for j in range(N):
        if l[j] == m[i][0]:
            count[i] += 1
        elif l[j] > m[i][0]:
            break
    for j in range(i-1,-1,-1):
        if m[j][1] == m[i][0]:
            if flag[j] == 0:
                count[i] += count[j]
                flag[j] = 1
    ans += (m[i][1]-m[i][0])*count[i]
    print(ans)

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'))
for i in range(Q):
  B,C=(int(x) for x in input().rstrip('\n').split())
  if B in dis:
    n = dis[B]
    if C in dis:
      dis[C] += n
    else:
      dis[C] = n
    res += n*(C-B)
    del dis[B]
  print(res)

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
        k_dic = list(dic.keys())
        v_dic = list(dic.values())
        ans = 0
        for i in range(len(k_dic)):
            if v_dic != 0:
                ans += k_dic[i] * v_dic[i]
        print(ans)
main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import Counter
readline = sys.stdin.buffer.readline

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

s = sum(a)
for b, c in L:
  # print(a)
  if b in a:
    a[c] += a[b]
    del a[b]
  print(sum(x * y for x, y in a.items()))

Submission status: Time Limit Exceeded

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

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

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

main()

Submission status: Time Limit Exceeded

Solution code:
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 = map(int, input().split())
    A = np.where(A==B, C, A)              
    print(np.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 = list(map(int, input().split()))
    sum_ = 0
    for j in range(len(A)):
        if A[j] == B:
            A[j] = C
        sum_ += A[j]
    print(sum_)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())
A_temp = list(map(int,input().split()))
A = np.array(A_temp)
Q = int(input())
result = []

for q in range(Q):
    B,C = map(int,input().split())
    A = np.where(A==B,C,A)
    result.append(np.sum(A))
[print(i) for i in result]

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)

a1 = []
a2 = []

for i in a:
	if i in a1:
		a2[a1.index(i)]+=1
	else:
		if i in b:
			a1.insert(0,i)
			a2.insert(0,1)
		else:
			a1.append(i)
			a2.append(1)

ans = []
s = 0

for i in range(len(a1)):
	s += a1[i]*a2[i]

ans.append(s)

for i in range(q):
	if b[i] in a1:
		bi = a1.index(b[i])
		if c[i] in a1:
			a2[a1.index(c[i])]+=a2[bi]
			ans.append(ans[-1]+a2[bi]*(c[i]-b[i]))
			a2[bi] = 0
		else:
			a1.append(c[i])
			a2.append(a2[bi])
			ans.append(ans[-1]+a2[bi]*(c[i]-b[i]))
			a2[bi] = 0
	else:
		ans.append(ans[-1])

for i in range(len(ans)-1):
	print(ans[i+1])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
n = int(input()) 
A = list(map(int, input().split()))
q = int(input()) 
for i in range(q):
    b, c = map(str, input().split())
    if int(b) in A:
        A = [int(str(a).replace(b, c)) for a in A]
    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)]

ans = np.sum(a)
for i in range(q):
    ans += np.count_nonzero(a == b[i])*(c[i]-b[i])
    print(ans)
    a = np.where(a == b[i], c[i],a)

Submission status: Time Limit Exceeded

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

sumP = sum(map(int, P.split()))
for i in range(Q):
    B, C = map(str, input().split())
    sumP -= (int(B)-int(C)) * P.count(B)
    P = P.replace(B, C)
    print(sumP)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
 
N = int(input())

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

npA = np.array(A)

Q = int(input())

Anslist = [0] * Q

for i in range(Q):

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

    A_replace = np.where(npA == b, c, npA)

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

freq = {}
A = list(map(int,input().split()))
for i in range(len(A)):
    freq[A[i]] = freq.get(A[i],0) + 1

q = int(input())

for i in range(q):
    b,c = map(int,input().split())
    ans = 0
    if c not in freq.keys():
        freq[c] = freq.get(c,0) + 0
    if b in freq.keys():
        freq[c] += freq[b]
        freq[b] = 0
    for keys,values in freq.items():
        ans += keys*values
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    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())))

    for i in range(q):
        for j in range(n):
            if(a[j] == bc[i][0]):
                a[j] = bc[i][1]
        print(sum(a))




if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = [int(i) for i in input().split(" ")]
q = int(input())

operations = []

for i in range(q):
    temp = input().split(" ")
    operations.append((int(temp[0]), int(temp[1])))

a.sort()

for op in operations:
    target, goto = op

    try:
        index = a.index(target)
        
        while True:
            if a[index] != target:
                break

            a[index] = goto
            index += 1

        print(sum(a))

    except:
        print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())

A_list = list(map(int, input().split()))
A_array = np.array(A_list)

Q = int(input())

for N in range(Q):
  
    B, C = map(int, input().split())
    
    if B == C:
      continue
    
    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())
A = list(map(int,input().split()))
Q = int(input())

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

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

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B_C = [list(map(int,input().split())) for i in range(Q)]
for i in range(Q):
    newlist = B_C[i]
    c = newlist[1]
    b = newlist[0]
    A = [c if k == b else k for k in A]
    print(sum(A))

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(1000000000)
input = sys.stdin.readline

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

x=[0]*(10**5)
for i in range(n):
    x[a[i]-1]+=a[i]


for _ in range(q):
    b,c=map(int,input().split())
    if x[b-1]!=0:
        x[c-1]+=x[b-1]//b*c
        x[b-1]=0
        print(sum(x))
    else:
        print(sum(x))

Submission status: Time Limit Exceeded

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

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


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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

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())
ans = sum(A)
for i in range(Q):
  b,c = map(int, input().split())
  cnt = 0
  while b in A:
    A.remove(b)
    A.append(c)
    cnt += 1
  ans += (c-b) * cnt
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
N = int(input())
A = Counter(list(map(int, input().split())))
Q = int(input())
S = []
for i in range(Q):
    B, C = list(map(int, input().split()))
    A[B], A[C] = 0, A[C]+A[B]
    s = sum([k*v for k, v in A.items()])
    S.append(s)
for s in S:
    print(s)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

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

Q = int(input())

goukei_AAA = sum(AAA)

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

        AAA = [BC[1] if m == BC[0] else m for m in AAA]
        goukei_AAA = goukei_AAA + (how_many_changes * (BC[1] - BC[0]))
        print(goukei_AAA)

Submission status: Time Limit Exceeded

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

sum = 0

for cnt_q in range(q):
    sum = 0
    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)