Problem:


Score : 400 points

Problem Statement

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

You will now successively do the following Q operations:

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

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

Constraints

All values in input are integers.

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

 B_{i} \neq C_{i} 

Input

Input is given from Standard Input in the following format:

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

Output

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

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

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

Sample Input 1

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

Sample Output 1

11
12
16

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

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

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

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000



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


Sample output:
11
12
16

Submission status: Time Limit Exceeded

Solution code:
import 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)]

for i in range(Q):
    b, c = map(int, input().split())
    num_A[c] += num_A[b]
    num_A[b] = 0
    print(sum(np.array(num_A)*np.array([j for j in range(10**5+1)])))

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)
    dis[B] = 0
  print(res)

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 = [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:
def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]

def main():
    n = int(input())
    a_list = [int(_) for _ in input().split()]
    Q = int(input())

    s_list = []
    for q in range(Q):
        b, c = map(int, input().split())
        a_index_list = my_index_multi(a_list, b)
        
        for i in a_index_list:
            a_list[i] = c

        s_list.append(sum(a_list))

    for s in s_list:
        print(s)

main()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter
n = int(input())
a = list(map(int, input().split()))
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:
n = int(input())
split = input().split()
inputList = [int(i) for i in split]
q = int(input())
bcList = []
for i in range(q):
    split = input().split()
    tmpList = [int(j) for j in split]
    bcList.append(tmpList)

#n=4
#inputList = [1,2,3,4]
#q=3
#bcList = [[1,2], [3,4], [2,4]]
for i in bcList:
    while i[0] in inputList:
        index = inputList.index(i[0])
        inputList[index] = i[1]
    print(sum(inputList))

Submission status: Time Limit Exceeded

Solution code:
import collections
import numpy as np

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())
#print(A,B,C)

c = collections.Counter(A)
values, counts = map(list,zip(*c.most_common()))
#print(values,counts)

for i in range(Q):
  #print(values,counts)
  if B[i] in values:
    idx = values.index(B[i])
  else:
    print(np.dot(np.array(values),np.array(counts)))
    continue
  values.pop(idx)
  num = counts.pop(idx)
  if C[i] in values:
    counts[values.index(C[i])]+=num
  else:
    values.append(C[i])
    counts.append(num)
  print(np.dot(np.array(values),np.array(counts)))

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin

def main():
    n = int(input())
    a = [int(x) for x in stdin.readline().rstrip().split()]
    base = sum(a)
    q = int(input())
    for i in range(q):
        b, c = [int(x) for x in stdin.readline().rstrip().split()]
        offset = c -b
        cnt = 0
        for i, aaa in enumerate(a):
            if aaa == b:
                a[i] = c
                cnt += 1
        base = base + offset*cnt
        print(base)
        

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
lstA = [int(Ai) for Ai in input().split()]
Q = int(input())
for _ in range(Q):
  i = 0
  B,C = [int(w) for w in input().split()]
  for idx, val in enumerate(lstA):
    if val == B:
      lstA[idx] = C
  print(sum(lstA))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
l=list(map(int,input().split()))
q=int(input())
for _ in range(q):
    b,c=map(int,input().split())
    for i in range(len(l)):
        if l[i]==b:
            l[i]=c
    x=l
    print(sum(x))

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = input().split()
alist = set()
adic = {}
for i in a:
    if int(i) in alist:
        adic[int(i)] = adic[int(i)] + 1
    else:
        alist.add(int(i))
        adic[int(i)] = 1

q = int(input())
ans = []

for i in range(q):
    s = input().split()
    b = int(s[0])
    c = int(s[1])
    su = 0
    if b in alist:
        if not(c in alist):
            adic[c] = 0
            alist.add(c)
        adic[c] = adic[c] + adic[b]
        adic[b] = 0
    for j in adic:
        su += j * adic[j]
    ans.append(su)
for i in range(len(ans)):
    print(ans[i])

Submission status: Time Limit Exceeded

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

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

    for i, j in enumerate(A):
        if j == 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())
b = [0] * q
c = [0] * q

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

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

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

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

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

ans = []
for _ in range(q):
    b, c = map(int, input().split())
    ary[c] += (ary[b]/b)*c
    ary[b] = 0
    ans.append(int(sum(ary)))

for a in ans:
    print(a)

Submission status: Time Limit Exceeded

Solution code:
s=int(input())
lst=list(map(int,input().split()))
q=int(input())
lis=[list(map(int,input().split())) for i in range(q)]

for j in range(q):
  for k in range(len(lst)):
    if lst[k]==lis[j][0]:
      lst[k]=lis[j][1]
  print(sum(lst))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
alist=list(map(int, input().split()))
Q=int(input())
bclist=[]
for i in range(Q):
    bclist.append(list(map(int, input().split())))
def repsum(alist,bc):
    alist.sort()
    for i in range(N):
        if alist[i]==bc[0]:
            alist[i]=bc[1]
        elif alist[i]>bc[0]:
            break
    return alist

for bc in bclist:
    alist=repsum(alist,bc)
    print(sum(alist))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

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

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
_ = input()
a = [*map(int, input().split())]
q = int(input())
b = [[*map(int,input().split())] for _ in range(q)]
n,c = np.unique(a,return_counts=True)
for i,j in b:
    d = np.where(n==i)
    n[d] = j
    print(sum(n*c))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
list_in = list(map(int, input().split()))
q = int(input())
for i in range(q):
    bc = list(map(int, input().split()))
    list_in = [bc[1] if list_in[l] == bc[0] else list_in[l] for l in range(n)]
    print(sum(list_in))

Submission status: Time Limit Exceeded

Solution code:
import numpy

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

arra = numpy.array(a)

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


for j in range(q):
    numpy.place(arra, arra == b[j], c[j])
    print(sum(arra))

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())
    for k, _ in enumerate(A):
        if _ == B[j]:
            A[k] = C[j]
    print(sum(A))

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

for j in range(Q):
    A = [k.replace(L[j][0], L[j][1]) for k in A]
    B = sum(map(int, A))
    print(B)

Submission status: Time Limit Exceeded

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

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:
        left = bisect.bisect_left(a,b)
        right = bisect.bisect_right(a,b)
        if left == right:
            right += 1
        a[left:right] = [c for i in range(right-left)]
    print(sum(a))
    a.sort()

Submission status: Time Limit Exceeded

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

for i in range(Q):
    B, C = list(map(int, input().split()))
    A = A*( (A==B)==False ) + C*(A==B)
    print(A.sum())

Submission status: Time Limit Exceeded

Solution code:
import collections
s=str(input())
s = list(map(int, input().split()))
q = int(input())
x = [list(map(int,input().split())) for i in range(q)]
c = collections.Counter(s)
ans=0
for i in range(q):
    if x[i][0] not in c.keys():
        if ans==0:
            for j in c.keys():
                ans+=j*c[j]
        print(ans)
        continue
    tmp = c[x[i][0]]
    del c[x[i][0]]
    c[x[i][1]] = c[x[i][1]]+tmp
    ans=0
    for j in c.keys():
        ans+=j*c[j]
    print(ans)

Submission status: Time Limit Exceeded

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

listB=[] #appendのために宣言が必要
while True:
    try:
        listB.append(list(map(int,input().split())))

    except:
        break;

for i in range(Q):
  listA.sort()
  for j in range(len(listA)):
    if listA[j]==listB[i][0]:
      listA[j]=listB[i][1]
    elif listA[j]>listB[i][0]:
      break
  #print(listA)
  print(sum(listA))

Submission status: Time Limit Exceeded

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

data = [0] * 100001

def my_sum(d):
    retval = 0

    for i in range(len(d)):
        if d[i] == 0:
            continue
        retval += d[i] * i
    return retval

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

    if data[B] != 0:
        data[C] += data[B]
        data[B] = 0
 
    print(my_sum(data))

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
b, c = map(int, input().split())
BC = [b,c]
for i in range(Q - 1):
    b, c = map(int, input().split())
    BC = np.vstack((BC,[b,c]))

S = np.sum(A)
for i in range(Q):
    num = 0
    swap_mae = BC[i,0]
    swap_go = BC[i,1]
    for j in range(N):
        if A[j] == swap_mae:
            A[j] = swap_go
            num += 1
    S += (swap_go-swap_mae) * num
    print(S)

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)

for B,C in pala:
    res = 0
    if B in count:
      count[C] += count.pop(B)

    for k , v in count.items():
        res += (k * v)
    
    print(res)

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())
    if B not in A:
        print(np.sum(A))
    else:
        A = np.where(A==B, C, A)              
        print(np.sum(A))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A_lst =  list(input().split())
Q = int(input())
BC_lst = []

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
d = defaultdict(int)

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

for el in a:
    d[el] += 1

def s_sum(dd):
    res = 0
    for k,v in dd.items():
        res += k * v
    return res

for ss in bc:
    b = ss[0]
    c = ss[1]

    b_cnt = d[b]
    c_cnt = d[c]
    d[b] = 0
    d[c] += b_cnt
    print(s_sum(d))

Submission status: Time Limit Exceeded

Solution code:

import numpy as np 
N = int(input())
A = [int(i) for i in input().split(" ")]
Q = int(input())
list_n = np.zeros(10**5)
for a in A:
    list_n[a - 1] += 1
list_num = np.array([i for i in range(1, 10**5+1)])
for i in range(Q):
    B, C = map(int, input().split(" "))
    if list_n[B - 1] != 0:
        tmp = list_n[B - 1]
        list_n[C - 1] += tmp
        list_n[B - 1] = 0
    
    print(int(np.sum(np.dot(list_n, list_num))))

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 = list(map(int, input().split()))
    B.append(b)
    C.append(c)

d = {}
for a in A:
    d.setdefault(a, 0)
    d[a] += 1
for b, c in zip(B,C):
    d.setdefault(b, 0)
    d.setdefault(c, 0)
    d[c] += d[b]
    d[b] = 0
    ans = 0
    for i, v in d.items():
        ans += i*v
    print(ans)

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())
    ans=[]
    for _ in range(Q):
        B,C=map(int, input().split())
        cnt=l[B-1]//B
        l[B-1]=0
        l[C-1]+=C*cnt
        ans.append(str(sum(l)))
    print('\n'.join(ans))
    return

if __name__=='__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    import sys
    input = sys.stdin.readline
    from collections import Counter
    N = int(input())
    A = [int(i) for i in input().split()]
    Q = int(input())
    BC = []
    for i in range(Q):
        BC.append(list(map(int, input().split())))
    dic = Counter(A)
    for i in BC:
        B, C = i[0], i[1]
        dic[C] += dic[B]
        dic[B] = 0
        ans = 0
        for k, v in dic.items():
            ans += int(k)*v
        print(ans)

resolve()

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

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

sumnum=sum(t)
for i in range(Q):
    B, C = map(int, input().split())
    num = t[B]//(B)
    t[B] = 0
    t[C] += num*(C)
    sumnum=sumnum-num*B+num*C
    print(sum(t))

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
A=list(map(int,input().split()))
Q=int(input())
anlist=[]
BC=[list(map(int,input().split())) for i in range(Q)]
for i in range(Q):
  if BC[i][0] in A:
    while True:
      A[A.index(BC[i][0])]=BC[i][1]
      if BC[i][0] not in A:
        break
  print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
BC = [tuple(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:
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_new = a
for i in range(q):
  a_new = [c[i] if j == b[i] else j for j in a_new]
  print(sum(a_new))

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)]
for i in range(q):
    j = 0
    while True:
        if a[j] == bc[i][0]:
            a[j] = bc[i][1]
        j += 1
        if n == j:
            break
    print(sum(a))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import collections

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

d = collections.Counter(A)

for i in range(Q):
    B,C = list(map(int, input().split()))
    if B in d:
        val = d[B]
        if C in d:
            d[C] = d[C] + d[B]
        else:
            d[C] = d[B]
        d.pop(B)

    ans = 0
    for k, v in d.items():
        ans += k * v
    
    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,d=map(int,input().split())
  e=a.count(c)
  for i in range(e):
    f=a.index(c)
    a[f]=d
  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

A=sorted(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=sorted(A)
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin
from collections import Counter
N=int(input())
A=list(map(int,input().split()))
D=Counter(A)
E=list(D.keys())
F=list(D.values())
G=[0]*len(E)
for i in range(0,len(D)):
    G[i]=E[i]*F[i]
Q=int(input())
Z=[0]*Q
for i in range(0,Q):
    B,C=list(map(int,input().split()))
    if E.count(B)>0:
        j=E.index(B)
        if E.count(C)>0:
            k=E.index(C)
            G[k]=G[k]+E[k]*F[j]
            F[k]=F[k]+F[j]
            E.pop(j)
            F.pop(j)
            G.pop(j)
        else:
            G[j]=C*F[j]
            E[j]=C
    Z[i]=sum(G)
for i in range(0,Q):
    print(Z[i])

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:
		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:
N=int(input())
A = list(input().split())
Q = int(input())
pairs = [list(input().split()) for i in range(Q)]

for pair in pairs:
#  cnt = 0
#  for j in range(N):
#    if A[j] == pairs[i][0]:
#      A[j] = pairs[i][1]
#    cnt += int(A[j])
  A = [s.replace(pair[0], pair[1]) for s in A]
  print(sum(list(map(int, A))))
#  ret = sum(list(map(int,A)))

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

for op in operations:
    target, goto = op

    a.sort()

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

            a[index] = goto
            index += 1

        print(sum(a))

    except:
        print(sum(a))

    #for i in range(len(a)):
    #    if a[i] == target:
    #        a[i] = goto

    #print(sum(a))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

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

S = sum(A)
for i in range(Q):
  a = A.count(L[i][0])
  S += a*(L[i][1]-L[i][0])
  print(S)
  A = [L[i][1] if j == L[i][0] else j for j in A]

Submission status: Time Limit Exceeded

Solution code:
#import math
#import numpy as np
#import torch
#import torch.nn as nn
#import matplotlib.pyplot as plt
#from decimal import Decimal
#import itertools
import collections

N=int(input())
#N,K = map(int,input().split())
#B,W = map(int,input().split())
#T=int(input())
A = list(map(int,input().split()))
#S=str(input())
#A=[p for p in range(2*10**5)]
Q=int(input())
l=[]
for i in range(Q):
    #print(A)
    B,C = map(int,input().split())

    A=[C if x==B else x for x in 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=list(map(int, input().split()))
  a=[s[1] if j==s[0] else j for j in a]
  print(sum(a))

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

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 i in range(Q):
    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 = sum(l)
for i in range(Q):
    ans += (m[i][1]-m[i][0])*count[i]
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
import math  # gcdもあるよ
import collections
from collections import deque
from collections import defaultdict
from copy import deepcopy
from itertools import accumulate #リストを与えると累積和を返す
def input(): return sys.stdin.readline().rstrip()
from functools import lru_cache #メモ化

def main():
    n = int(sys.stdin.readline())
    a = list(map(int,sys.stdin.readline().split()))
    q = int(sys.stdin.readline())
    queue = [list(map(int,sys.stdin.readline().split())) for _ in range(q)]
    count = collections.Counter(a)
    #print(count)
    #print(list(count))
    for b, c in queue:
        if  b in count:
            if c in count:
                count[c] += count[b]
                del count[b]
            else:
                count[c] = count[b]
                del count[b]
        ans = 0
        for k in count:
            ans += k * count[k]
        print(ans) 
    
    
    return 0

if __name__ == "__main__":
    main()

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

for num, rep in zip(b, c):
    if num in set(a):
        a = [rep if ele == num else ele for ele in a]
        print(sum(a))
    else:
        print(sum(a))
        continue

Submission status: Time Limit Exceeded

Solution code:
import collections
b=[]
c=[]
n=int(input())
a=list(map(int,input().split()))
q=int(input())
d=collections.Counter(a)
for i in range(q):
    x,y=map(int,input().split())
    b.append(x)
    c.append(y)
for i in range(q):
    tmp=d[b[i]]
    d[b[i]]=0
    d[c[i]]+=tmp
    sum=0
    for key,val in d.items():
        sum+=key*val
  
    print(sum)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = input().split()
A = [int(x) for x in A]
Q = int(input())
BC = []
for i in range(Q):
    bc = input().split()
    bc = [int(x) for x in bc]
    BC.append(bc)

for j in range(Q):
    if BC[j][0] in A:
        for k in range(N):
            if A[k] == BC[j][0]:
                A[k] = BC[j][1]
    print(sum(A))

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())
    #print(A)
    for _ in range(q):
        b, c = map(int, input().split())
        A = np.where(A == b, c, A)
        print(np.sum(A))


if __name__ == "__main__":
    main()