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

Solution (Python):
import math









import collections
N = int(input()) 
A = list(map(int, input().split())) 
Q = int(input()) 
counter = collections.Counter(A)
ans = 0
for i in counter.keys():
  ans = ans + i * counter[i]

while True:
  try:

    B,C = list(map(int, input().split())) 
    old = C * counter[C] + counter[B] * B
    counter[C] = counter[C] + counter[B]
    del counter[B]
    new = C * counter[C]
    ans = ans + (new - old)
    print(ans)
  except:
    break;

Solution (Python):
n = int(input())
a_count_list = [0 for i in range(10**5+1)]
for i in input().split(" "):
    x = int(i)
    a_count_list[x-1]+=1
total = sum([(i+1)*x for i,x in enumerate(a_count_list)])

q = int(input())
for i in range(q):
    b, c = input().split(" ")
    b = int(b)
    c = int(c)
    total+=a_count_list[b-1] * c
    total-=a_count_list[b-1] * b
    a_count_list[c-1] += a_count_list[b-1]
    a_count_list[b-1] = 0
    print(total)

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
cnt=[0]*(10**5)
ans=sum(a)
for i in a:
  cnt[i-1]+=1
q=int(input())
bc=[list(map(int,input().split())) for i in range(q)]
for i in range(q):
  ans+=(cnt[bc[i][0]-1]*(bc[i][1]-bc[i][0]))
  print(ans)
  cnt[bc[i][1]-1]+=cnt[bc[i][0]-1]
  cnt[bc[i][0]-1]=0

Solution (Python):
from sys import stdin




def ii(): return int(stdin.readline())
def fi(): return float(stdin.readline())
def mi(): return map(int, stdin.readline().split())
def fmi(): return map(float, stdin.readline().split())
def li(): return list(mi())
def si(): return stdin.readline().rstrip()
def lsi(): return list(si())

res=['Yes', 'No']



test_case=1
while test_case:
    test_case-=1


    cnt=[0]*100005
    n=ii()
    a=li()
    for i in a:
        cnt[i]+=1
    s=sum(a)
    for _ in range(ii()):
        x, y=mi()
        s+=(y-x)*cnt[x]
        print(s)
        cnt[y]+=cnt[x]
        cnt[x]=0

Solution (Python):
import collections
def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]
N=int(input())
A=list(map(int,input().split()))
goukei=sum(A)
Q=int(input())
BC=[]
for i in range(Q):
    BC.append(list(map(int,input().split())))
c = collections.Counter(A)
for i in BC:
    goukei+=c[i[0]]*(i[1]-i[0])
    c[i[1]]=c[i[0]]+c[i[1]]
    c[i[0]]=0
    print(goukei)

Solution (Python):
import collections
N = int(input())
a = list(map(int, input().split()))
a_c = collections.Counter(a)
Q = int(input())
BC = [list(map(int, input().split())) for _ in range(Q)]
s_old = 0
for k, v in a_c.items():
    s_old += k*v
for bc in BC:
  b = bc[0]
  c = bc[1]
  s = s_old
  if b in a_c:
    n = a_c.pop(b)
    a_c[c]+=n
    s-=n*b
    s+=n*c
  print(s)
  s_old = s

Solution (Python):
n = int(input().strip()) 
a = [int(x.strip()) for x in input().strip().split(' ')]

x = {}
sum = 0
for i in a:
  x[i] = (x[i] if i in x else 0) + 1
  sum = sum + i

q = int(input().strip())
for i in range(0, q):
  b, c = [int(x.strip()) for x in input().strip().split(' ')]
  if b in x and b != c:
    sum = sum + (c - b) * x[b]
    if c in x:
      x[c] = x[c] + x[b]
    else:
      x[c] = x[b]
    del x[b]    
  print(sum)

Solution (Python):
n = int(input())
A = list(map(int,input().split()))
lis = [0 for _ in range(10**5 + 1)]
S = sum(A)
for a in A:
    lis[a] += 1
q = int(input())
for _ in range(q):
    b,c = map(int,input().split())
    S += (c-b)*lis[b]
    if not lis[b] == 0:
        temp = lis[b]
        lis[b] = 0
        lis[c] += temp
    print(S)

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

import collections
cnt = collections.Counter(a)
ans = 0
for ai, ni in cnt.items():
    ans += ai * ni
for _ in range(q):
    bi, ci = map(int, input().split())
    tmp = cnt[bi]
    del cnt[bi]
    cnt[ci] = tmp + cnt[ci]
    ans = ans - bi * tmp + ci * tmp
    print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
n=int(input())
A=list(map(int,input().split()))
k={}
ans=sum(A)
for i in A:
  if i in k:
    k[i]+=1
  else:
    k[i]=1
q=int(input())
for i in range(q):
  b,c=map(int,input().split())
  if b in k:
    f=c*k[b]-b*k[b]
    ans+=f
    p=k[b]
    del k[b]
    if c in k:
      k[c]+=p
    else:
      k[c]=p
  print(ans)

Solution (Python):
import sys, math

def calcSum(AList, B, C, Sum):
    Len = AList[B]
    if(Len == 0):
        return Sum
    Sum += (C-B) * Len

    AList[B] = 0
    AList[C] += Len
    return Sum

if(__name__ == "__main__"):
    N= int( input().strip() )

    Max = int(10**5)+1
    AList = [0] * Max
    A_str = input().strip().split()
    N_Queries = int( input().strip() )

    sum = 0
    for i in range(N):
        value = int(A_str[i])
        AList[value] += 1
        sum += value
    BCs = []
    Sums = [sum]
    for i in range(N_Queries):
        BC_str =  input().strip().split()
        B = int(BC_str[0])
        C = int(BC_str[1])
        Sums.append( calcSum(AList, B, C, Sums[-1]) )
        """
        BC = [ int(BC_str[0]), int(BC_str[1]) ]
        BCs.append(BC)
        """

    for i in range(1, 1+N_Queries):
        print(Sums[i])

Solution (Python):
from collections import Counter
n = int(input())
a = list(map(int,input().split()))
q = int(input())
sm = sum(a)
dic = dict(Counter(a))
for _ in range(q):
    b,c = map(int,input().split())
    if b not in dic:
        print(sm)
    else:
        dif = c-b
        sm = sm+dic[b]*dif
        print(sm)
        x = dic[b]
        if c in dic:
            dic[c]+=x
        else:
            dic[c]=x
        dic[b]=0

Solution (Python):
import collections
n=int(input())
a=list(map(int,input().split()))
s=sum(a)
q=int(input())
x=collections.Counter(a)
for _ in range(q):
  b,c=map(int,input().split())
  s=s-x[b]*b+x[b]*c
  print(s)
  x[c]+=x[b]
  x[b]=0

Solution (Python):
n = int( input() )
a_array = list( map( int, input().split() ) )
q = int( input() )
bc_array = []
for _ in range( q ):
    bc_i = list( map( int, input().split() ) )
    bc_array.append( bc_i )

a_list = [ 0 for _ in range( 10 ** 5 + 1 ) ]
for a in a_array:
    a_list[ a ] += 1

s = 0
for i in range( 10 ** 5 + 1 ):
    s += i * a_list[ i ]

for b, c in bc_array:
    s = s + ( c - b ) * a_list[ b ]
    a_list[ c ] += a_list[ b ]
    a_list[ b ] = 0
    print( s )

Solution (Python):
n = int(input())
data = list(map(int, input().split()))
q = int(input())
d = {}
big = 10**5+100

for i in range(big):
  d[i+1] = []
for i in data:
  d[i].append(i)

ans = sum(data)
for i in range(q):
  a, b = map(int, input().split())
  
  ans += len(d[a]) * (b-a)
  d[b] = d[b] + d[a]
  d[a] = []
  print(ans)

Solution (Python):
from collections import Counter

n = int(input())
A = list(map(int, input().split()))
counter = Counter(A)
value = sum(A)

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

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
Q=int(input())
B=[]
C=[]
for i in range(Q):
  Bt,Ct=map(int,input().split())
  B+=[Bt]
  C+=[Ct]
num =[0 for i in range(10**5+3)]
for i in range(N):
  num[A[i]]+=1
S=0
for i in range(10**5+1):
  S+=num[i]*i
for i in range(Q):
  tmp=num[B[i]]
  num[B[i]] =0
  num[C[i]] += tmp
  S=S+tmp*(C[i]-B[i])
  print(S)

Solution (Python):
import itertools
from collections import deque,defaultdict,Counter
from itertools import accumulate
import bisect
from heapq import heappop,heappush,heapify
import math
from copy import deepcopy
import queue


Mod = 1000000007
fact = [1, 1]
factinv = [1, 1]
inv = [0, 1] 
for i in range(2, 10**5 + 1):
    fact.append((fact[-1] * i) % Mod)
    inv.append((-inv[Mod % i] * (Mod // i)) % Mod)
    factinv.append((factinv[-1] * inv[-1]) % Mod)
    
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n - r] % p
    
def sieve_of_eratosthenes(n):
    if not isinstance(n,int):
        raise TypeError("n is not int")
    if n<2:
        raise ValueError("n is not effective")
    prime = [1]*(n+1)
    for i in range(2,int(math.sqrt(n))+1):
        if prime[i] == 1:
            for j in range(2*i,n+1):
                if j%i == 0:
                    prime[j] = 0
    res = []
    for i in range(2,n+1):
        if prime[i] == 1:
            res.append(i)
    return res

 
class UnionFind:
    def __init__(self,n):
        self.parent = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    def findroot(self,x):
        if x == self.parent[x]:
            return x
        else:
            y = self.parent[x]
            y = self.findroot(self.parent[x])
            return y
    
    def union(self,x,y):
        px = self.findroot(x)
        py = self.findroot(y)
        if px < py:
            self.parent[y] = px
        else:
            self.parent[px] = py
 
    def same_group_or_no(self,x,y):
        return self.findroot(x) == self.findroot(y)
import string
def main():  
    n = int(input())
    a = list(map(int, input().split()))
    q = int(input())
    bc = [list(map(int, input().split())) for i in range(q)]
    b = [bc[i][0] for i in range(q)]
    c = [bc[i][1] for i in range(q)]
    dic = Counter(a)
    base = sum(a)
    for i in range(q):
        celb = deepcopy(dic[b[i]])
        celc = deepcopy(dic[c[i]])
        dic[c[i]] += dic[b[i]]
        dic[b[i]] = 0
        base += (c[i]-b[i])*(celb)
        print(base)
if __name__ == "__main__":
    main()

Solution (Python):
n = int(input())
*A, = map(int, input().split())
C = {i: 0 for i in range(1, 10**5 + 1)}
for a in A:
    C[a] += 1
s = sum(A)
q = int(input())
for _ in range(q):
    b, c = map(int, input().split())
    tmp = C[b]
    C[b] = 0
    C[c] += tmp
    s += (c - b) * tmp
    print(s)

Solution (Python):
import collections
n=int(input())
a=list(map(int,input().split()))
dic=collections.Counter(a)
m=int(input())

s=sum(a)

for i in range(m):
    p,q=map(int,input().split())
    s=s-p*dic[p]+q*dic[p]
    dic[q]+=dic[p]
    dic[p]=0
    print(s)

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

cnt = [0] * (100000+1)
ans = 0
for i in range(N):
  cnt[A[i]] += 1
  ans += A[i]

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

Solution (Python):
from collections import defaultdict

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

d = defaultdict(int)

for a in A:
    d[a] += 1
S = sum(A)

for q in range(Q):
    b = B[q]
    c = C[q]
    if d[b]==0:
        print(S)
    else:
        S -= d[b]*b
        S += c*d[b]
        d[c] += d[b]
        d[b] = 0
        print(S)

Solution (Python):
import collections


def main():
    _ = int(input())
    A = list(map(int, input().split()))
    q = int(input())

    CNT = [0] * (10 ** 5)

    C = collections.Counter(A)
    for k, v in C.items():
        CNT[k - 1] = v

    s = 0
    for i in range(10 ** 5):
        s += (i + 1) * CNT[i]

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

        s = s - b * value + c * value
        print(s)


if __name__ == '__main__':
    main()

Solution (Python):
import collections

N=int(input())
A=list(map(int,input().split()))
Q=int(input())
bcs=[list(map(int,input().split())) for i in range(Q)]
total=sum(A)
c=collections.Counter(A)
ans=[0 for i in range(Q)]


for i in range(Q):
    B=bcs[i][0]
    C=bcs[i][1]
    if c[B]!=0:
        total+=c[B]*(C-B)
        ans[i]=total
        c[C]+=c[B]
        c[B]=0
    else:
        ans[i]=total
for i in range(Q):
    print(ans[i])

Solution (Python):
import collections
input()
math_dic = collections.Counter((map(int,input().split())))
num = int(input())
total_num = sum([index*value for index,value in math_dic.items()])
for i in range(num):
    a,b = map(int,input().split())
    if a not in math_dic:
        print(total_num)
        continue
    if b not in math_dic:
        math_dic[b] = 0
    total_num -= a*math_dic[a]
    total_num += b*math_dic[a]
    math_dic[b] += math_dic.pop(a)
    print(total_num)

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

Solution (Python):
from collections import Counter

def main():
    n = int(input())
    a = list(map(int,input().split()))
    total = sum(a)
    counter = Counter(a)
    q = int(input())
    for i in range(q):
        b,c = map(int,input().split())
        num_of_changed_num = counter[b]
        counter[b] = 0
        counter[c] += num_of_changed_num
        total -= b * num_of_changed_num
        total += c * num_of_changed_num
        print(total)



if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict

def main():
    n = int(input())
    d = defaultdict(int)
    res = 0
    for a in input().split():
        aa = int(a)
        d[int(aa)] += 1
        res += aa

    nq = int(input())
    for q in range(nq): 
        b, c = [int(i) for i in input().split()]
        res += (c - b) * d[b]
        d[c] += d[b]
        d[b] = 0
        print(res)

if __name__ == '__main__':
    main()

Solution (Python):








import sys,collections

N = int(sys.stdin.readline())
A = tuple(map(int,sys.stdin.readline().split())) 
Q = int(sys.stdin.readline())
BC = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(Q)) 
co = collections.Counter(A)
s = sum(A)

for b,c in BC:
    if b in co:
        n = co[b]
        del(co[b])
        co[c] += n
        s += (c-b)*n
    print(s)

Solution (Python):
n=int(input())
arr=list(map(int,input().strip().split()))
k=int(input())
d=dict()
for i in range(10**5+1):
    d[i]=0
for i in range(n):
    d[arr[i]]=d[arr[i]]+1
sumi=0
for i in range(n):
    sumi=sumi+arr[i]
for i in range(k):
    a,b=[int(a) for a in input().split()]
    e1=d[a]
    d[b]=d[b]+e1
    sumi=sumi+(e1)*(b-a)
    print(sumi)
    d[a]=0

Solution (Python):
N = int(input())
ls = [0 for i in range(10**5)]
now = 0
A = list(map(int,input().split()))
for i in range(N):
    now += A[i]
    ls[A[i]-1] += 1
q = int(input())
for i in range(q):
    a,b = map(int,input().split())
    now += (b-a)*ls[a-1]
    print(now)
    ls[b-1] += ls[a-1]
    ls[a-1] = 0

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

imax = 10**5

d = [0]*imax
for i in range(n):
    d[a[i]-1] += 1

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

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

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

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

Solution (Python):
import sys
import numpy as np
import random
from decimal import Decimal
import itertools
import re
import bisect
from collections import deque, Counter
from functools import lru_cache

sys.setrecursionlimit(10**9)
INF = 10**13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
def SERIES(n): return np.fromstring(sys.stdin.buffer.read(), dtype=np.int32, sep=' ')
def GRID(h,w): return np.fromstring(sys.stdin.buffer.read(), dtype=np.int32, sep=' ').reshape(h,-1)[:,:w]
def GRIDfromString(h,w): return np.frombuffer(sys.stdin.buffer.read(), 'S1').reshape(h,-1)[:,:w]
MOD = 1000000007

def main():
	n = I()
	a_list = LI()
	q = I()
	a_sum = sum(a_list)
	a_list_counter = Counter(a_list)
	for _ in range(q):
		b, c = LI()
		a_sum += (c-b)*a_list_counter[b]
		a_list_counter[c] += a_list_counter[b]
		a_list_counter[b] = 0
		print(a_sum)



if __name__ == '__main__':
    main()

Solution (Python):
import numpy as np
n = int(input())
a = np.array([int(a) for a in input().split()])
q = int(input())
bc = np.array([[int(a) for a in input().split()] for j in range(q)])

u, c = np.unique(a, return_counts=True)
dica = dict(zip(u, c))


keys = dica.keys()

tmp = sum([ k*dica[k] for k in dica.keys()])


for i in range(q):
  t1, t2 = bc[i]
  if not t1 in keys:
    dica[t1] = 0
  if not t2 in keys:
    dica[t2] = 0

  tmp += dica[t1] * (t2 - t1)
  print(tmp)
  
  dica[t2] = dica[t1] + dica[t2]
  dica[t1] = 0

Solution (Python):
import sys
from math import factorial
from collections import Counter
from fractions import Fraction
import heapq, bisect, fractions
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10**15 +5
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
MOD = 10**9 + 7

n = INT()
a = LIST()
q = INT()
b = [0]*q
c = [0]*q
for i in range(q):
    bb, cc = MAP()
    b[i] = bb
    c[i] = cc

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

Solution (Python):


import sys
import pprint

sys.setrecursionlimit(10 ** 6)

class Logger:
	def __init__(self, debug):
		self.debug = debug
	def print(self, *args):
		if self.debug:
			pprint.pprint(args)


def main():
	log = Logger(0)
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	q = int(sys.stdin.readline())
	b = []
	c = []
	for i in range(q):
		bi, ci = map(int, sys.stdin.readline().split())
		b.append(bi)
		c.append(ci)
	v = {}
	for i in range(n):
		v[a[i]] = v.get(a[i], 0) + 1
	suma = sum(a)
	for i in range(q):
		suma += v.get(b[i], 0) * (c[i] - b[i])
		v[c[i]] = v.get(c[i], 0) +  v.get(b[i], 0)
		v[b[i]] = 0
		log.print(v)
		print(suma)
	


main()

Solution (Python):
N = 4
ARR = [1, 1, 1, 1]
Q = 3
SRR = [
    [1, 2],
    [2, 1],
    [3, 5]
]

N = 4
ARR = [1, 2, 3, 4]
Q = 3
SRR = [
    [1, 2],
    [3, 4],
    [2, 4],
]












N = int(input())
ARR = list(map(int,input().split()))
Q = int(input())
SRR = []

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


def calculate(n, arr, q, srr):
    dict = {}
    sumValue = sum(arr)
    for i in range(n):
        value = arr[i]
        if dict.get(value) == None:
            dict.__setitem__(value, 1)
        else:
            dict.__setitem__(value, dict.get(value) + 1)

    for i in range(q):
        fromValue = srr[i][0]
        toValue = srr[i][1]

        if dict.get(fromValue) == None:
            print(sumValue)
        else:
            fromNum = dict.get(fromValue)
            dict.__setitem__(fromValue, 0)
            sumValue += fromNum * (toValue - fromValue)
            if dict.get(toValue) == None:
                dict.__setitem__(toValue, fromNum)
            else:
                dict.__setitem__(toValue, dict.get(toValue) + fromNum)
            print(sumValue)


calculate(N, ARR, Q, SRR)

Solution (Python):
import collections
n=int(input())
List=list(map(int,input().split()))
hashmap=collections.defaultdict(int)
q=int(input())
total=0
for x in List:
    total+=x
    hashmap[x]+=1
for _ in range(q):
    a,b=map(int,input().split())
    
    total=total-hashmap[a]*a+hashmap[a]*b
    hashmap[b]+=hashmap[a]
    hashmap[a]=0
    print(total)

Solution (Python):
n = int(input())
alist = list(map(int, input().split(" ")))
q = int(input())

master = [0 for i in range(100001)]
total = sum(alist)

for a in alist:
  master[a] += 1
for i in range(q):
  b,c = map(int, input().split(" "))
  d = master[b]
  master[b] = 0
  master[c] += d
  total -= b*d
  total += c*d
  print(total)

Solution (Python):
N=int(input())
Ax = map(int,input().split())
Q=int(input())

t=[0]*(10**5+1)
s = 0
for a in Ax:
    t[a] += 1
    s += a

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

Solution (Python):
import numpy as np




N = int(input())
A = np.array(list(map(int, input().split())))
Q = int(input())
BC = []
for _ in range(0,Q):
    BC += [list(map(int, input().split())),]

M = {}
for n in A:
    M[n] = M.get(n, 0) + 1



def solve(N,A,Q,BC,M):
    S = 0
    for (k,v) in M.items():
        S += k*v
    for (b,c) in BC:
        t = M.pop(b,0)
        M[c] = M.get(c,0) + t
        S += (c-b)*t
        print(S)
    return S
        
S = solve(N,A,Q,BC,M)

Solution (Python):
import sys
from collections import Counter

input = sys.stdin.readline


def S():
    return input().rstrip()


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


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


n = I()
al = list(MI())
q = I()

a = Counter(al)

s = sum(al)
for _ in range(q):
    b, c = MI()
    if b in a.keys():
        v = a.pop(b)
        if c in a.keys():
            a[c] += v
        else:
            a[c] = v
        s += (c - b) * v
    print(s)

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
a_d = {}
for a in A:
    if a in a_d:
        a_d[a] += 1
    else:
        a_d[a] = 1
mysum = sum(A)


Q = int(input())
for q in range(Q):
    b, c = map(int,input().split())
    if b in a_d:
        add = a_d[b] 
        
        mysum = mysum - add*b + add*c
        a_d[b] = 0
        if c in a_d:
            a_d[c] += add
        else:
            a_d[c] = add
    print(mysum)

Solution (Python):
import collections

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

c = collections.Counter(A)

ans = 0

for k, v in c.items():
    ans += k * v

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

for i in range(Q):
    B, C = BC[i]
    sabun = 0
    if B in c.keys():
        poped_val = c.pop(B)
        if C not in c.keys():
            c[C] = 0
        c[C] += poped_val
        sabun = C * poped_val - B * poped_val
    ans += sabun
    print(ans)

Solution (Python):
n = int(input())
an = list(map(int, input().split()))
q = int(input())
bc = [list(map(int, input().split())) for _ in range(q)]


dic = {}
for a in an:
    dic[a] = 1 if a not in dic else dic[a] + 1
sm = sum(k*dic[k] for k in dic)

for i in range(q):
    b, c = bc[i]
    if b in dic:
        sm -= b * dic[b]
        sm += c * dic[b]
        if c in dic:
            dic[c] += dic[b]
        else:
            dic[c] = dic[b]
        del dic[b]
    print(sm)

Solution (Python):
from collections import Counter

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

operates = [tuple(map(int, input().split())) for _ in range(Q)]
result = 0
for k, n in A.items():
  result += k * n

for b, c in operates:
  n_b = A.get(b, 0)
  if n_b > 0:
    A[b] = 0
    A[c] += n_b
    result -= b * n_b
    result += c * n_b
  print(result)

Solution (Python):
from collections import Counter

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

s = sum(map(lambda k: k * d[k], d))
for i in range(Q):
  B, C = [int(x) for x in input().split()]

  s += (C - B) * d[B]
  d[C] = d.get(C, 0) + d[B]
  d[B] = 0
  
  print(s)

Solution (Python):

from collections import Counter
n = int(input())
a = list(map(int, input().split()))
sum_a = sum(a)
q = int(input())
bc = [list(map(int, input().split())) for _ in range(q)]
a = Counter(a)

for i in range(q):
    
    
    num = a[bc[i][0]]*bc[i][1]
    sum_a = sum_a - (a[bc[i][0]] * bc[i][0]) + num

    a[bc[i][1]] += a[bc[i][0]]
    a[bc[i][0]] = 0
    print(sum_a)

Solution (Python):
import collections


N = int(input())
A = list(map(int,input().split()))
Q = int(input())
c = collections.Counter(A)
ans = sum(A)
for i in range(Q):
    B,C = list(map(int,input().split()))
    ans = ans + c[B]*(C-B)
    c[C] += c[B]
    c[B] = 0
    print(ans)

Solution (Python):
n=int(input())
m={}
s=0
for i in input().split():
    i=int(i)
    x=m.get(i,0)
    m[i]=x+1
    s+=i
q=int(input())
for i in range(q):
    b,c=[int(i) for i in input().split()]
    x=m.get(b,0)
    y=m.get(c,0)
    m[b]=0
    m[c]=x+y
    s=s-(b*x)+(c*x)
    print(s)

Solution (Python):
def main():
    N = int(input())
    A = list(map(int, input().split()))
    Q = int(input())
    opeList = []

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

        opeList.append([b, c])
    
    bucket = [0] * (10**5 + 1)
    sumA = sum(A)

    for num in A:
        bucket[num] += 1
    
    for ope in opeList:
        tmp = bucket[ope[0]]
        bucket[ope[0]] = 0
        bucket[ope[1]] += tmp
        sumA = sumA - ope[0] * tmp + ope[1] * tmp
        print(sumA)

if __name__ == '__main__':
    main()

Solution (Python):
def _calc_sum(cache):
    sum_value = 0
    for v, indices in cache.items():
        sum_value += v * len(indices)
    return sum_value


def _main(N, A_list, Q, BC_list):
    cache = {}
    for i, a in enumerate(A_list):
        cache.setdefault(a, []).append(i)

    sum_value = _calc_sum(cache)

    for b, c in BC_list:
        indices = cache.get(b, [])
        cache[b] = []
        sum_value -= b * len(indices)
        cache.setdefault(c, []).extend(indices)
        sum_value += c * len(indices)
        print(sum_value)


def _entry():
    N = int(input())
    A_list = list(map(int, input().split()))
    Q = int(input())
    BC_list = []
    for i in range(Q):
        B, C = map(int, input().split())
        BC_list.append((B, C))
    _main(N, A_list, Q, BC_list)


if __name__ == "__main__":
    _entry()

Solution (Python):
n = int(input())
al = list(map(int, input().split()))
q = int(input())
bl = []
cl = []
for i in range(q):
    b,c = map(int, input().split())
    bl.append(b)
    cl.append(c)

shoki = sum(al)

dic = {}
for i in al:
    if i in dic:
        dic[i] += 1
    else:
        dic[i] = 1


for i in range(q):
    b = bl[i]
    c = cl[i]
    if b in dic:
        bcount = dic.pop(b)
    else:
        bcount = 0
    if c in dic:
        dic[c] += bcount
    else:
        dic[c] = bcount
    shoki += (c - b)*bcount
    print(shoki)

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

from collections import defaultdict
d = defaultdict(int)
S = 0
for a in A:
   d[a] += 1
   S += a

for _ in range(Q):
   b, c = map(int, input().split())
   S += d[b] * (c - b)
   print(S)
   d[c] += d[b]
   d[b] = 0

Solution (Python):
from collections import Counter

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

def sum_from_counter(d):
  return sum(map(lambda k: k * d[k], d))

s = sum(map(lambda k: k * d[k], d))
for i in range(Q):
  B, C = [int(x) for x in input().split()]
  d[C] = d.get(C, 0) + d[B]
  s += (C - B) * d[B]
  d[B] = 0
  print(s)

Solution (Python):
import numpy as np
import math
import scipy as sp
import queue
import collections

MOD = 10 ** 9 + 7
INF = 10 ** 9

def main(kwargs):
    n = kwargs["n"]
    A = kwargs["A"]
    q = kwargs["q"]
    B = kwargs["B"]
    C = kwargs["C"]
    cnt = dict(collections.Counter(A))
    res = [sum(A)]

    for i in range(q):
        if B[i] in cnt.keys():
            res.append(res[-1] + (C[i] - B[i]) * cnt[B[i]])

            if C[i] in cnt.keys():
                cnt[C[i]] += cnt[B[i]]

            else:
                cnt[C[i]] = cnt[B[i]]

            cnt[B[i]] = 0

        else:
            res.append(res[-1])

    res = "\n".join([str(i) for i in res[1:]])
    return res

if __name__ == "__main__":
    kwargs = {}

    cin = input().split()
    kwargs["n"] = [int(i) for i in cin][0]

    cin = input().split()
    kwargs["A"] = [int(i) for i in cin]

    cin = input().split()
    kwargs["q"] = [int(i) for i in cin][0]

    kwargs["B"] = []
    kwargs["C"] = []
    for i in range(kwargs["q"]):
        cin = input().split()
        b, c = [int(i) for i in cin]
        kwargs["B"].append(b)
        kwargs["C"].append(c)

    cout = main(kwargs)
    print(cout)

Solution (Python):
n = int(input())
nums = list(map(int, input().split()))
d = [0 for _ in range(10 ** 5 + 10)]
for k in nums:
	d[k] += 1

ans = sum(nums)

q = int(input())
for _ in range(q):
	query = list(map(int, input().split()))
	k = d[query[0]]
	if k >= 1:
		ans += (query[1] - query[0]) * k
		d[query[0]] = 0 
		d[query[1]] += k
	print(ans)

Solution (Python):
from collections import defaultdict

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

n= readInt()
a = readInts()
q = readInt()
bc = []
for i in range(q):
	bc.append(readInts())

s = sum(a)
d = defaultdict(int)
for i in a:
	d[str(i)]+=1
for i in bc:
	t = d[str(i[0])]
	d[str(i[0])]=0
	d[str(i[1])]+=t
	s=s-t*i[0]+t*i[1]
	print(s)

Solution (Python):
from collections import Counter
from collections import defaultdict
def main():
    n = int(input())
    a = list(map(int, input().split()))
    q = int(input())
    asum = sum(a)
    ac = Counter(a)
    acl = defaultdict(int)
    for ae in ac:
        acl[ae] = ac[ae]

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

if __name__ == '__main__':
    main()

Solution (Python):
from collections import Counter
n = int(input())
la = list(map(int, input().split()))
s = sum(la)
d = dict(Counter(la))

q = int(input())
for _ in range(q):
    b,c = map(int, input().split())
    if b in d:
        nb = d.pop(b)
    else:
        nb = 0
    delta = (c-b)*nb
    s += delta
    print(s)
    if nb > 0:
        if c in d:
            d[c] += nb
        else:
            d[c] = nb