Problem:


Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

 1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5} 

 B_{i} \neq C_{i} 

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

4
1 2 3 4
3
1 2
3 4
2 4

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

4
1 1 1 1
3
1 2
2 1
3 5

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000



Sample input:
4
1 2 3 4
3
1 2
3 4
2 4


Sample output:
11
12
16

Submission status: Accepted

Solution code:
from collections import Counter

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

cntA = Counter(A)

ans = sum(A)

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

    ans += cntA[B]*(C - B)
    cntA[C] += cntA[B]
    cntA[B] = 0
    
    print(ans)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import Counter

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

counter = Counter(a)
sum_res = sum(a)

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

  sum_res += (c - b) * counter[b]

  counter[c] += counter[b]
  counter[b] =0

  print(sum_res)

Submission status: Accepted

Solution code:
import collections

N = int(input())
a = list(map(int,input().split()))
Q = int(input())
ans = sum(a)
a = collections.Counter(a)

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

Submission status: Accepted

Solution code:
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction

mod = 10 ** 9 + 7
mod1 = 998244353

# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")


# -------------------game starts now----------------------------------------------------import math
class TreeNode:
    def __init__(self, k, v):
        self.key = k
        self.value = v
        self.left = None
        self.right = None
        self.parent = None
        self.height = 1
        self.num_left = 1
        self.num_total = 1


class AvlTree:

    def __init__(self):
        self._tree = None

    def add(self, k, v):
        if not self._tree:
            self._tree = TreeNode(k, v)
            return
        node = self._add(k, v)
        if node:
            self._rebalance(node)

    def _add(self, k, v):
        node = self._tree
        while node:
            if k < node.key:
                if node.left:
                    node = node.left
                else:
                    node.left = TreeNode(k, v)
                    node.left.parent = node
                    return node.left
            elif node.key < k:
                if node.right:
                    node = node.right
                else:
                    node.right = TreeNode(k, v)
                    node.right.parent = node
                    return node.right
            else:
                node.value = v
                return

    @staticmethod
    def get_height(x):
        return x.height if x else 0

    @staticmethod
    def get_num_total(x):
        return x.num_total if x else 0

    def _rebalance(self, node):

        n = node
        while n:
            lh = self.get_height(n.left)
            rh = self.get_height(n.right)
            n.height = max(lh, rh) + 1
            balance_factor = lh - rh
            n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
            n.num_left = 1 + self.get_num_total(n.left)

            if balance_factor > 1:
                if self.get_height(n.left.left) < self.get_height(n.left.right):
                    self._rotate_left(n.left)
                self._rotate_right(n)
            elif balance_factor < -1:
                if self.get_height(n.right.right) < self.get_height(n.right.left):
                    self._rotate_right(n.right)
                self._rotate_left(n)
            else:
                n = n.parent

    def _remove_one(self, node):
        """
        Side effect!!! Changes node. Node should have exactly one child
        """
        replacement = node.left or node.right
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = replacement
            else:
                node.parent.right = replacement
            replacement.parent = node.parent
            node.parent = None
        else:
            self._tree = replacement
            replacement.parent = None
        node.left = None
        node.right = None
        node.parent = None
        self._rebalance(replacement)

    def _remove_leaf(self, node):
        if node.parent:
            if AvlTree._is_left(node):
                node.parent.left = None
            else:
                node.parent.right = None
            self._rebalance(node.parent)
        else:
            self._tree = None
        node.parent = None
        node.left = None
        node.right = None

    def remove(self, k):
        node = self._get_node(k)
        if not node:
            return
        if AvlTree._is_leaf(node):
            self._remove_leaf(node)
            return
        if node.left and node.right:
            nxt = AvlTree._get_next(node)
            node.key = nxt.key
            node.value = nxt.value
            if self._is_leaf(nxt):
                self._remove_leaf(nxt)
            else:
                self._remove_one(nxt)
            self._rebalance(node)
        else:
            self._remove_one(node)

    def get(self, k):
        node = self._get_node(k)
        return node.value if node else -1

    def _get_node(self, k):
        if not self._tree:
            return None
        node = self._tree
        while node:
            if k < node.key:
                node = node.left
            elif node.key < k:
                node = node.right
            else:
                return node
        return None

    def get_at(self, pos):
        x = pos + 1
        node = self._tree
        while node:
            if x < node.num_left:
                node = node.left
            elif node.num_left < x:
                x -= node.num_left
                node = node.right
            else:
                return (node.key, node.value)
        raise IndexError("Out of ranges")

    @staticmethod
    def _is_left(node):
        return node.parent.left and node.parent.left == node

    @staticmethod
    def _is_leaf(node):
        return node.left is None and node.right is None

    def _rotate_right(self, node):
        if not node.parent:
            self._tree = node.left
            node.left.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.left
            node.left.parent = node.parent
        else:
            node.parent.right = node.left
            node.left.parent = node.parent
        bk = node.left.right
        node.left.right = node
        node.parent = node.left
        node.left = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    def _rotate_left(self, node):
        if not node.parent:
            self._tree = node.right
            node.right.parent = None
        elif AvlTree._is_left(node):
            node.parent.left = node.right
            node.right.parent = node.parent
        else:
            node.parent.right = node.right
            node.right.parent = node.parent
        bk = node.right.left
        node.right.left = node
        node.parent = node.right
        node.right = bk
        if bk:
            bk.parent = node
        node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
        node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
        node.num_left = 1 + self.get_num_total(node.left)

    @staticmethod
    def _get_next(node):
        if not node.right:
            return node.parent
        n = node.right
        while n.left:
            n = n.left
        return n
avl=AvlTree()
#-----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
    def __init__(self, data, default='z', func=lambda a, b: min(a ,b)):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)


# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
    def __init__(self, data, default=0, func=lambda a, b: a * a + b * b):
        """initialize the segment tree with data"""
        self._default = default
        self._func = func
        self._len = len(data)
        self._size = _size = 1 << (self._len - 1).bit_length()

        self.data = [default] * (2 * _size)
        self.data[_size:_size + self._len] = data
        for i in reversed(range(_size)):
            self.data[i] = func(self.data[i + i], self.data[i + i + 1])

    def __delitem__(self, idx):
        self[idx] = self._default

    def __getitem__(self, idx):
        return self.data[idx + self._size]

    def __setitem__(self, idx, value):
        idx += self._size
        self.data[idx] = value
        idx >>= 1
        while idx:
            self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
            idx >>= 1

    def __len__(self):
        return self._len

    def query(self, start, stop):
        if start == stop:
            return self.__getitem__(start)
        stop += 1
        start += self._size
        stop += self._size

        res = self._default
        while start < stop:
            if start & 1:
                res = self._func(res, self.data[start])
                start += 1
            if stop & 1:
                stop -= 1
                res = self._func(res, self.data[stop])
            start >>= 1
            stop >>= 1
        return res

    def __repr__(self):
        return "SegmentTree({0})".format(self.data)


# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorials = [1, 1]
        self.invModulos = [0, 1]
        self.invFactorial_ = [1, 1]

    def calc(self, n):
        if n <= -1:
            print("Invalid argument to calculate n!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.factorials):
            return self.factorials[n]
        nextArr = [0] * (n + 1 - len(self.factorials))
        initialI = len(self.factorials)
        prev = self.factorials[-1]
        m = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = prev * i % m
        self.factorials += nextArr
        return self.factorials[n]

    def inv(self, n):
        if n <= -1:
            print("Invalid argument to calculate n^(-1)")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        p = self.MOD
        pi = n % p
        if pi < len(self.invModulos):
            return self.invModulos[pi]
        nextArr = [0] * (n + 1 - len(self.invModulos))
        initialI = len(self.invModulos)
        for i in range(initialI, min(p, n + 1)):
            next = -self.invModulos[p % i] * (p // i) % p
            self.invModulos.append(next)
        return self.invModulos[pi]

    def invFactorial(self, n):
        if n <= -1:
            print("Invalid argument to calculate (n^(-1))!")
            print("n must be non-negative value. But the argument was " + str(n))
            exit()
        if n < len(self.invFactorial_):
            return self.invFactorial_[n]
        self.inv(n)  # To make sure already calculated n^-1
        nextArr = [0] * (n + 1 - len(self.invFactorial_))
        initialI = len(self.invFactorial_)
        prev = self.invFactorial_[-1]
        p = self.MOD
        for i in range(initialI, n + 1):
            prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
        self.invFactorial_ += nextArr
        return self.invFactorial_[n]


class Combination:
    def __init__(self, MOD):
        self.MOD = MOD
        self.factorial = Factorial(MOD)

    def ncr(self, n, k):
        if k < 0 or n < k:
            return 0
        k = min(k, n - k)
        f = self.factorial
        return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD


# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
    if a == 1 or n == 0:
        return 1
    if n % 2 == 0:
        s = powm(a, n // 2, m)
        return s * s % m
    else:
        return a * powm(a, n - 1, m) % m


# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
    zipped_pairs = zip(list2, list1)

    z = [x for _, x in sorted(zipped_pairs)]

    return z


# --------------------------------------------------product----------------------------------------
def product(l):
    por = 1
    for i in range(len(l)):
        por *= l[i]
    return por


# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
    left = 0
    right = n - 1

    count = 0

    while (left <= right):
        mid = int((right + left)/ 2)

        # Check if middle element is
        # less than or equal to key
        if (arr[mid]<=key):
            count = mid+1
            left = mid + 1

        # If key is smaller, ignore right half
        else:
            right = mid - 1

    return count


# --------------------------------------------------binary----------------------------------------
def countdig(n):
    c = 0
    while (n > 0):
        n //= 10
        c += 1
    return c


def countGreater( arr,n, k):
    l = 0
    r = n - 1

    # Stores the index of the left most element
    # from the array which is greater than k
    leftGreater = n

    # Finds number of elements greater than k
    while (l <= r):
        m = int(l + (r - l) / 2)
        if (arr[m] >= k):
            leftGreater = m
            r = m - 1

        # If mid element is less than
        # or equal to k update l
        else:
            l = m + 1

    # Return the count of elements
    # greater than k
    return (n - leftGreater)


# --------------------------------------------------binary------------------------------------
n=int(input())
l=list(map(int,input().split()))
d=defaultdict(int)
for i in range(n):
    d[l[i]]+=1
s=sum(l)
for i in range(int(input())):
    b,c=map(int,input().split())
    s+=d[b]*c-d[b]*b
    print(s)
    d[c]+=d[b]
    d[b]=0

Submission status: Accepted

Solution code:
from collections import Counter

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

ans = sum(A)

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

Submission status: Accepted

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

lst = collections.Counter(A)

Q = int(input())

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

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

for i in ans:
    print(i)

Submission status: Accepted

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

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

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

Submission status: Accepted

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

ans = sum(a)
from collections import Counter
cnt = Counter(a)

for i, j in s: 
    if j in cnt:
        cnt[j] += cnt[i]
    else:
        cnt[j] = cnt[i]    
    ans = ans - i * cnt[i] + cnt[i] * j
    if i in cnt:
        #cnt.pop(i)
        cnt[i] = 0
    print(ans)

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
 
    n = int(input())
    a = list(map(int, input().split()))
    q = int(input())
    d = [0 for _ in range(10 ** 5)]
    ans = sum(a)
 
    for ai in a:
        d[ai - 1] += 1
 
    for i in range(q):
        bi, ci = map(int, input().split())
        bi_count = d[bi - 1]
        # 操作による差分を操作前の和に加える
        ans += (ci - bi) * bi_count
        print(ans)
        # 操作による要素の差分を操作前の値に加える
        d[ci - 1] += d[bi - 1]
        d[bi - 1] = 0
 
 
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import Counter
n = int(input())

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

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

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

Submission status: Accepted

Solution code:
# 初期入力
from collections import Counter
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
A_c =Counter(A)
Q = int(input())
S =[0]*Q
bc =[]
for i in range(Q):
    x,y = (int(i) for i in input().split())
    bc.append((x,y))
    #print(A_np)
sum_A =[0]*(Q+1)
sum_A[0] =sum(A)
ind =0
for k,v in bc:
    sum_A[ind+1] =sum_A[ind] -A_c[k] *k +A_c[k] *v
    A_c[v] +=A_c[k]
    A_c[k] =0
    #print(A_c)
    print(sum_A[ind +1])
    ind +=1

Submission status: Accepted

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

mx = 10**5
table = [0] * (mx + 1)
for i in a:
    table[i] += 1

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

Submission status: Accepted

Solution code:
from collections import Counter

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

b=[0]*q
c=[0]*q
for qq in range(q):
    b[qq] ,c[qq]= map(int,input().split()) 

ans = sum(a)
aa = Counter(a)

# print(aa)

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

Submission status: Accepted

Solution code:
import sys
N = int(input())
A = list(map(int, input().split()))
total = sum(A)
num = [0] * (10 ** 5 + 1)
for a in A:
    num[a] += 1

Q = int(input())
for _ in range(Q):
    b, c = map(int, sys.stdin.readline().split())
    total -= b * num[b]
    total += c * num[b]
    num[c] += num[b]
    num[b] = 0
    print(total)

Submission status: Accepted

Solution code:
import numpy as np

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

counts = np.zeros(100000, dtype=int)

ans = 0

for i in range(len(list_a)):
    counts[list_a[i]-1] += 1
    ans += list_a[i]

q = int(input())

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

    ans += counts[b-1] * (c - b)

    counts[c-1] += counts[b-1]
    counts[b-1] = 0

    print(ans)

Submission status: Accepted

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

from  collections import Counter

dict_a = Counter(a)
s = sum(a)

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

Submission status: Accepted

Solution code:
import collections

N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B_and_C = [list(map(int, input().split())) for _ in range(Q)]
sum_A = sum(A)
collect = collections.Counter(A)
for b_c in B_and_C:
    sum_A -= b_c[0] * collect[b_c[0]]
    if b_c[1] not in collect:
        collect[b_c[1]] = 0
    collect[b_c[1]] += collect[b_c[0]]
    sum_A += b_c[1] * collect[b_c[0]]
    collect[b_c[0]] = 0
    print(sum_A)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N = int(input())
A = [int(x) for x in input().split()]

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

ans = sum(A)

Q = int(input())

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

    ans -= B * cnt[B]
    ans += C * cnt[B]

    cnt[C] += cnt[B]
    cnt[B] = 0

    print(ans)

Submission status: Accepted

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

g = [0]*(10**5+1)
t = sum(a)
s = []

for aj in a:
    g[aj]+=1

for i in range(q):
    b,c = map(int,input().split())
    if g[b] != 0:
        t = t + c*g[b] - b*g[b]
        g[c] = g[c] + g[b]
        g[b] = 0
        s.append(t)
    else:
        s.append(t)

for m in range(q):
    print(s[m])

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
BC = [list(map(int,input().split())) for i in range(Q)]
B, C = [list(i) for i in zip(*BC)]
#print(B,C,BC)

dic = {}
for a in A:
  dic[a] = dic.get(a,0) + 1
#print(dic)

ans = sum(A)
for q in range(Q):
  ans = ans + (C[q]-B[q]) * dic.get(B[q],0)
  dic[C[q]] = dic.get(B[q],0) + dic.get(C[q],0)
  dic.pop(B[q],None)
  print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
BC = [list(map(int,input().split())) for i in range(Q)]
B, C = [list(i) for i in zip(*BC)]
#print(B,C,BC)

dic = {}
for a in A:
  dic[a] = dic.get(a,0) + 1
#print(dic)

ans = sum(A)
for q in range(Q):
  ans = ans + (C[q]-B[q]) * dic.get(B[q],0)
  dic[C[q]] = dic.get(B[q],0) + dic.get(C[q],0)
  dic[B[q]] = 0
  print(ans)

Submission status: Accepted

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

L = [0] * (10**5+1)
for aa in a:
    L[aa] += 1
for _ in range(q):
    b, c = list(map(int, input().split()))
    L[c] += L[b]
    s += L[b] * (c-b)
    L[b] = 0
    print(s)

Submission status: Accepted

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

counter = Counter(a)
sum_res = sum(a)

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

    counter[c] += counter[b]
    counter[b] = 0
    print(sum_res)

Submission status: Accepted

Solution code:
from collections import Counter 
N = int(input())
Alist = list(map(int,input().split()))
num = ['NU'] + [0] * 100000
ans = sum(Alist)
cnt = Counter(Alist)
Q = int(input())

for i in range(1,100001):
    num[i] = cnt[i]

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