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 sys

sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
from math import floor, sqrt, factorial, hypot, log  
from heapq import heappop, heappush, heappushpop
from collections import Counter, defaultdict, deque
from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint


def ceil(a, b): return (a + b - 1) // b


inf = float('inf')
mod = 10 ** 9 + 7


def pprint(*A):
    for a in A:     print(*a, sep='\n')


def INT_(n): return int(n) - 1


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


def MF(): return map(float, input().split())


def MI_(): return map(INT_, input().split())


def LI(): return list(MI())


def LI_(): return [int(x) - 1 for x in input().split()]


def LF(): return list(MF())


def LIN(n: int): return [I() for _ in range(n)]


def LLIN(n: int): return [LI() for _ in range(n)]


def LLIN_(n: int): return [LI_() for _ in range(n)]


def LLI(): return [list(map(int, l.split())) for l in input()]


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


def F(): return float(input())


def ST(): return input().replace('\n', '')

import numpy as np
from collections import Counter


def main():
    N = I()
    A = LI()
    Q = I()
    act_list = LLIN(Q)
    cnt = Counter(A)
    ans = sum(A)
    
    for z in act_list:
        b_num = cnt[z[0]]
        cnt[z[0]] = 0
        cnt[z[1]] = cnt[z[1]] + b_num
        
        
        
        ans = ans - (z[0] * b_num) + (z[1] * b_num)
        print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
d = {}
for a in A:
    if a in d:
        d[a] += 1
    else:
        d[a] = 1
ans = 0
for k in d:
    ans += k * d[k]
Q = int(input())
for i in range(Q):
    b, c = map(int, input().split())
    if b in d:
        Bn = d[b]
        if c in d:
            d[c] += d[b]
            d[b] = 0
        else:
            d[c] = d[b]
            d[b] = 0
        ans += (c-b)*Bn
    print(ans)

Solution (Python):
n = int(input())
A = list(map(int, input().split()))
q = int(input())
l = [0]*(10**5+10)
num = sum(A)
for i in A:
    l[i] = l[i] + 1


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

Solution (Python):
import sys
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
read = sys.stdin.buffer.read
sys.setrecursionlimit(10 ** 7)
INF = float('inf')

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

import collections
counter = collections.defaultdict(int)
for key, value in collections.Counter(A).items():
    counter[key] = value

ans = sum(A)

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

Solution (Python):
from collections import Counter

R = lambda: map(int, input().split())
R()
d = Counter(R())
s = sum(d.elements())
q, = R()
for _ in range(q):
  b, c = R()
  s += (c - b) * d[b]
  print(s)
  d[c]+=d[b]
  d[b] = 0

Solution (Python):
n=int(input())
l=list(map(int,input().split()))
q=int(input())
ar=[0 for i in range (100000)]
tot=0
for i in range(n):
    ar[l[i]-1]+=1
    tot+=l[i] 
for j in range(q):
    a,b=map(int,input().split())
    val=0
    tot=tot-(a*ar[a-1])-(ar[b-1]*b)
    ar[b-1]+=ar[a-1]
    tot=tot+(ar[b-1]*b)
    ar[a-1]=0
    print(tot)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B = [0] * Q
C = [0] * Q
dic = {}
for q in range(Q):
  B[q], C[q] = map(int, input().split())
for k in range(N):
  
  if A[k] in dic:
    dic[A[k]] += 1
  else:
    dic[A[k]] = 1
sumA = sum(A)
for q in range(Q):
  if B[q] in dic:
    sumA += (C[q]-B[q]) * dic[B[q]]
  else:
    print(sumA)
    continue
  if C[q] in dic:
    dic[C[q]] += dic[B[q]]
  else:
    dic[C[q]] = dic[B[q]]
  dic[B[q]] = 0
  print(sumA)

Solution (Python):
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    n = gete(int)
    a = list(geta(int))

    d = defaultdict(int)
    s = sum(a)
    for i in a:
        d[i] += 1

    for _ in range(gete(int)):
        b, c = geta(int)

        if b in d:
            s += (c-b) * d[b]
            d[c] += d[b]
            d[b] = 0

        print(s)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
import collections

input = sys.stdin.readline


def main():
    N = int(input())
    A =list(map(int,input().split()))
    AD = collections.Counter(A)
    Q = int(input())
    ans =0
    for key, item in AD.items():
        ans += key * item


    for i in range(Q):
        b, c = map(int,input().split())
        if b not in AD.keys():
            print(ans)
        else:
            if c not in AD.keys():
                ans =ans +(c-b)*AD[b]
                AD[c] = AD[b]
                AD[b] =0
                print(ans)
            else:
                ans = ans + (c - b) * AD[b]
                AD[c] += AD[b]
                AD[b] = 0
                print(ans)






if __name__ == "__main__":
    main()

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

Solution (Python):
mod=10**9+7
import math
import sys
from collections import deque
import heapq
import copy
import itertools
from itertools import permutations
from itertools import combinations
import bisect
def mi() : return map(int,sys.stdin.readline().split())
def ii() : return int(sys.stdin.readline().rstrip())
def i() : return sys.stdin.readline().rstrip()
a=ii()
l=list(mi())
b=ii()
lst=[0]*(100001)
m=sum(l)
for j in l:
  lst[j]+=1
for k in range(b):
  x,y=mi()
  g=lst[x]
  m+=(y-x)*g
  lst[x]=0
  lst[y]+=g
  print(m)

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

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

numdic = {}

s = 0
for i in a:
  s += i
  
  if i in numdic:
    numdic[i] += 1
  else:
    numdic[i] = 1



for i in range(q):
  bc = list(map(lambda x:int(x), input().split()))
  
  if bc[0] in numdic:
    s = s + bc[1]*numdic[bc[0]] - bc[0]*numdic[bc[0]]
    if bc[1] in numdic:
      numdic[bc[1]] += numdic[bc[0]]
      numdic[bc[0]] = 0
    else:
      numdic[bc[1]] = numdic[bc[0]]
      numdic[bc[0]] = 0
  print(s)

Solution (Python):

import sys
input = sys.stdin.readline



def swaparr(arr, a,b):
    temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp


def gcd(a,b):
    if a == 0:
        return b
    return gcd(b%a, a)


def nCr(n, k): 
    if(k > n - k): 
        k = n - k 
    res = 1
    for i in range(k): 
        res = res * (n - i) 
        res = res / (i + 1) 
    return int(res) 


def upper_bound(a, x, lo=0):
    hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x:
            lo = mid+1
        else:
            hi = mid
    return lo


def primefs(n):
    
    primes = {}
    while(n%2 == 0 and n > 0):
        primes[2] = primes.get(2, 0) + 1
        n = n//2
    for i in range(3, int(n**0.5)+2, 2):
        while(n%i == 0 and n > 0):
            primes[i] = primes.get(i, 0) + 1
            n = n//i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    
    
    return primes


def power(x, y, p): 
    res = 1
    x = x % p  
    if (x == 0) : 
        return 0
    while (y > 0) : 
        if ((y & 1) == 1) : 
            res = (res * x) % p 
        y = y >> 1      
        x = (x * x) % p 
    return res 


def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b









def find(x, link):
    p = x;
    while( p != link[p]):
        p = link[p];
    
    while( x != p):
        nex = link[x];
        link[x] = p;
        x = nex;
    return p;




def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        x,y = swap(x,y)
    if x != y:
        size[x] += size[y]
        link[y] = x


def sieve(n): 
    prime = [True for i in range(n+1)] 
    p = 2
    while (p * p <= n): 
        if (prime[p] == True): 
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    return prime


MAXN = int(1e6 + 5)
def spf_sieve():
    spf[1] = 1;
    for i in range(2, MAXN):
        spf[i] = i;
    for i in range(4, MAXN, 2):
        spf[i] = 2;
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i*i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i;
    




def factoriazation(x):
    ret = {};
    while x != 1:
        ret[spf[x]] = ret.get(spf[x], 0) + 1;
        x = x//spf[x]
    return ret
    
    


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

def str_array():
    return input().strip().split();


MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');



n = int(input()); a = int_array();
ans = sum(a); dick = dict();
for i in a:
    dick[i] = dick.get(i, 0) + 1;
for _ in range(int(input())):
    b, c = int_array();
    k = dick.get(b, 0); 
    if k > 0:
        del dick[b];
    dick[c] = dick.get(c, 0) + k;
    ans -= k*b; ans += k*c;
    print(ans);

Solution (Python):
import collections

def list_count(l):
    return collections.Counter(l)


n=int(input())
a=list(map(int,input().split()))
a_val_list=list_count(a)
a_sum=sum(a)

q=int(input())

for i in range(q):
    b,c=map(int,input().split())
    b_val=a_val_list.get(b, 0)
    a_val_list[b]=0
    a_sum-=b*b_val

    a_val_list[c]=a_val_list.get(c,0)+b_val
    a_sum+=c*b_val

    print(a_sum)

Solution (Python):
n = int(input())
a = [int(i) for i in input().split()]
aa = [0]*(10**5+1)
for i in a:
    aa[i-1]+=1

q= int(input())
s = sum(a)
l = []

for i in range(q):
    b,c =map(int,input().split())
    if aa[b-1]>0:
        aa[c-1]+=aa[b-1]
        s-=b*aa[b-1]
        s+=c*aa[b-1]
        aa[b-1]=0
    l.append(s)

for i in l:
    print(i)

Solution (Python):
import sys
from collections import Counter

N = int(input())
A = list(map(int, sys.stdin.readline().rsplit()))
Q = int(input())
d = dict(Counter(A))
res = sum(A)

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

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

numdic={}
for i in range(10**5):
    numdic[i+1]=0

for a in alist:
    numdic[a] = numdic[a] + 1
    

outsum=sum(alist)

for i in range(q):
    tmpb,tmpc=map(int,input().split())
    tmp = numdic[tmpb]
    outsum += (tmpc-tmpb)*tmp

    print(outsum)
    
    numdic[tmpb]=0
    numdic[tmpc]=numdic[tmpc]+tmp

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

S = sum(A)
D = Counter(A)

for b, c in BC:
    s = c - b
    nb = D[b]
    S += nb * s
    print(S)
    D[b] = 0
    D[c] += nb

Solution (Python):
from collections import Counter
n=int(input())
a=list(map(int, input().split()))
q=int(input())
cou=Counter(a)
arr=list(cou.items())
dic={}
for item in arr:
    dic[item[0]]=item[1]
ans=sum(a)
for _ in range(q):
    b,c=map(int,input().split())
    if not b in dic.keys():
      print(ans)
      continue
    if not c in dic.keys():
      dic[c]=0
    tmpb=dic.pop(b)
    tmpc=dic.pop(c)
    ans+=(c-b)*tmpb
    dic[c]=tmpb+tmpc
    print(ans)

Solution (Python):
from collections import defaultdict


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

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

    for bc in BC:
        tmp = d[bc[0]]
        ans -= tmp * bc[0]
        d[bc[0]] = 0
        ans -= d[bc[1]] * bc[1]
        tmp += d[bc[1]]
        ans += tmp * bc[1]
        d[bc[1]] = tmp
        print(ans)


if __name__ == "__main__":
    main()

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

    ans = sum(a)
    dict_of_digit = {}
    for a_num in a:
        if a_num not in dict_of_digit.keys():
            dict_of_digit[a_num] = 1
        else:
            dict_of_digit[a_num] += 1

    q = int(input())

    for idx in range(q):
        b, c = map(int, input().split())
        if b in dict_of_digit.keys() and dict_of_digit[b] > 0:
            diff = c - b
            ans += diff * dict_of_digit[b]
            if c not in dict_of_digit.keys():
                dict_of_digit[c] = dict_of_digit[b]
            else:
                dict_of_digit[c] += dict_of_digit[b]
            dict_of_digit[b] = 0
        print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import sys
readline = sys.stdin.readline


def st(line):
    tmp = ''
    for l in line:
        if l == '\n':
            yield tmp
        elif l == ' ':
            yield tmp
            tmp = ''
        else:
            tmp += l


def solve():
    N = int(input())
    As = st(readline())

    d = dict()
    total = 0
    for a in As:
        a = int(a)

        if a in d:
            d[a] += 1
        else:
            d[a] = 1
        total += a

    Q = int(input())
    queries = (map(int, readline().strip().split()) for _ in range(Q))

    for que in queries:
        b, c = que

        if b not in d:
            print(total)
            continue

        n_b = d[b]
        d[b] = 0

        if c not in d:
            d[c] = 0

        d[c] += n_b
        total += (c - b) * n_b

        print(total)


def main():
    solve()


if __name__ == "__main__":
    main()

Solution (Python):
import sys
from math import ceil, floor, sqrt, sin, cos, pi
from itertools import accumulate, permutations, combinations
from fractions import gcd 
from collections import deque, Counter
from operator import itemgetter
from heapq import heappop,heappush
sys.setrecursionlimit(10**7)
def lcm(x, y): return ((x * y) // gcd(x, y)) 


lin = [0 for i in range(10**5+1)]
n = int(input())
a = list(map(int, input().split()))
ans = 0
for x in a:
    ans += x
    lin[x] += 1
q = int(input())
for i in range(q):
    b, c = map(int, input().split())
    ans += (c - b)*lin[b]
    lin[c] += lin[b]
    lin[b] = 0
    print(ans)

Solution (Python):


import re
import math
from collections import defaultdict
from collections import deque
import collections
from fractions import Fraction
import bisect
from queue import PriorityQueue
import itertools
from itertools import accumulate
from copy import deepcopy
from collections import Counter
import heapq
import random
import time
import os
import sys
import datetime
from functools import lru_cache
from functools import reduce
readline=sys.stdin.readline
sys.setrecursionlimit(2000000)
alphabet="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Set():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(bool)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        if not self.find(x):
            heapq.heappush(self.heap,x)
            self.dic[x]=True
            self.size+=1

    def remove(self,x):
        if self.find(x):
            self.dic[x]=False
            self.size-=1

    def find(self,x):
        return self.dic[x]
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==False:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class multiset():
    def __init__(self,A=[]):
        self.heap=[]
        self.dic=defaultdict(int)
        self.size=0
        for a in A:self.add(a)
    
    def __str__(self):
        return str(self.heap)
    
    def add(self,x):
        heapq.heappush(self.heap,x)
        self.dic[x]+=1
        self.size+=1

    def remove(self,x):
        if self.dic[x]>0:
            self.dic[x]-=1
            self.size-=1
    
    def count(self,x):
        return self.dic[x]

    def find(self,x):
        return self.dic[x]>0
    
    def top(self):
        while self.heap and self.dic[self.heap[0]]==0:
            heapq.heappop(self.heap)
        if self.heap:return self.heap[0]
        else:return None

    def pop(self):
        ret=None
        if self.heap:
            ret=self.top()
            self.remove(ret)
        return ret
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):
    if b:print("yes")
    else:print("no")
def Yn(b):
    if b:print("Yes")
    else:print("No")
def YN(b):
    if b:print("YES")
    else:print("NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(bbool,ret1,ret2):
    if bbool:return ret1
    else:return  ret2
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def pm(x):
    return x//abs(x)
def inputintlist(): 
    return list(map(int,input().split()))
def inputfloatlist(): 
    return list(map(float,input().split()))
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def getmd(x1,y1,x2,y2):
    return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):
    return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow






N=int(input())
A=inputintlist()
D=defaultdict(int)
for a in A:
    D[a]+=1
ans=0
for a,b in D.items():
    ans+=a*b
Q=int(input())
for a in range(Q):
    b,c=inputintlist()
    cnt=D[b]
    ans-=cnt*b
    ans+=cnt*c
    D[b]=0
    D[c]+=cnt

    print(ans)

Solution (Python):
from sys import stdin, setrecursionlimit
from collections import defaultdict


def main():
    input = stdin.buffer.readline
    n = int(input())
    a = list(map(int, input().split()))
    ans = sum(a)
    dic = defaultdict(int)
    for ai in a:
        dic[ai] += 1
    q = int(input())
    bc = [list(map(int, input().split())) for _ in range(q)]
    for b, c in bc:
        count = dic[b]
        ans += count * (c - b)
        print(ans)
        dic[b] -= count
        dic[c] += count


if __name__ == "__main__":
    setrecursionlimit(10000)
    main()

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
asum = sum(a)
cnt = [0] * (10**5+1)
q = int(input())

for i in a:
    cnt[i] += 1

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

Solution (Python):
from collections import Counter

def main():
    n = int(input())
    a = Counter(map(int, input().split()))
    temp, a = listed(a)
    q = int(input())
    bc = [tuple(map(int, input().split())) for _ in range(q)]
    
    for b, c in bc:
        t = a[b]
        if t == 0:
            print(temp)
            continue
        a[b] = 0
        temp -= b*t
        a[c] += t
        temp += c*t
        print(temp)

def listed(a):
    x = [0] * (10**5 + 1)
    kei = 0
    for i,v in a.items():
        x[i] = v
        kei += i*v
    return kei, x

if __name__ == '__main__':
    main()

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

from collections import Counter
count = Counter(al)

als = sorted(al)
dp = [0]*(10**5+1)
res = sum(als)

for i in range(10**5+1):
    dp[i] =count[i]

for j in range(q):
    a,b = map(int, input().split())
    res += dp[a] * (b-a)
    dp[b] += dp[a]
    dp[a] = 0
    print(res)

Solution (Python):
import collections
n=int(input()) 
a=list(map(int, input().split())) 
q=int(input()) 
b = []
c = []

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

ans = sum(a)
cc = collections.Counter(a)


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

Solution (Python):
from collections import Counter, defaultdict

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

ans = sum(A)
c = Counter(A)

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

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

sm=sum(a)
d=defaultdict(int)
for i in range(n):
    d[a[i]]+=1

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

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

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

s = sum(a)

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

Solution (Python):
n  =int(input())

arr =[int(x) for x in input().split()]
summ = sum(arr)
q = int(input())
from collections import *
count = Counter(arr)
while q:
     q-= 1
    
     b,c = [int(x) for x in input().split()]
     summ += count[b]*c - count[b]*b
    
     count[c] += count[b]
     count[b] = 0
     print(summ)

Solution (Python):
from collections import Counter
import sys


def input(): return sys.stdin.readline().strip()
def I(): return int(input())
def LI(): return list(map(int, input().split()))
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 S(): return input()
def LS(): return input().split()


n = I()
a = LI()
q = I()
bcs = LIR(q)
sum_a = sum(a)
counter = Counter(a)
for b, c in bcs:
    sum_a += c * counter[b] - b * counter[b]
    print(sum_a)
    counter[c] += counter[b]
    counter[b] = 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)]
goukeiti=sum(A)
atai=[0]*(10**5+1)
for i in A:
    atai[i-1]+=1
for i in BC:
    if atai[i[0]-1]!=0:
        kotae=atai[i[0]-1]*i[1]-atai[i[0]-1]*(i[0])
        atai[i[1]-1]+=atai[i[0]-1]
        atai[i[0]-1]=0
        goukeiti+=kotae
        print(goukeiti)
    else:
        print(goukeiti)

Solution (Python):

n=int(input())
arr=list(map(int,input().split()))
sumv=0
d={}
for i in arr:
    sumv+=i
    try:
        d[i]+=1
    except:
        d[i]=1

q=int(input())

while q:
    
    b,c=map(int,input().split())
    if b in d:
        sumv+=(c-b)*d[b]
   
        try:
            d[c]+=d[b]
        except:
            d[c]=d[b]
    d[b]=0
    print(sumv)


    q-=1

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

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

Solution (Python):
import collections

N = int(input())

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

A_count = collections.Counter(A)

Q = int(input())

total = sum(A)

for i in range(Q):
    B, C = map(int, input().split())
    total += C * A_count[B]
    total -= A_count[B] * B

    A_count[C] += A_count[B]
    A_count[B] = 0

    print(total)

Solution (Python):
from collections import Counter
n = int(input())
A = list(map(int, input().split()))
cnt = Counter(A)
ans = sum(A)
q = int(input())
for _ in range(q):
    b, c = map(int, input().split())
    if cnt.get(b) is None:
        alt = 0
    else:
        alt= cnt[b]
        cnt[b] = 0
    cnt[c] += alt
    ans += (c - b) * alt
    
    print(ans)

Solution (Python):
import sys, collections
input = sys.stdin.readline

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

counter = collections.Counter(A)
S = sum(A)
for i, (b, c) in enumerate(BC):
    count = counter[b]
    S += (c-b)*count
    counter[b] -= count
    counter[c] += count
    print(S)

Solution (Python):
import collections
import numpy as np

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

  print(S)