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:
def resolve():
    n=int(input())
    a = list(map(int, input().split()))
    ans=sum(a)
    q=int(input())
    a_dict = {}
    for i in set(a):
        a_dict[str(i)] = 0
    for j in a:
        a_dict[str(j)] += 1
    ch=list(a_dict.keys())
    for _ in range(q):
        b,c = map(str, input().split())
        if b in ch:
            d = a_dict[b]
            a_dict[b]=0
            if c in ch:
                a_dict[c] += d
            else:
                a_dict[c] = d
                ch.append(c)
            ans=ans-d*(int(b)-int(c))
            print(ans)
        else:
            print(ans)
resolve()

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
n = int(input())
an = list(map(int, sys.stdin.readline().rstrip().split()))
q = int(input())

import numpy as np

sum = np.sum(an)
ans=[]

for _ in range(q):
    b,c = map(int, input().split())
    for i in range(n):
        if b == an[i]:
            an[i]=c
            sum += c-b
    ans.append(sum)

for q in ans:
    print(q)

Submission status: Time Limit Exceeded

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


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

        try:
            ind=A.index(B)
            A[ind]=C
            #print(A)
        except:
            a=False
    #print(A)
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
import numpy as np
sys.setrecursionlimit(1000000000)


def main():
    input()
    A = np.fromstring(input(), 'int', sep=' ')
    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))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right
from math import gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode

INF = float("inf")

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

def I():
    return int(input())

def MI():
    return map(int,input().split())

def RI():
    return list(map(int,input().split()))

def CI(n):
    return [ int(input()) for _ in range(n) ]

def LI(n):
    return [ list(map(int,input().split())) for _ in range(n) ]

def S():
    return input()

def MS():
    return input().split()

def RS():
    return list(input().split())

def CS(n):
    return [ input() for _ in range(n) ]

def LS(n):
    return [ list(input().split()) for _ in range(n) ]

n = I()
a = RI()
q = I()
bc = LI(q)

for i in range(q):
    b = bc[i][0]
    c = bc[i][1]
    a = [ c if i==b else i for i in a ]
    s = sum(a)
    print(s)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

str1 = input()
A = [int(str1.split(" ")[i]) for i in range(N)]
  
Q = int(input())

for j in range(Q):
  SUM = 0
  str2 = input()
  B, C = int(str2.split(" ")[0]), int(str2.split(" ")[1])
  for i in range(N):
    if A[i] == B:
      A[i] = C
  SUM = sum(A)
  print(SUM)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline
n = int(input())
a = list(map(str, input().strip().split()))
q = int(input())
bc = [map(str, input().split()) for _ in range(q)]
b, c = [list(i) for i in zip(*bc)]
ii = 0

for i in b:
    a = [n.replace(i,c[ii]) for n in a]
    print(sum(list(map(int, a))))
    ii += 1

Submission status: Time Limit Exceeded

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

s = 0
result = ""

r = 1
while r <= q:
  e = list(map(int, input().split()))
  i = 0
  while i < n:
     if(p[i] == e[0]):
        p[i] = e[1]
     s = sum(p)
     i += 1

  r += 1
  result += str(s)+"\n"


print(result.rstrip("\n"))

Submission status: Time Limit Exceeded

Solution code:
n = input()
a = [int(i) for i in input().split()]
q = int(input())
bb = []
cc = []
for i in range(q):
    btmp, ctmp = [int(j) for j in input().split()]
    bb.append(btmp)
    cc.append(ctmp)



atol = sum(a)
for b,c in zip(bb,cc):
    
    count = len([ i for i in a  if i == b])
    a = [ c if b == i else i for i in a ]
    atol +=  (c - b) * count
    print(atol)

Submission status: Time Limit Exceeded

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

for i in range(q):
  b, c = map(str, input().split())
  num = ",".join(a)
  num = num.replace(b, c)
  a = num.split(",")
  ans = map(int, a)
  print(sum(ans))

Submission status: Time Limit Exceeded

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

a =""
for i in range(N-1):
  a += A[i]+"." 
a += A[N-1]

for i in BC:
  B = str(i[0])
  C = str(i[1])
  if B in a:
    a = a.replace(B,C)
  b = a
  print(sum(list(map(int, b.split(".")))))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
lsn = list(map(int,input().split()))
Q = int(input())
ls2 = []
for i in range(Q):
    Bi,Ci = map(int,input().split())
    ls2.append([Bi,Ci])
for l in ls2:
    lsn = [l[1] if i == l[0] else i for i in lsn]
    print(sum(lsn))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
Query = [tuple(map(int, input().split())) for _ in range(Q)]
from collections import Counter
cntr = Counter(A)
keys = list(cntr.keys())
for b, c in Query:
    cntr[c] += cntr[b]
    cntr[b] = 0
    ans = 0
    for k, v in cntr.items():
        ans += k * v
    print(ans)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

for B,C in pala:
    res = 0
    for i in range(len(data)):
        if data[i] == B:
            data[i] = C
        res += data[i]
    print(res)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
a = list(map(int,input().split()))
ans = sum(a)
#print(ans)
q = int(input())
b = []
c = []
from itertools import groupby
d = [[key,len(list(group))] for key,group in groupby(sorted(a))]

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

Submission status: Time Limit Exceeded

Solution code:
def getCalc(AAA, BBB):
    sum = 0
    for i in range(len(AAA)):
        sum += AAA[i] * BBB[i]
    return sum


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

total = sum(A)

AAA = []
BBB = []

for i in range(10 ** 5 + 1):
    count = A.count(i)
    if (count > 0):
        AAA.append(i)
        BBB.append(count)

for i in range(Q):
    if (B[i] in AAA):
        AAA = [C[i] if x == B[i] else x for x in AAA]
    print(getCalc(AAA, BBB))

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())
BC=[]
for i in range(Q):
    BC.append(list(map(int, input().split())))
BC=np.array(BC)

for i in range(Q):
    if BC[i,0] not in A:
        pass
    else:
        for j in range(len(A)):
            if A[j]==BC[i,0]:
                A[j]=BC[i,1]
    print(np.sum(A))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [int(x) for x in input().split()]
Q = int(input())
ans = []
for x in range(Q):
    B, C = [int(x) for x in input().split()]
    N = A.count(B)
    A = list(filter(lambda x: x != B, A))
    A.extend([C] * N)
    ans.append(sum(A))
for x in ans:
    print(x)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
lst = []
for _ in range(Q):
    a,b = map(int,input().split())
    lst.append([a,b])
#print(A)
#print(lst)

#rep_lst = [s.replace('1','2') for s in A]

#print(rep_lst)

for i in range(Q):
    A = [lst[i][1] if j == lst[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()]
sa  = sorted(a)

q = int(input())
b = []
for _ in range(q):
    b.append([int(i) for i in input().split()])


for i in range(q):
    idx = -1
    seta = set(sa)
    if b[i][0] in seta:
         idx = sa.index(b[i][0])
    # print(idx)

    if idx != -1:
        while (True):
            if idx < n and sa[idx] == b[i][0]:
                sa[idx] = b[i][1]
                idx += 1
            else:
                break
    # print(sa)
    print(sum(sa))

Submission status: Time Limit Exceeded

Solution code:
import collections

def calc_sum(c):
    sum_val = 0
    for key, val in c.items():
        sum_val += key * val
    return sum_val

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

actions = []

for i in range(Q):
    B, C = map(int, input().split())
    actions.append({'B':B, 'C':C})

c = collections.Counter(arr)

for i in range(Q):
    B = actions[i]['B']
    C = actions[i]['C']
    if B in c:
        c[C] += c[B]
        c.pop(B)
    print(calc_sum(c))

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 i, j in zip(b, c):
  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:
from collections import Counter

N = int(input())
a = Counter(map(int, input().split()))
Q = int(input())

for i in range(Q):
    b, c = map(int, input().split())
    a[c] += a[b]
    a[b] = 0
    #print(sum([x*y for x, y in a.items()]))
    print(sum(a.elements()))

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


ans = sum(a)
for i in range(q):
  dif = c[i] - b[i]
  ans += dif * a.count(b[i])
  a = [c[i] if j == b[i] else j for j in a]
  print(ans)

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

n = int(input())
a = list(map(int, input().split()))
a_dic = defaultdict(int)
for i in range(n):
    a_dic[a[i]] += 1

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

    a_dic[c] += a_dic[b]
    a_dic[b] = 0
    a_sum = 0
    for k, v in a_dic.items():
        a_sum += k * v

    print(a_sum)

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
import collections

N = int(input())
A = list(map(int, input().split()))
C = collections.Counter(A)
Q = int(input())
X = [[] for _ in range(Q)]
for i in range(Q):
    X[i] = list(map(int, input().split()))

for i in range(Q):
    b, c = X[i]
    for j in range(C[b]):
        A.remove(b)
        A.append(c)
    C = collections.Counter(A)
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

# 実行環境(0:vscode, 1:atcoder)
MODE = 1

# 入力の次元
DIMENSION = 2

# int型に変換
INT_TYPE = 1

if not (MODE):
    with open("input.txt", "r") as f:
        s = f.read()
else:
    s = sys.stdin.read()

if DIMENSION == 0:
    if INT_TYPE == 1:
        s = int(s)
elif DIMENSION == 1:
    if INT_TYPE == 0:
        s = s.split()
    elif INT_TYPE == 1:
        s = [int(x) for x in s.split()]
elif DIMENSION == 2:
    if INT_TYPE == 0:
        s = [x.split() for x in s.splitlines()]
    elif INT_TYPE == 1:
        s = [[int(y) for y in x.split()] for x in s.splitlines()]

N = s[0][0]
A = np.array(s[1])
Q = s[2][0]
BC = np.array(s[3:])
B = BC[:, 0]
C = BC[:, 1]

A_sum = np.sum(A)

D = np.array([np.count_nonzero(A == i) for i in range(100001)])
for i in range(Q):
    b = B[i]
    c = C[i]
    A_sum += D[b] * (c - b)
    print(A_sum)
    D[c] += D[b]
    D[b] = 0

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):
	if  b[i] in a:

		ind = []
		ind  = [j for j, x in enumerate(a) if x == b[i]]
		l = len(ind)

		for k in range(l):
			a[ind[k]] = c[i]
		print(sum(a))

	else:
		print(sum(a))
	"""
	for j in range(n):
		if a[j] ==b[i]:
			a[j] = c[i]
	"""

Submission status: Time Limit Exceeded

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

for i in range(Q):
    a,b=input().split()
    list.append((int(a), int(b)))
#print(list[1][1])
for i in range(Q):
  for j in range(N):
      if  A[j] == list[i][0]:
        A[j] = list[i][1]
  print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
la = list(map(int, input().split()))
q = int(input())
sa = sum(la)
lc = []
for i in range(q):
  b, c = map(int, input().split())
  cnt1 = la.count(b)
  cnt2 = lc.count(b)
  sa += (c-b)*(cnt1+cnt2)  
  print(sa)
  
  lc += [c]*cnt1

Submission status: Time Limit Exceeded

Solution code:
import bisect

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())
a_li = sorted(a_li)

for i in range(q):
    b,c = map(int,input().split())
    indexes = func2(a_li, b)
    for i in indexes:
        a_li[i] = c
    print(sum(a_li))

Submission status: Time Limit Exceeded

Solution code:

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

from collections import Counter
co = list(Counter(A).items())
co = [list(_) for _ in co]
#print(co)
num = len(co)

total = sum(A)
for i in range(q):
    b, c = map(int,input().split())
    for j in range(num):
        if co[j][0] == b:
            total -= (co[j][0] * co[j][1])
            co[j][0] = c
            total += (co[j][0] * co[j][1])
    print(total)

Submission status: Time Limit Exceeded

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

for i in range(q):
  b, c = map(int, input().split())
  cnt = 0
  for j in range(len(a)):
    if a[j] == b:
      a[j] = c
      cnt += 1
  x += (c - b) * cnt
  print(x)

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] += dis[B]
      del dis[B]
    else:
      dis[C] = dis[B]
      del dis[B]
    res += n*(C-B)
  print(res)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

ans = 0

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

uniqA, counts = np.unique(npA, return_counts=True)
ans = np.sum(npA)

Q=int(input())

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

	if B in uniqA:
		srcIndex = np.where(uniqA == B)[0]
		srcCount = int(counts[srcIndex])
		diff = ( C - int(uniqA[srcIndex]) ) * srcCount
		counts[srcIndex] = 0
		if C in uniqA:
			counts[np.where(uniqA == C)[0]] += srcCount
		else:
			uniqA = np.append(uniqA, C)
			counts = np.append(counts, srcCount)

	ans += diff
	print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
A.sort()
tmp_sum = sum(A)
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)
        A[left:right] = [c] * (right-left)
        A.sort()
        tmp_sum = tmp_sum + c *(right-left) - b * (right - left)
        print(tmp_sum)
    else:
        print(tmp_sum)

Submission status: Time Limit Exceeded

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

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

    for j in range(0, len(b_l)):
        for i in range(0, len(a)):
            if b_l[j] == a[i]:
                a.pop(i)
                a.insert(i,c_l[j])
        print(sum(a))
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):
    B,C = (int(x) for x in input().split())

    for j in range(N):

        try:
            idx = A.index(B)
            if(idx>-1):
                #if A[j]==B:
                #    A[j]=C
                A[idx]=C
        except ValueError:
            break
    
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
from collections import Counter

def resolve():
  N = int(input())
  A = [int(x) for x in input().split(" ")]
  Q = int(input())

  countA = Counter(A)

  for _ in range(Q):
    B, C = map(int, input().split(" "))
    if B in countA.keys():
      countA[C] += countA.pop(B)
    sum_A = 0
    for a in countA.items():
      sum_A += a[0]*a[1]
    print(sum_A)

if __name__ == "__main__":
  resolve()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n=int(input())
a=np.array(list(map(int,input().split())))
q=int(input())
b=[]
c=[]
for i in range(q):
    b1,c1=np.array(list(map(int,input().split())))
    b.append(b1)
    c.append(c1)

for i in range(q):
    for j,k in enumerate(a):
        if b[i]==k:
            a[j]=c[i]
    sum=np.sum(a)
    print(sum)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
A = list(map(int,input().split()))
s = sum(A)
Q = int(input())
for _ in range(Q):
    B,C = map(int,input().split())
    if B in A:
        c = A.count(B)
        A = [C if i == B else i for i in A]
        s = s-((B-C)*c)

    print (s)

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())
a_sum= np.sum(a)

for i in range(q):
  b,c=map(int, input().split())
  count=np.count_nonzero(a==b)
  a[a==b]=c
  a_sum += count*(c-b)
  print(a_sum)

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
N=int(input())
z=input()
a=z.split()
A=[]
B=[]
C=[]
for i in range(N):
    A.append(int(a[i]))
Q=int(input())
for j in range(Q):
    d=input()
    D=d.split()
    B.append(int(D[0]))
    C.append(int(D[1]))
A.sort()
for j in range(Q):
    k=0
    while A[k]<=B[j]:
        if A[k]==B[j]:
            A[k]=C[j]
        k+=1
        if k==N:
            break
    A.sort()
    print(sum(A))

Submission status: Time Limit Exceeded

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

Q = int(input())
for j in range(Q):
    BC= list(input().split())
    A = [int(BC[1]) if i == int(BC[0]) else i for i in A]
    print(sum(A))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())

A_in = input()
    
Q = int(input())

for i in range(Q):
    B, C = map(str, input().split())
    
    A_in = A_in.replace(B, C)
    
    #A_val = []
    #for i in A_in.split():
    #    A_val.append(int(i))
    #
    #print(sum(A_val))
     
    S = 0
    for i in A_in.split():
        S += int(i)
    print(S)

Submission status: Time Limit Exceeded

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

        ans = []

        temp_s = A

        for i in range(Q):
                before = str(BC[i][0])
                if before not in temp_s:
                        pass
                else:
                        temp_s = [s.replace(before,str(BC[i][1])) for s in temp_s]
                temp_i = [int(s) for s in temp_s]
                ans.append(sum(temp_i))

        return ans

if __name__=="__main__":
        ans = main()

        n = len(ans)
        for i in range(n):
                print(ans[i])

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    n = int(input())
    A = list(map(int, input().split()))
    q = int(input())
    S = sum(A)

    for _ in range(q):
        b, c = map(int, input().split())
        k = A.count(b)
        A = [c if a == b else a for a in A]
        S += k * (c - b)
        print(S)

resolve()

Submission status: Time Limit Exceeded

Solution code:
import sys

def retList(target, A):
  split = target.split()
  ret = []
  for j, v in enumerate(A):
    #print(j, v, split[0], split[1])
    if v == int(split[0]):
      #print("変換")
      v = int(split[1])
    ret.append(v)
  return ret

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

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

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

B = sys.stdin.readlines()
C = [b.strip() for b in B]
#print(C)

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

Submission status: Time Limit Exceeded

Solution code:
import bisect

n = int(input())
an_list = list(map(int, input().split()))
an_list = sorted(an_list)

q = int(input())
for _ in range(q):
    b, c = map(int, input().split())
    index_r = bisect.bisect_right(an_list, b)
    index_l = bisect.bisect_left(an_list, b)
    an_list[index_l:index_r] = [c for x in range(len(an_list[index_l:index_r]))]
    print(sum(an_list))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
l=list(map(int,input().split()))
q=int(input())
dic=dict()
list_sum=sum(l)
for i in range(len(l)):
    if(l[i] not in dic.keys()):
        dic[l[i]]=1
    else:
        dic[l[i]]+=1
# print(dic)

for i in range(q):
    s=0
    b,c=map(int,input().split())
    if(b in dic.keys() and dic[b]!=0):
        # s=(c-b)*dic[b]+list_sum
        if(c in dic.keys()):
            dic[c]+=dic[b]
            dic[b]=0
        else:
            dic[c]=dic[b]
            dic[b]=0
    for x in dic:
        if(dic[x]!=0):
            s+=x*dic[x]
    print(s)

Submission status: Time Limit Exceeded

Solution code:
#d
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 i in range(Q):
    for j in range(A.count(B[i])):
        youso=A.index(B[i])
        A[youso]=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())))
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)
  ans= ans+sa
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

b = []
c = []
ret = []

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

    ll = set(a)
    if b[i] in ll:
        cnt = a.count(b[i])
        for x in range(cnt):
            idx = a.index(b[i])
            a[idx] = c[i]
    ret += [str(sum(a))]

print('\n'.join(ret))

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 n, j in enumerate(a):
		if j == b:
			a[n] = 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 = [A.count(i) for i in range(1, 100001)]
for change in changes:
    num[change[1] - 1] += num[change[0] - 1]
    num[change[0] - 1] = 0
    s = sum([(i + 1) * num[i] for i in range(100000)])
    print(s)

Submission status: Time Limit Exceeded

Solution code:
import sys

def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))

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

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

Submission status: Time Limit Exceeded

Solution code:
import collections

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

cc = collections.Counter(a)
c_buf = 0
cc_j_buf = 0
for i in range(q):
  flag = 0
  b = b_c[i][0]
  c = b_c[i][1]
  count = 0
  for j in cc:
    if j == b:
      if c in cc:
        cc[c] = cc[c] + cc[j]
      else:
        cc_j_buf = cc[j]
        flag = 1
      cc[j] = 0
  if flag == 1:
    cc[c] = cc_j_buf
  for j in cc:
    count = count + j*cc[j]
  print(count)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())
A = np.array(list(map(int, input().split())))
Q = int(input())
B = [0]*Q
C = [0]*Q
for i in range(Q):
    B[i], C[i] = map(int, input().split())
    
    A = np.sort(A)
    for k in range(N):
        if A[k] == B[i]:
            A[k] = C[i]
        elif A[k] > B[i]:
            break

    print(np.sum(A))

Submission status: Time Limit Exceeded

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


for q in range(Q):
    b, c = map(int, input().split())
    for n in range(N):
        if b == A[n]:
            A[n] = c
    print(sum(A))

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

def calc(A):
    ans = 0
    for i in range(len(A)):
        ans += A[i] * (i + 1)

    return ans

VALUE = [0 for i in range(100000)]

for i in range(N):
    VALUE[A[i] - 1] += 1

for i in range(Q):
    VALUE[BC[i][1] - 1] += VALUE[BC[i][0] - 1]
    VALUE[BC[i][0] - 1] = 0
    print(calc(VALUE))

Submission status: Time Limit Exceeded

Solution code:
N = input()
AT = input()
Q = input()
BT = []

N = int(N)
A = AT.split(" ")
Q = int(Q)

for i in range(N):
    A[i] = int(A[i])

sum = 0
out = []

for i in range(Q):
    X = input()
    B = X.split(" ")
    B[0] = int(B[0])
    B[1] = int(B[1])

    for j in range(N):
        if A[j] == B[0]:
            A[j] = B[1]
        sum = sum + A[j]
    out.append(sum)
    sum = 0

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