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: Accepted

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

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

ans = sum(a)

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

Submission status: Accepted

Solution code:
from collections import Counter

from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))

n=int(input())
a=lnii()

count=Counter(a)
ans=0
for k,v in count.items():
  ans+=k*v

q=int(input())
for i in range(q):
  b,c=nii()

  b_cnt=count[b]

  if b_cnt!=0:
    count[b]=0
    if c in count:
      count[c]+=b_cnt
    else:
      count[c]=b_cnt

  ans=ans-(b*b_cnt)+(c*b_cnt)
  print(ans)

Submission status: Accepted

Solution code:
(n,), aa, (q,), *bc = [list(map(int, l.split())) for l in open(0)]

from collections import defaultdict, Counter

d = defaultdict(int)
rd = defaultdict(set)

co = Counter(aa)

ans = sum([x*y for x, y in co.items()])

for b, c in bc:
    co[c] += co[b]
    ans += co[b]*(c-b)
    del co[b]
    print(ans)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = list(map(int,input().split()))
    Q = int(input())
    B = [0 for i in range(Q)]
    C = [0 for i in range(Q)]
    
    A_num = [0 for i in range(10**5+1)]
    ans = 0
    for a in A:
        ans += a
        A_num[a] += 1
    
    for q in range(Q):
        b,c = map(int,input().split())
        if A_num[b] != 0:
            ans += (c-b)*A_num[b]
            A_num[c] += A_num[b]
            A_num[b] = 0
            
        print(ans)
    
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def change_dict_key(D, old_key, new_key, default_value=None):
  if new_key not in D:
    D[new_key] = D.pop(old_key, default_value)
  else:
    D[new_key] += D.pop(old_key, default_value)

n=int(input())
A=list(map(int,input().split()))+[100001]
q=int(input())
BC=[list(map(int,input().split())) for _ in range(q)]
ans,pre,count=sum(A)-A[n],A[0],0
D=dict()

A.sort()
for a in A:
  if pre != a:
    D[pre]=count
    count,pre=1,a
    continue
  count += 1

for b,c in BC:
  if b not in D:
    print(ans)
    continue
  num = D[b]
  change_dict_key(D,b,c)
  ans += num*(c-b)
  print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import Counter
input = sys.stdin.readline
sys.setrecursionlimit(2 * 10**6)


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


def main():
    N = int(input())
    A = inpl()
    Q = int(input())
    BC = [inpl() for _ in range(Q)]
    cA = Counter(A)

    sum_p = sum(k * v for k, v in cA.items())

    for b, c in BC:
        if b not in cA:
            print(sum_p)
            continue
        t_value = cA.pop(b)
        sum_p -= t_value * b
        if c in cA:
            cA[c] += t_value
        else:
            cA[c] = t_value
        sum_p += t_value * c
        print(sum_p)

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

for a in range(len(A)):
    dp[A[a]] += 1
s = sum(A)

for q in range(Q):
    B, C = map(int,input().split())
    dp[C] += dp[B]
    s +=(C-B)*dp[B] 
    dp[B] = 0
    print(s)

Submission status: Accepted

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

summ = sum(a)
cc = collections.Counter(a)
for i in range(q):
  b = b_c[i][0]
  c = b_c[i][1]
  if b in cc:
    buf = cc[b]
    cc[b] = 0
    if c in cc:
      cc[c] = cc[c] + buf
    else:
      cc[c] = buf
    summ = summ - b*buf + c*buf
    print(summ)
  else:
    print(summ)

Submission status: Accepted

Solution code:
import collections


if __name__ == '__main__':
    n = int(input())
    a = [int(i) for i in input().split()]
    q = int(input())
    key = [i for i in range(10**5+1)]
    val = [0]*(10**5+1)
    dict = dict(zip(key,val))
    dict.update(collections.Counter(a))
    ans = sum(a)

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

Submission status: Accepted

Solution code:
n = int(input())

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

q = int(input())

b = [0] * q
c = [0] * q
cnt = [0] * 100001

for i in range(len(a)):
    cnt[a[i]] += 1
s = sum(a)
for i in range(q):
    b[i], c[i] = map(int, input().split())

for i in range(q):
    s = s + ((c[i]-b[i])*cnt[b[i]])
    cnt[c[i]] += cnt[b[i]]
    cnt[b[i]] = 0
    print(s)

Submission status: Accepted

Solution code:
import sys
import numpy as np
from collections import Counter

# 実行環境(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 = Counter(A)

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: Accepted

Solution code:
from collections import Counter

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

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

d = Counter(A)

sub_s = sum(A)

for b, c in BC:
    sub_s += d[b] * (c - b)
    d[c] += d[b]
    d[b] = 0

    print(sub_s)

Submission status: Accepted

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

Aset = set(A)
lst = {}
for i in Aset:
    lst[i] = 0
    
for i in range(N):
    lst[A[i]] += 1

Q = int(input())

# 最初の全てのA_iの和
ans_init = 0
for i in lst:
    ans_init += i*lst[i]

# 初期値からのプラスマイナス分
ans_pm = 0
ans = []
for i in range(Q):
    B, C = map(int, input().split())
    if B in lst:
        # 更新する前に、lst中のkeyがBの個数をBnumに記憶しておく。
        Bnum = lst[B]
        # lstを更新
        if C in lst:
            lst[C] += lst[B]
            lst.pop(B)
        else:
            lst[C] = lst[B]
            lst.pop(B)
    
        # 初期値からの増減分をここで算出。
        ans_pm += Bnum*(C-B)
        ans.append(ans_init + ans_pm)
        
    else:
        ans.append(ans_init + ans_pm)

for i in ans:
    print(i)

Submission status: Accepted

Solution code:
import collections

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

Q = int(input())

A_counter = collections.Counter(A)

sumA = sum(A)

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

    #Bの個数をカウントする。もし0なら0
    if A_counter[B] == 0:
        print(sumA)
    else:
        sumA =sumA - (B * A_counter[B])
        sumA = sumA + (C * A_counter[B])
        print(sumA)
        A_counter[C] = A_counter[B] + A_counter[C]  
        A_counter[B] = 0

Submission status: Accepted

Solution code:
from collections import Counter


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

for i in range(1, q+1):
    b, c = map(int, input().split())
    x = c - b
    s[i] = s[i-1] + x*counter[b]
    counter[c] += counter[b]
    counter[b] = 0

for i in range(1, q+1):
    print(s[i])

Submission status: Accepted

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

list=[0]*100001
sum=sum(A)
for i in A:
    list[i]+=1

for bc in BC:
    x=list[bc[0]]
    sum+=(bc[1]-bc[0])*x
    print(sum)
    list[bc[0]]-=x
    list[bc[1]]+=x

Submission status: Accepted

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


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

s = sum(A)

CNT = [0] * (10**5 + 1)
for a in A:
    CNT[a] += 1

q = int(input())
for _ in range(q):
    b, c = map(int, input().split())
    s += (c - b) * CNT[b]
    CNT[c] += CNT[b]; CNT[b] = 0
    print(s)

Submission status: Accepted

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n = ni()
a = na()
q = ni()
l = [na() for _ in range(q)]

import collections

c = collections.Counter(a)
ans = sum(a)
for i in l:
  if c[i[0]] >0:
    ans = ans - c[i[0]]*i[0] + i[1]*(c[i[0]])
    c[i[1]] = c[i[1]] + c[i[0]]
    c[i[0]] = 0
    print(ans)
  else:
    print(ans)

Submission status: Accepted

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

for i in range(q):
    s += (c[i]-b[i])*d[b[i]]
    d[c[i]] += d[b[i]]
    d[b[i]] = 0
    print(s)

Submission status: Accepted

Solution code:
import collections
N = int(input())
A = list(map(int, input().split()))
c = collections.Counter(A)
tot = sum(A)
Q = int(input())
for i in range(Q):
    f, t = map(int, input().split())
    dis = t - f
    num = c[f]
    tot += num * dis
    print(tot)
    c[f] = 0
    if t in c:
        c[t] = c[t] + num
    else:
        c[t] = num

Submission status: Accepted

Solution code:
from collections import Counter
dicy = {}
def swap(a,b):
	tmp = 0
	try:
		tmp = dicy.pop(a)
	except Exception:
		tmp = 0

	try:
		dicy[b] += tmp
	except Exception:
		dicy[b] = tmp

	return (int(b)-int(a)) * tmp
  

max = input()
dicy = dict(Counter(input().split(' ')))
result = 0
for v,k in dicy.items():
	result += int(v)*int(k)
num_oper = int(input())
for i in range(num_oper):
	a,b = input().split(' ')
	diff = swap(a,b)
	result += diff
	print(result)

Submission status: Accepted

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

q = int(input())

A = {}
a = 0
for i in L:
    a += i
    if i in A:
        A[i] = A[i] +1
    else:
        A[i] = 1

#print(A)
#print(a)
for i in range(q):
    b,c = map(int,input().split())
    #print(L2)
    if b in A:
        a = a - A[b]*b
        a = a + A[b]*c
        
        if c in A:
            A[c] = A[c] + A[b]
        else:
            A[c] = A[b]
        A.pop(b)
    print(a)

Submission status: Accepted

Solution code:
from collections import defaultdict
def main():
    N = int(input())
    A = [int(a) for a in input().split()]
    Q = int(input())
    Query = list()

    for q in range(Q):
        B, C = map(int, input().split())
        Query.append([B, C])

    elem = defaultdict(int)
    s = 0

    for a in A:
        elem[a] += 1
        s += a

    for q in Query:
        B, C =  q

        if B in elem.keys():
            # Bの数
            nB = elem[B]

            # Cが存在するならBの数分、Cを増やす
            if C in elem.keys():
                elem[B] = 0
                elem[C] += nB
              
                s = s - B * nB + C * nB
                print(s) 
            else:
                elem[B] = 0
                elem[C] = nB
                
                s = s - B * nB + C * nB
                print(s)
            
        else:
            print(s)
           
if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

D=dict()

for a in A:
    if a not in D:
        D[a]=1
    else:
        D[a]+=1
S=sum(A)

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

    if B in D:
        #print(S)
        S-=D[B]*B
        #print(S)
        S+=D[B]*C
        #print(S)
        
        if C in D:
            D[C]+=D[B]
        else:
            D[C]=D[B]

        del D[B]

    print(S)

Submission status: Accepted

Solution code:
def solve():
	N = int(input())
	arr = list(map(int, input().split()))
	summ = sum(arr)
	freq = dict()
	for x in arr:
		freq[x] = freq.get(x, 0) + 1
	Q = int(input())
	for _ in range(Q):
		B, C = map(int, input().split())
		Bfreq = freq.get(B, 0)
		summ -= B * Bfreq
		summ += C * Bfreq
		freq[C] = freq.get(C, 0) + Bfreq
		if (B in freq):
			freq.pop(B)
		print(summ)


def main():
	# for _ in range(int(input())):
	solve()


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
from collections import defaultdict

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
Counter = defaultdict(int)
for a in A:
    Counter[a] += 1
sum_val = sum(A)
ans = []
for _ in range(Q):
    B, C = map(int, input().split())
    sum_val += (C - B) * Counter[B]
    Counter[C] += Counter[B]
    Counter[B] = 0
    ans.append(sum_val)
print(*ans, sep='\n')

Submission status: Accepted

Solution code:
import numpy as np

N = int(input())
A = np.fromstring(input(), sep=" ", dtype=np.int64)
Q = int(input())
B = np.zeros(Q)
C = np.zeros(Q)
D = np.fromstring(" ".join([input() for q in range(Q)]), sep=" ", dtype=np.int64).reshape((Q, 2))
B = D[:, 0]
C = D[:, 1]

d = dict(np.c_[np.unique(A, return_counts=True)])
s = np.sum(A)
for q in range(Q):
    if(B[q] in d):
        n = d.pop(B[q])
        s += n * (C[q] - B[q])
        if(C[q] in d):
            d[C[q]] += n
        else:
            d[C[q]] = n
    print(s)

Submission status: Accepted

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

from collections import Counter

counter = Counter(A)
ans = sum([key*value for key, value in counter.items()])

for q in range(Q):
  ans = ans+((BC[q][1]-BC[q][0])*counter[BC[q][0]])
  counter[BC[q][1]] += counter[BC[q][0]]
  counter[BC[q][0]] = 0
  print (ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
mp, ans = {}, 0
for i in range(n):
    if(a[i] in mp.keys()):
        mp[a[i]] += 1
    else:
        mp[a[i]] = 1
for k in mp.keys():
    ans += k * mp[k]
q = int(input())
for i in range(q):
    b, c = map(int, input().split())
    if(b not in mp.keys()):
        mp[b] = 0
        print(ans)
        continue
    if(c in mp.keys()):
        mp[c] += mp[b]
    else:
        mp[c] = mp[b]
    ans += (c-b) * mp[b]
    mp[b] = 0
    print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import collections

num = int(input())
a_i = list(map(int, input().split()))
q = int(input())
c = collections.Counter(a_i)
ans = sum(a_i)

for x in range(q):
    a, b = map(int, input().split())
    val = b - a
    cnt = c[a]
    c[a] -= cnt
    c[b] += cnt
    ans += val * cnt
    print(ans)

Submission status: Accepted

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
whole=sum(answers)
for number in numbers:
    suuji=answers[number[0]]//number[0]
    answers[number[0]]=0
    answers[number[1]]+=suuji*number[1]
    whole+=(number[1]-number[0])*suuji
    print(whole)

Submission status: Accepted

Solution code:
N = int(input())
l = [0]*(10**5+1)
A = [j for j in map(int, input().split())]
for i in A:
    l[i] += 1

Q = int(input())

BC = []
ans = sum(A)

for i in range(Q):
    B, C = map(int, input().split())
    BC.append([B, C])
for i in BC:
    B = i[0]
    C = i[1]
    ans += l[B]*(C-B)
    l[C] += l[B]
    l[B] = 0
    print(ans)

# print(N)
# print(A)
# print(Q)
# print(BC)

Submission status: Accepted

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 += [b]
    C += [c]
s = set()
d = {}
for i in range(N):
    if A[i] not in d:
        d[A[i]] = 1
        s.add(A[i])
    else:
        d[A[i]] += 1

result = sum(A)
for i in range(len(B)):
    if B[i] in s:
        result -= B[i]*d[B[i]]
        result += C[i]*d[B[i]]
        if C[i] not in d:
            d[C[i]] = d[B[i]]
        else:
            d[C[i]] += d[B[i]]
        s.add(C[i])
        s.remove(B[i])
        del d[B[i]]
    print(result)

Submission status: Accepted

Solution code:
n = int(input())
A = {}
a = list(map(int,input().split()))
for i in a:
    if not i in A:
        A[i] = 1
    else:
        A[i] += 1

s = 0
for k,v in A.items():
    s += k*v

Q = int(input())
for _ in range(Q):
    b,c = map(int,input().split())
    if b in A:
        s = s-(b-c)*A[b]
        if not c in A:
            A[c] = A[b]
        else:
            A[c] += A[b]
        A[b] = 0

    print (s)

Submission status: Accepted

Solution code:
import sys
import collections
def main():
    n = int(input())
    a = collections.Counter(list(map(int, input().split())))
    s = [0 for i in range(10**5+1)]
    sa = 0
    for i in a:
        s[i] += a[i]
        sa += i*a[i]
    q = int(input())
    for x in sys.stdin.readlines():
        b, c = map(int, x.split())
        s[c] += s[b]
        sa = sa + c*s[b] - b*s[b]
        s[b] = 0
        print(sa)

main()

Submission status: Accepted

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

    self.__sum = 0
    for k, v in self.__b.items():
      self.__sum += k * v    

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

      self.__sum += (c - b) * self.__b[b]

      self.__b[b] = 0

  def sum(self):
    return self.__sum

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

Submission status: Accepted

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

mydict = {}
for i in A:
    if i in mydict:
        score = mydict[i]
        mydict[i] = score + 1
    else:
        mydict[i] = 1


count = 0
for k, v in mydict.items():
    count = count + k*v
    
for i in range(Q):
    if b[i] in mydict:
        if c[i] in mydict:
            score1 = mydict[b[i]]
            score2 = mydict[c[i]]
            
            count1 = score1* b[i]
            count2 = score1* c[i]
            del mydict[b[i]]
            mydict[c[i]] = score1 + score2
            count = count - count1 + count2

            
        else:
            count = count - b[i] * mydict[b[i]] + c[i] * mydict[b[i]]
            mydict[c[i]] = mydict[b[i]]
            del mydict[b[i]]
            

    
    print(count)

Submission status: Accepted

Solution code:
import collections
n=int(input())
a=input()
a=a.split()
a=[int(n) for n in a]
q=int(input())
al=collections.Counter(a)
s=sum(a)
for i in range (q):
    x=input()
    x0=x.split()
    b=int(x0[0])
    c=int(x0[1])
    r=al[b]*(c-b)
    s=s+r
    print(s)
    al[c]=al[c]+al[b]
    al[b]=0

Submission status: Accepted

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)]
dic_A=dict()
sum_A=sum(A)
ans=list()
tmp=0
for i in A:
    if i in dic_A:
        dic_A[i]+=1
    else:
        dic_A[i]=1
for j in range(Q):
    if B[j][0] in dic_A:
        tmp=sum_A+ dic_A[B[j][0]]*(B[j][1]-B[j][0])
        ans.append(tmp)
        sum_A=tmp
        if B[j][1] not in dic_A:
            dic_A[B[j][1]]=dic_A[B[j][0]]
        else:
            dic_A[B[j][1]]+=dic_A[B[j][0]]
        dic_A[B[j][0]]=0
    else:
        if tmp==0:
            ans.append(sum_A)
        else:
            ans.append(tmp)
for k in ans:
    print(k)

Submission status: Accepted

Solution code:
import collections
N = int(input())
A_list = list(map(int, input().split()))
c = collections.Counter(A_list)
result = sum(A_list)
Q = int(input())

for _ in range(Q):
    B,C = map(int,input().split())
    result += (C-B) * c[B]
    c[C] += c[B]
    c[B] = 0
    print(result)

Submission status: Accepted

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

# print(n,q)
# print(A)
# print(BC)
C = {}
for a in A:
    if a in C:
        C[a]+=1
    else:
        C[a]=1

s = sum(A)
# print(a)
for b,c in BC:
    # print(b,c)
    d = c-b
    if not b in C:
        C[b] = 0
    s += d*C[b]
    if not c in C:
        C[c] = 0
    C[c] += C[b]
    C[b] = 0
    print(s)

Submission status: Accepted

Solution code:
from collections import Counter
import sys

input = sys.stdin.readline


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

    d = Counter(A)
    # print(d)
    ans = sum(A)

    for i in range(Q):
        b, c = map(int, input().split())
        if d[b] != 0:
            ans -= d[b] * b
            ans -= d[c] * c
            d[c] += d[b]
            d[b] = 0
            ans += d[c] * c

        print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import math
import collections
import decimal
import itertools
from collections import deque
from functools import reduce
import heapq
n = int(input())
#n, k = map(int, sys.stdin.readline().split())
#s = input()
a = list(map(int, sys.stdin.readline().split()))

q = int(input())
l = [0 for i in range(10 ** 5 + 2)]
for i in range(n):
    l[a[i]] += 1

ans = sum(a)
for i in range(q):
    b, c = map(int, sys.stdin.readline().split())
    ans += (c-b) * l[b]
    l[c] += l[b]
    l[b] = 0
    print(ans)

Submission status: Accepted

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

for i in range (q):
    bc.append(list(map(int, input().split())))
num=[0]*(10**5+1)
for i in range(n):
    x=a[i]
    num[x]+=1

kk=0
for l in range(10**5+1):
    kk+=l*num[l]

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

Submission status: Accepted

Solution code:

def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [input().split() for _ in range(n)]
def s4(n):return [[x for x in s] for s in s2(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]
def t3(n):return [tuple(int(x) for x in input().split()) for _ in range(n)]
def p0(b,yes="Yes",no="No"): print(yes if b else no)
# from sys import setrecursionlimit
# setrecursionlimit(1000000)
from collections import Counter,deque,defaultdict
# import itertools
# import math
# import networkx as nx
# from bisect import bisect_left,bisect_right
# from heapq import heapify,heappush,heappop
n=n0()
A=n1()
Q=n0()
BC=n3(Q)

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

s=sum(A)

for b,c in BC:
    if d[b]==0:
        print(s)
        continue
    a=d[b]
    s+=(c-b)*a
    d[b]=0
    d[c]+=a
    print(s)

Submission status: Accepted

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)


s = sum(A)
nord = [0]*(10**5 +1)

for a in A:
    nord[a] += 1

for b,c in zip(B,C):
    s +=  (c-b)*nord[b]
    nord[c] += nord[b]
    nord[b] = 0
    print(s)

Submission status: Accepted

Solution code:
from collections import Counter

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


my_dict = Counter(A)

def cals_sum(my_dict):
    values = [ my_dict[key]*key for key in my_dict.keys() if my_dict[key] != 0]
    #for key in my_dict.keys():
    #    value = my_dict[key]
    #    sum += int(key) * int(value)
    return sum(values)
  
my_sum = cals_sum(my_dict)

for i in range(len(B)):
    b = B[i]
    c = C[i]
    tmpb = my_dict[b] 
    my_dict[b] = 0
    tmpc = my_dict[c]
    my_dict[c] = tmpb + tmpc
    
    my_sum += ((tmpb)*c - tmpb*b)

    print(my_sum)

Submission status: Accepted

Solution code:
import numpy as np
n=int(input())
a=np.array(list(map(int,input().split())))
a0,a1= np.unique(a,return_counts=True)
suma=np.sum(a)
a2=np.array([0]*100001)
for j in range(a0.size):
  a2[a0[j]]=a1[j]
#print(suma)
#print(a0)
#print(a1)
q=int(input())
for i in range(q):
  b,c=map(int,input().split())
  sumb=a2[b]
  a2[b]=0
  a2[c]+=sumb
  sumc=sumb*(c-b)
  suma+=sumc
  print(suma)

Submission status: Accepted

Solution code:
summ=0
mapper=dict()
n=int(input())
arr=[int(i) for i in input().split()]
for i in range(0,n):
    temp=arr[i]
    if temp not in mapper:
        mapper[temp]=0
    mapper[temp]+=1
    summ+=temp
q=int(input())
for i in range(0,q):
    temp,temp1=[int(j) for j in input().split()]
    if((temp in mapper) and  temp1 not in mapper):
        summ-=temp*mapper[temp]
        summ+=temp1*mapper[temp]
        mapper[temp1]=0
        mapper[temp1]+=mapper[temp]
        mapper.pop(temp)
    elif((temp in mapper) and (temp1 in mapper)):
        summ-=temp*mapper[temp]
        summ+=temp1*mapper[temp]
        val=mapper[temp]
        mapper.pop(temp)
        mapper[temp1]=mapper[temp1]+val
    print(summ)

Submission status: Accepted

Solution code:
import collections
n=int(input())
a=dict(collections.Counter(list(map(int,input().split()))))
q=int(input())
ans=0
for i in a:
  ans+=i*a[i]
for i in range(q):
  b,c=map(int,input().split())
  ans+=a.get(b,0)*(c-b)
  print(ans)
  a[c]=a.get(b,0)+a.get(c,0)
  a[b]=0

Submission status: Accepted

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


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

al = {}
suma = sum(a)

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

for i in range(q):
    if b[i][0] in al:
        suma += (b[i][1] - b[i][0]) * al[b[i][0]]
        
        if b[i][1] in al:
            
            al[b[i][1]] += al[b[i][0]]
            al[b[i][0]] = 0
        else:
            al[b[i][1]] = al[b[i][0]]
            al[b[i][0]] = 0
    print(suma)

Submission status: Accepted

Solution code:
import collections

n = int(input())
a = list(map(int, input().split()))
a_ = collections.Counter(a)
sum = 0
for x in a_.items():
    sum += x[0]*x[1]
q = int(input())
res = []
for _ in range(q):
    b, c = map(int, input().split())
    d = a_.get(b, 0)
    if d != 0:
        a_[b] = 0
        a_[c] += d
    sum += (c-b)*d
    res.append(sum)
for x in res:
    print(x)

Submission status: Accepted

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

c = Counter(a)
ans = sum(a)
for i in range(q):
    ans = ans + (b[i][1] - b[i][0])*c[b[i][0]]
    c[b[i][1]] += c[b[i][0]]
    c[b[i][0]] = 0
    print(ans)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
s = sum(a)
x = [0 for _ in range(10**5+1)]
for ai in a:
  x[ai] += 1
q = int(input())
for _ in range(q):
  b,c = map(int,input().split())
  xb = x[b]
  x[b] = 0
  s+= xb*(c-b)
  x[c] += xb
  print(s)

Submission status: Accepted

Solution code:
# import sys
# import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
#     combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
# mod = 998244353
INF = 1<<50

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

def main():
    n = int(input())
    a = readInt()
    q = int(input())
    bc = []
    mx = max(a)
    for i in range(q):
        bc.append(readInt())
        mx = max(mx,max(bc[i][0],bc[i][1]))
    A = [0 for i in range(mx+1)]
    for x in a:
        A[x] += 1
    ans = sum(a)
    for i in range(q):
        b,c = bc[i]
        ans += (c-b)*A[b]
        A[c] += A[b]
        A[b] = 0
        print(ans)
    return

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter

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

  sum_A = 0
  for a in countA.keys():
    sum_A += a*countA[a]

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


if __name__ == "__main__":
  resolve()

Submission status: Accepted

Solution code:
from collections import Counter

def update(dic, b, c):
    n = dic.pop(b)
    dic[c] = n + dic.get(c, 0)
    
def calc_diff(dic, b, c):
    if dic.get(b):
        return c * dic[b] - b * dic[b]
    return 0

def calc_total(dic):
    return sum(k * v for k, v in dic.items())

N = int(input())
lis = list(map(int, input().split()))
dic = dict(Counter(lis))
Q = int(input())
total = calc_total(dic)
for _ in range(Q):
    B, C = map(int, input().split())
    diff = calc_diff(dic, B, C)
    total += diff
    print(total)
    if diff:
        update(dic, B, C)