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
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())


def dijkstra_heap(s, edge, n):
    
    d = [10**20] * n
    used = [True] * n 
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d


def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr


def lcm(x, y):
    return (x * y) // gcd(x, y)


def lcm_list(numbers):
    return reduce(lcm, numbers, 1)


def gcd_list(numbers):
    return reduce(gcd, numbers)


def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True



def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P


def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]



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

Solution (Python):
from collections import defaultdict
N = int(input())
A = [int(a) for a in input().split()]
d = defaultdict(int)
for a in A:
    d[a] += 1
Q = int(input())
S = sum(A)
ans = []
for _ in range(Q):
    B, C = map(int, input().split())
    S += d[B] * (C - B)
    ans.append(S)
    d[C] += d[B]
    d[B] = 0
for a in ans:
    print(a)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
from collections import deque

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
     
def main():
    N = I()
    A = LI()
    Q = I()
    d = collections.Counter(A)
    ans = []
    cursum = sum(A)
    for i in range(Q):
        b, c = LI()
        cursum -= b * d[b]
        d[c] += d[b]
        cursum += c * d[b]
        d[b] = 0
        ans.append(cursum)
    for a in ans:
        print(a)


main()

Solution (Python):

from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect


def LI(): return [int(x) for x in sys.stdin.readline().split()]


def I(): return int(sys.stdin.readline())


def LS(): return [list(x) for x in sys.stdin.readline().split()]


def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res


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


sys.setrecursionlimit(1000000)


def main():
    N = I()
    A = LI()
    Q = I()
    BC = [LI() for _ in range(Q)]

    d = defaultdict(int)

    for ai in A:
        d[ai] += 1

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

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


main()

Solution (Python):
import sys, math
input = sys.stdin.readline
rs = lambda: input().strip()
ri = lambda: int(input())
rl = lambda: list(map(int, input().split()))
mod = 10**9 + 7

N = ri()
A = rl()
Q = ri()
queries = []
for i in range(Q):
	q = rl()
	queries.append(q)

import collections

cnt = collections.Counter(A)
s = sum(A)

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

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


num=[]
for i in range(100000+1):
    num.append(0)
for a in As:
    num[a]+=1

sum=0
for number,i in enumerate(num):
    sum+=number*i


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

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

from collections import Counter
N = int(input())
As = list(mapint())
Q = int(input())

S = sum(As)
C = Counter(As)
for _ in range(Q):
    b, c = mapint()
    cnt = C[b]
    S += (c-b)*cnt
    C[b] = 0
    C[c] += cnt
    print(S)

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

r = [0]*(10**5+1)
for i in range(n):
    r[a[i]] += 1
s = sum(a)
for b,c in bc:
    r[c] += r[b]
    s += (c-b)*r[b]
    r[b] = 0
    print(s)

Solution (Python):
import collections
FAST_IO = 1
if FAST_IO:
    import io, sys, atexit
    rr = iter(sys.stdin.read().splitlines()).next
    sys.stdout = _OUTPUT_BUFFER = io.BytesIO()
    @atexit.register
    def write():
        sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
    rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())
 
    
    

N = rri()
arr = rrm()
dic = collections.Counter(arr)
s = sum(arr)
q = rri()
for _ in range(q):
    a, b= rrm()
    s+=dic[a]*(b-a)
    dic[b]+=dic[a]
    del dic[a]
    print(s)

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

def solve():
    N = int(readline())
    A = list(map(int, readline().split()))
    Q = int(readline())
    BC = [list(map(int, readline().split())) for i in range(Q)]

    count = {}
    for a in A:
        count[a] = count.get(a, 0) + 1
    
    s = sum(A)

    for b, c in BC:
        if b in count:
            nb = count[b]
            diff = (c - b) * nb
            s += diff
            print(s)

            del count[b]
            count[c] = count.get(c, 0) + nb
        else:
            print(s)


solve()

Solution (Python):
import collections

n = int(input())
a = list(map(int, input().split()))
count = collections.Counter(a)
ans = sum(a)

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

Solution (Python):
"""
~~ Author : Bhaskar
~~ Dated : 10~06~2020
"""

import sys
from bisect import *
from math import floor,sqrt,ceil,factorial as F,gcd,pi
from itertools import chain,combinations,permutations,accumulate
from collections import Counter,defaultdict,OrderedDict,deque
from array import array
INT_MAX = sys.maxsize
INT_MIN = -(sys.maxsize)-1
mod = 1000000007
ch = "abcdefghijklmnopqrstuvwxyz"
lcm = lambda a,b : (a*b)//gcd(a,b)
setbit = lambda x : bin(x)[2:].count("1")
input = lambda : sys.stdin.readline()

def solve():
    n = int(sys.stdin.readline())
    a = list(map(int, sys.stdin.readline().split()))
    d = Counter(a)
    s = sum(a)
    q = int(sys.stdin.readline())
    for _ in range(q):
        b, c = map(int, sys.stdin.readline().split())
        s += d[b]*c - d[b]*b
        d[c] += d[b]
        d[b] = 0
        print(s) 


if __name__ == "__main__":
    try:
        sys.stdin = open('input.txt','r')
        sys.stdout = open('output.txt','w')
    except:
       pass
    solve()

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

cnt={}
for i in a:
  if i in cnt:
    cnt[i]+=1
  else:
    cnt[i]=1
s=0
for i in cnt:
  s+=i*cnt[i]
  
for i in ql:
  if i[0] in cnt:
    s+=(i[1]-i[0])*cnt[i[0]]
    if i[1] in cnt:
      cnt[i[1]]+=cnt[i[0]]
    else:
      cnt[i[1]]=cnt[i[0]]
    cnt[i[0]]=0
  print(s)

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


def read():
    N = int(input().strip())
    A = list(map(int, input().strip().split()))
    Q = int(input().strip())
    BC = []
    for i in range(Q):
        b, c = map(int, input().strip().split())
        BC.append((b, c))
    return N, A, Q, BC


def solve(N, A, Q, BC):
    D = Counter(A)
    ans = sum(A)
    for b, c in BC:
        if D[b] > 0:
            v = D[b]
            ans -= b * v
            D[b] = 0
            D[c] += v
            ans += c * v
        print(ans)


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
C = (10**5+1)*[0]
T = sum(A)

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

for q in range(Q):
  b,c = map(int,input().split())
  T+=C[b]*(c-b)
  C[c]+=C[b]
  C[b]=0
  print(T)

Solution (Python):
N=int(input())
A=[int(i) for i in input().split()]
Q=int(input())
B=[0 for i in range(Q)]
C=[0 for i in range(Q)]
for i in range(Q):
    B[i],C[i]=map(int,input().split())
D=dict()
for i in range(N):
    if A[i] in D:
        D[A[i]]+=1
    else:
        D[A[i]]=1
S=sum(A)
for i in range(Q):
    if not(B[i] in D):
        print(S)
        continue
    tmp=D[B[i]]
    D[B[i]]=0
    if C[i] in D:
        D[C[i]]+=tmp
    else:
        D[C[i]]=tmp
    S=S+(C[i]-B[i])*tmp
    print(S)

Solution (Python):
import sys
from collections import Counter

input = sys.stdin.readline


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

    c = Counter(A)
    d = dict(c.items())
    S = sum(k * v for k, v in c.items())
    for B, C in BC:
        if B in d:
            v = d[B]
            if C in d:
                d[C] += v
            else:
                d[C] = v
            d[B] = 0
            S = S + (C - B) * v
        print(S)


if __name__ == "__main__":
    main()

Solution (Python):

import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from collections import deque
from functools import lru_cache
import bisect
import re
import queue
import decimal


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [Scanner.string() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [Scanner.int() for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True

    @staticmethod
    def fact(N):
        res = {}
        tmp = N
        for i in range(2, int(N ** 0.5 + 1) + 1):
            cnt = 0
            while tmp % i == 0:
                cnt += 1
                tmp //= i
            if cnt > 0:
                res[i] = cnt
        if tmp != 1:
            res[tmp] = 1
        if res == {}:
            res[N] = 1
        return res


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


MOD = int(1e09) + 7
INF = int(1e15)


def solve():
    N = Scanner.int()
    D = [0 for _ in range(10 ** 5 + 10)]
    A = Scanner.map_int()
    for a in A:
        D[a] += 1
    S = sum(A)
    Q = Scanner.int()
    for _ in range(Q):
        b, c = Scanner.map_int()
        x = D[b] * b
        S -= x
        y = D[b] * c
        D[c] += D[b]
        D[b] = 0
        S += y
        print(S)


def main():
    
    
    
    
    
    solve()


if __name__ == "__main__":
    main()

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
count=[0]*(10**5)
total=sum(A)
for a in A:
    count[a-1]+=1
Q=int(input())
for q in range(Q):
    B,C=map(int,input().split())
    total+=count[B-1]*(C-B)
    if count[B-1]!=0:
        count[C-1]+=count[B-1]
        count[B-1]=0
    print(total)

Solution (Python):
from collections import Counter
N = int(input())
As = list(map(int, input().split()))
counter = Counter(As)
ans = 0
for k,v in counter.items():
  ans += k*v

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

Solution (Python):
from collections import Counter
N = int(input())
A = list(map(int, input().split()))
cnt = Counter(A)

res = 0
for k, v in cnt.items():
    res += k*v

for _ in range(int(input())):
    B, C = map(int, input().split())
    res -= cnt[B]*B
    res += cnt[B]*C

    cnt[C] += cnt[B]
    cnt[B] = 0
    print(res)

Solution (Python):
import sys
from collections import Counter
input = sys.stdin.readline
N = int(input())
A = [int(i) for i in input().split()]
Q = int(input())
BC = [[int(i) for i in input().split()] for _ in range(Q)]

S = sum(A)
C = Counter(A)
for b, c in BC:
    if b in C:
        if c not in C:
            C[c] = 0
        C[c] += C[b]
        S += (c-b)*C[b]
        C[b] = 0
    print(S)

Solution (Python):
n = int(input())
A = tuple(map(int, input().split()))
sa = sum(A)

from collections import Counter
AC = dict(Counter(A))
Q = int(input())
for _ in range(Q):
    f, to = map(int, input().split())
    if f in AC:
        fcount = AC.pop(f)
        AC.setdefault(to, 0)
        AC[to] += fcount
        sa += fcount*(to-f)
    print(sa)

Solution (Python):
def main():
    N = int(input())
    dic = {}
    for i in range(10**5+10):
        dic[i]=0
    
    s=0
    l = [int(x) for x in input().split()]
    for a in l:
        dic[a]+=1
        s+=a
    ans=[]
    Q = int(input())
    for i in range(Q):
        b,c = map(int,input().split())
        b_num = dic[b]
        dic[b]=0
        dic[c]+=b_num
        s = s + (c-b)*b_num
        ans.append(s)
    for i in ans:
        print(i)
    
main()

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

Solution (Python):

import sys
from collections import Counter as cl

def solve(N: int, A: "List[int]", Q: int, B: "List[int]", C: "List[int]"):
    d = [0]*(10**5)
    for ai in A:
        d[ai-1] +=1

    ans = 0
    for i, di in enumerate(d):
        ans += di*(i+1)

    for bi, ci in zip(B,C):
        t_ = d[bi-1]
        ans = ans - bi*t_ + ci*t_
        d[ci-1] += t_
        d[bi-1] = 0
        print(ans)




    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    A = [int(next(tokens)) for _ in range(N)]  
    Q = int(next(tokens))  
    B = [int()] * (Q)  
    C = [int()] * (Q)  
    for i in range(Q):
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, A, Q, B, C)

if __name__ == '__main__':
    main()

Solution (Python):
from collections import Counter

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

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

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

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

from collections import Counter
C = Counter(A)
C = dict(C)
S = sum(A)
for i in range(q):
    b, c = map(int, input().split())
    if b in C:
        vb = C[b]
        C[b] = 0
        S -= b*vb
        S += c*vb
        print(S)
        if c in C:
            C[c] += vb
        else:
            C[c] = vb
    else:
        print(S)

Solution (Python):

N = int(input())

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

dic = {}

s = sum(A)
for i in A:
    if i not in dic:
        dic[i] = 1
    else:
        dic[i] += 1
        

Q = int(input())

for i in range(Q):

    B,C = map(int,input().split())

    if B not in dic:
        pass
    else:

        s -= dic[B] * B
        s += dic[B] * C

        if C not in dic:
            dic[C] = 0

        dic[C] += dic[B]
        dic[B] = 0

    print (s)

Solution (Python):
from collections import Counter

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
queries = []
for i in range(Q):
    Bi, Ci = map(int, input().split())
    queries.append((Bi, Ci))

S = sum(A)
c = Counter(A)
for Bi, Ci in queries:
    S += (Ci - Bi) * c[Bi]
    print(S)
    c.update({Bi: -c[Bi], Ci: c[Bi]})

Solution (Python):
import sys
from collections import Counter

sys.setrecursionlimit(10 ** 7)
rl = sys.stdin.readline


def solve():
    N = int(rl())
    A = list(map(int, rl().split()))
    Q = int(rl())
    B, C = [0] * Q, [0] * Q
    for i in range(Q):
        B[i], C[i] = map(int, rl().split())
    
    counter = Counter(A)
    sum_a = sum(A)
    ans = []
    for b, c in zip(B, C):
        sum_a -= counter[b] * b
        sum_a += counter[b] * c
        counter[c] += counter[b]
        counter[b] = 0
        ans.append(sum_a)
    print(*ans, sep='\n')


if __name__ == '__main__':
    solve()

Solution (Python):
n = int(input())
a = list(map(int, input().strip().split()))
q = int(input())
MAX = 1000000 + 1
p = [0] * MAX
si = 0
for i in range(n):
    p[a[i]] += 1
    si += a[i]

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

    if p[b] > 0:
        si = si - b * p[b] + c * p[b]
        p[c] += p[b]
        p[b] = 0

    ans.append(si)

for i in range(q):
    print(ans[i])

Solution (Python):
from math import gcd, sqrt, cos, radians, pi
from collections import defaultdict as d

n = int(input())
tab = list(map(int, input().split()))
S = sum(tab)
dico = d(int)
for i in tab:
	dico[i] += 1
q = int(input())
for i in range(q):
	b, c = map(int, input().split())
	s = S - (b * dico[b]) + (c * dico[b])
	dico[c] += dico[b]
	dico[b] = 0
	S = s
	print(S)

Solution (Python):
import sys
input=sys.stdin.readline
n=int(input())
a=list(map(int,input().split()))
d={}
s=0
for i in a:
    s+=i
    if i in d:
        d[i]+=1
    else:
        d[i]=1
q=int(input())
for _ in range(q):
    b,c=map(int,input().split())
    if b in d:
        x=d[b]
        s=s-b*x+c*x
        d[b]=0
        if c in d:
            d[c]+=x
        else:
            d[c]=x
    print(s)

Solution (Python):
import sys
import collections

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    cnt = collections.Counter(A)

    ans = sum(A)

    for b, c in BC:
        ans -= cnt[b] * b
        cnt[c] += cnt[b]
        ans += cnt[b] * c
        cnt[b] = 0

        print(ans)




if __name__ == '__main__':
    main()

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

SA = sum(A)
CA = [0]*(10**5+1)
for i in range(N):
    CA[A[i]]+=1

for i in range(Q):
    B,C = list(map(int,input().split()))
    NB = CA[B]
    NC = CA[C]
    SA = SA - NB*B + NB*C
    CA[B] = 0
    CA[C] += NB
    print(SA)

Solution (Python):
from collections import defaultdict
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
BC = [list(map(int,input().split())) for i in range(Q)]

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

ans = sum(A)

for b,c in BC:
    t = dic[b]
    ans -= b*t
    dic[b] = 0
    dic[c] += t
    ans += c*t
    print(ans)

Solution (Python):
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
sumA = sum(A)
numlist = [0]*(10**5 + 1)
for Aele in A:
    numlist[Aele] += 1
for i in range(Q):
    (B,C) = map(int,input().split())
    Bs = numlist[B]
    sumA = sumA + C*Bs - B*Bs
    numlist[B] = 0
    numlist[C] += Bs
    print(sumA)

Solution (Python):
n=int(input())
A=list(map(int,input().split()))
q=int(input())
from collections import defaultdict
d=defaultdict(int)
for i in range(n):  
  d[A[i]]+=1

ans=sum(A)

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

Solution (Python):
from collections import defaultdict
N = int(input())
A = list(map(int,input().split()))
ans = sum(A)
dic = defaultdict(int) 
for num in A:
  dic[num] += 1

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

Solution (Python):
from collections import Counter

n = int(input())
A = list(map(int, input().split()))
ans = sum(A)
C = Counter(A)
q = int(input())
for _ in range(q):
    b, c = map(int, input().split())
    if b in C:
        C[c] += C[b]
        ans += (c - b) * C[b]
        C[b] = 0
    print(ans)

Solution (Python):
import sys
readline = sys.stdin.readline
from collections import Counter


def main():
    N = int(readline())
    A = list(map(int, readline().rstrip().split()))
    counter = Counter(A)
    res = sum(A)

    Q = int(readline())
    for _ in range(Q):
        b, c = map(int, readline().rstrip().split())
        res = res - b * counter[b] + c * counter[b]
        counter.setdefault(c, 0)
        counter[c] += counter[b]
        counter.setdefault(b, 0)
        counter[b] = 0

        print(res)
        

if __name__ == '__main__':
    main()

Solution (Python):
import sys

import math
import collections

import bisect
import itertools
import fractions

import copy

import decimal

import queue



sys.setrecursionlimit(10000001)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))



def main():
    n = ni()
    a = na()
    q = ni()

    cnt = collections.Counter(a)

    total = sum(a)
    for _ in range(q):
        b, c = ns()

        if c in cnt.keys():
            cnt[c] += cnt[b]
        else:
            cnt[c] = cnt[b]
        total += (c - b) * cnt[b]
        cnt[b] = 0

        print(total)

if __name__ == '__main__':
    main()

Solution (Python):

from sys import stdin
input = stdin.readline
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True 
BIG = 10**18
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = inn()
a = inl()
q = inn()
h = {}
for x in a:
    if x not in h:
        h[x] = 0
    h[x] += 1
sm = sum(a)
for i in range(q):
    b,c = inm()
    if b not in h:
        print(sm)
    else:
        sm += h[b]*(c-b)
        if c not in h:
            h[c] = 0
        h[c] += h[b]
        h[b] = 0
        print(sm)

Solution (Python):
n=int(input())
A=[int(i) for i in input().split()]
q=int(input())

tab=[0 for i in range(10**5+1)]

s=0
for ele in A:
    tab[ele]+=1
    s+=ele

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

Solution (Python):
import sys
input = sys.stdin.readline
from collections import Counter
def main():
    N = int(input())
    A = list(map(int, input().split()))
    cnt = Counter(A)
    total = sum(A)
    Q = int(input())
    for _ in range(Q):
        B, C = map(int, input().split())
        total = total + (C - B) * cnt[B]
        cnt[C] += cnt[B]
        cnt[B] = 0
        print(total)
if __name__ == "__main__":
    main()

Solution (Python):
def main():
    import sys
    from collections import Counter
    input = sys.stdin.readline
    N = int(input())
    A = Counter([int(x) for x in input().strip().split()])
    Q = int(input())
    ans = sum([k * v for k, v in A.items()])
    for q in range(Q):
        b, c = [int(x) for x in input().strip().split()]
        ans = ans + c * A[b] - b * A[b] 
        A[c] += A[b]
        A[b] = 0
        print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import defaultdict
input = lambda: sys.stdin.readline().rstrip()

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

d = defaultdict(lambda: 0)
ans = 0
for v in a:
   d[v] += 1
   ans += v
for i in range(q):
   b, c = bc[i]
   if b > c:
      ans -= (b - c) * d[b]
   else:
      ans += (c - b) * d[b]
   d[c] += d[b]
   d[b] = 0
   print(ans)

Solution (Python):
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10 ** 8)
from itertools import accumulate
from itertools import permutations
from itertools import combinations
from collections import defaultdict
from collections import Counter
import fractions
import math
from collections import deque
from bisect import bisect_left
from bisect import bisect_right
from bisect import insort_left
import itertools
from heapq import heapify
from heapq import heappop
from heapq import heappush
import heapq
from copy import deepcopy
from decimal import Decimal
alf = list("abcdefghijklmnopqrstuvwxyz")
ALF = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

INF = float("inf")


d = defaultdict(int)
N = int(input())
A = list(map(int,input().split()))
s = 0
ans = []
for i in range(N):
    a = A[i]
    s += a
    d[a] += 1
Q = int(input())
for i in range(Q):
    B,C = map(int,input().split())
    if d[B] == 0:
        ans.append(s)
    else:
        num = d[B]
        d[B] = 0
        d[C] += num
        s += C*num
        s -= B*num
        ans.append(s)
for i in ans:
    print(i)

Solution (Python):
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()

def main():
    N=ii()
    A = list(mi())

    counter = [0]*(10**5+5)

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

    ans = sum(A)

    Q=ii()
    for q in range(Q):
        B,C=mi()
        ans -= B * counter[B]
        ans += C * counter[B]

        counter[C] += counter[B]
        counter[B] = 0
        print(ans)




if __name__ == "__main__":
  main()