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: Runtime Error

Solution code:


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

n = int(input())
a = list(map(int, input().split()))
for i in range(int(input())):
    x, y = map(int, input().split())
    for b in range(len(a)):
        if a[b] == x:
            a[b] = y
    print(sum(a))

Submission status: Runtime Error

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


for _ in range(Q):
  b,c=map(int,input().split())
  time = A.count(b)
  if(b != 0):
    place = A.index(b)
    for i in range(time):
      A[place + i] = c
    A.sort()
  print(sum(A))

Submission status: Runtime Error

Solution code:

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

n = int(input())
a = list(map(int, input().split()))
for i in range(int(input())):
    x, y = map(int, input().split())
    for b in range(len(a)):
        if a[b] == x:
            a[b] = y
    print(sum(a))

Submission status: Runtime Error

Solution code:
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")

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)


def input(): return sys.stdin.readline().rstrip("\r\n")

n = int(input())
a = list(map(int, input().split()))
for i in range(int(input())):
    x, y = map(int, input().split())
    for b in range(len(a)):
        if a[b] == x:
            a[b] = y
    print(sum(a))

Submission status: Runtime Error

Solution code:
N = int(input())
A = np.array(list(map(int,input().split(" "))))
Q = int(input())
B = [list(map(int,input().split(" "))) for i in range(0,Q)]

for i in range(0,Q):
    index = [j for j, x in enumerate(A) if x == B[i][0]]
    A[index] = B[i][1]
    print(sum(A))
#print("\n".join(list(map(str,A.tolist()))))

Submission status: Runtime Error

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

q = int(input())
ans = sum(arr)

hashmap = {}
for val in arr:
    if val in hashmap:
        hashmap[val] += 1
    else:
        hashmap[val] = 1


while q > 0:
    print(hashmap)
    [x, y] =  [int(x) for x in input().split()]
    if x in hashmap:
        if y in hashmap:
            hashmap[y] += hashmap[x]
            ans -= hashmap[x]*x
            ans += y*hashmap[x]
        else:
            diff = hashmap[x] * x
            ans -= diff
            hashmap[y] = hashmap[x]
            del hashmap[x]
            add = hashmap[y] * y
            ans += add
        
    print(ans)
    q -=1

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;

int main() {
  int n,q,s,t;
  cin >> n;
  vector<int> a(n);
  s = 0;
  for (int i=0; i<n; i++) {
    cin >> t;
    a.at(i) = t;
    s += t;
  }
  cin >> q;
  int b,c,d;
  
  for (int i=0; i<q; i++) {
    cin >> b >> c;
    d = c - b;
    for (int j=0; j<n; j++) {
      if (a.at(j) == b) {
        s += d;
        a.at(j) = c;
      }
    }
    cout << s << endl;
  }
}

Submission status: Runtime Error

Solution code:
N = int(input())
A = np.array(list(map(int,input().split(" "))))
Q = int(input())
B = [list(map(int,input().split(" "))) for i in range(0,Q)]

for i in range(0,Q):
    index = [j for j, x in enumerate(A) if x == B[i][0]]
    A[index] = B[i][1]
    print(np.sum(A))
#print("\n".join(list(map(str,A.tolist()))))

Submission status: Runtime Error

Solution code:


import collections

n = int(input())
a = list(map(int, input().split(" ")))
q = int(input())
have_map = collections.Counter(a)
cost_map = { k:k for k in have_map.keys() }
for i in range(q):
    x, y = map(int, input().split(" "))
    have_map[y] = have_map.get(x, 0) + have_map.get(y, 0)
    have_map.pop(x, 0)

    cost = 0
    for k,v in have_map.items():
        cost += cost_map[k] * v
    print(cost)

Submission status: Runtime Error

Solution code:
input()
a = list(map(int, input()))
b = int(input())
for i in range(b):
  c = list(map(int, input()))
  for d, n in enumerate(a):
    if n == c[0]:
      a[d] == c[1]
  f = 0
  for e in a:
    f += e
  print(f)

Submission status: Runtime Error

Solution code:
# import sys
# input = sys.stdin.readline
# import re
# import itertools
import collections

def main():
    n = int(input())
    s = input_list()
    sc = collections.Counter(s)
    q = int(input())
    ans = []
    for i in range(q):
        b, c = input_list()
        sc[c] += sc[b]
        sc.pop(b)
        a = 0
        for k, v in sc.items():
            a += k*v
        ans.append(a)
    for a in ans:
        print(a)


def count_tento(l, cur):
    count = 0
    for v in l:
        if v > cur:
            count += 1
    return count

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

def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N = int(input())
li = list(map(int,input().split()))
Q = int(input())
import bisect
for i in range(Q):
    b,c = map(int,input().split())
    li.sort()
    ind = bisect.bisect_left(li,b)
    if li[ind]==b:
        while li[ind]==b:
          li[ind]=c
          if ind!=N-1:
              ind+=1
          else:
            break;
    print(sum(li))

Submission status: Runtime Error

Solution code:
A = list(map(int, input().split()))
Q = int(input())
ans = []
for i in range(Q):
	b, c = list(map(int, input().split()))
	for j in range(N):
		if A[j] == b:
			A[j] = c

	ans += [sum(A)]
[print(a) for a in ans]

Submission status: Runtime Error

Solution code:
if __name__=='__main__':
    N = int(input())
    A = input().split(" ")
    #A_i = [int(s) for s in A]
    Q=int(input())
    str_list=[]
    S=[]
    for i in range(Q):
        str_list.append(list(input().split()))

    for j in range(Q):
        if str_list[j][0] in A:
            A=[s.replace(str_list[j][0],str_list[j][1]) for s in A]
            A_i = [int(s) for s in A]

        print(sum(A_i))

Submission status: Runtime Error

Solution code:
def resolve():
    N = int(input())
    A = input().split()
    Q = int(input())
    for _ in range(Q):
        b, c = input().split()
        for a in A:
        a.replace(b, c)
    print(sum(map(int, A)))

if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B = []
C = []
for _ in range(Q):
  l = map(int, input().split())
  B.append(l[0])
  C.append(l[1])

for i in range(Q):
  for a in A:
    if a == B[i]:
      a = C[i]
  print(sum(A))

Submission status: Runtime Error

Solution code:
import math
data = input()
num = int(data)
o = input().rstrip().split(" ")
list =[]
for i in o:
    list.append(int(i))
list.sort()
p = input()
times = int(p)
num_count=[list.count(i) for i in range(100000)]
for i in range(times):
    B, C = map(int, input().split(" "))
    a = num_count[B]
    num_count[B] = 0
    num_count[C] += a
    ans = 0
    for i in range(100000):
        ans = ans + (i) * num_count[i]
    print(ans)

Submission status: Runtime Error

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

for i in range(q):
    if l[i][0] in a:
        a = a.replace(l[i][0], l[i][1])
        new_a = a.split()
        new_a = [int(j) for j in new_a]
    print(sum(new_a))

Submission status: Runtime Error

Solution code:
    
n = int(input())
a = list(map(int, input().split()))
for i in range(int(input())):
    x, y = map(int, input().split())
    for b in range(len(a)):
        if a[b] == x:
            a[b] = y
    print(sum(a))



#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


def main():
    pass


# region fastio

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


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

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

# endregion

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
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 = 10**5
    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])

Submission status: Runtime Error

Solution code:
def main():
    nmax = 10000
    n = int(input())
    values = [0] * nmax
    a = [int(v) for v in input().split()]
    for v in a:
        values[v-1] += 1
    asum = sum(a)

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

main()

Submission status: Runtime Error

Solution code:
N=int(input())
A=list(int(x) for x in input().split())
Q=int(input())
X=[list(map(int,input().split())) for i in range(Q)]

for i in range(Q):
	sum=0
	if X[i][0] in A:
		Aaf=[X[i][1] if j==X[i][0] else j for j in A]
		for k in range(N):
			sum+=Aaf[k]
	print(sum)
	A=Aaf

Submission status: Runtime Error

Solution code:
import numpy as np

N = int(input())
A = np.array(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)

m = max(A)+1
res = np.arange(m,dtype=int)
newA = np.zeros((m),dtype=int)


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

for i in range(Q):
    newA[C[i]] += newA[B[i]]
    newA[B[i]] = 0
    print(np.dot(res,newA))

Submission status: Runtime Error

Solution code:
n=int(input())
a=list(map(int,input().split()))
q=int(input())
d=[0]*1000
for i in a:
    d[i-1]+=1
s=0
for num,i in enumerate(d):
    s+=i*(num+1)

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

for b,c in zip(bb,cc):
    k=d[b-1]
    s+=(c-b)*k
    d[b-1]=0
    d[c-1]+=k

    print(s)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

#define endl "\n"
#define INF INT_MAX
#define all(x) x.begin(), x.end()

using namespace std;

typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<vector<int>> matrix;

typedef pair<int, int> pii;
typedef vector<pair<int, int>> vpii;

int main()
{
   ios_base::sync_with_stdio(false);
   cin.tie(nullptr); 

   ll q, n, m, sum = 0, b, c;
   cin >> n;
   multiset<ll> s;
   for (int i = 0; i < n; ++i) {
      cin >> m;
      sum += m;
      s.insert(m);
   }
   cin >> q;
   
   while (q--) {
      cin >> b >> c;
      ll count = s.count(b);
      if (count > 0) {
         s.erase(b);
         for (int i = 0; i < count; ++i) {
            s.insert(c);
         }
         sum -= b*count;
         sum += c*count;
      }
      cout << sum << endl;
   }
    
   return 0;
} //AntiD2ta

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from collections import Counter
from numba import jit

n = int(input())
a = list(map(int, input().split()))
arr = defaultdict(int)
q = int(input())
bc = []
for _ in range(q):
    b, c = map(int, input().split())
    bc.append((b, c))


@jit
def solve(n, a, arr, q, bc):
    for k, v in Counter(a).items():
        arr[k] = v

    q = int(input())

    for b, c in bc:
        arr[c] += arr[b]
        arr[b] = 0
        print(sum([x * y for x, y in arr.items()]))


solve(n, a, arr, q, bc)

Submission status: Runtime Error

Solution code:
N = int(input())	
A_list = list(map(int,input().split()))
Q = int(input())
result = []
for i in range(Q):
        B, C = map(int,input().split())
        A_list = [C if A == B else A for A in A_list]
        print(sum(A_list)

Submission status: Runtime Error

Solution code:
def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    n = int(input())
    A = list(map(int, input().split()))
    q = int(input())
    import numpy as np
    A.sort()
    ans = sum(A)
    for i in range(q):
        b,c = map(int, input().split())
        count = 0
        for j,a in enumerate(A):
            if a == b:
                A[j]=c
                conunt += 1
            elif a > b:
                break
        ans += (c-b)* count
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
a = input()
q = int(input())
for i in range(q):
    b,c = map(str,input().split())
    if b not in a:
        print(sum(x))
        break
    a = a.replace(b,c)
    x = a.split()
    x = [int(s) for s in x]
    print(sum(x))

Submission status: Runtime Error

Solution code:
n = int(input())
list_in = list(map(int, input().split()))
q = int(input())
for i in range(q+1):
    bc = list(map(int, input().split()))
    for j in range(n):
        if list_in[j] == bc[0]:
            list_in[j] = bc[1]
    print(sum(list_in))

Submission status: Runtime Error

Solution code:
N = int(input())
given_list = [str(i) for i in input().split()]
Q = int(input())

for _ in range(Q):
    query = input().split()
    query = [str(i) for i in query]

    B = query[0]
    C = query[1]
    
    if B in given_list:
        given_list_replased = sorted(given_list)
        for i in range(N):
          if given_list_replased[i] == B:
              given_list_replased[i] = C
          elif int(given_list_replased[i]) > int(C):
              break
        given_list_replased = [int(i) for i in given_list_replased]  
        print(sum(given_list_replased)) #####          
    else:
        given_list = [int(i) for i in given_list]  
        print(sum(given_list)) #####
    
    given_list = [str(i) for i in given_list_replased]

Submission status: Runtime Error

Solution code:

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

arg=[0]*(N+5)
for a in A:
    arg[a]+=1
ans=sum(A)
for _ in range(Q):
    a,b=map(int,input().split())
    ans+=arg[a]*(b-a)
    print(ans)
    arg[b]+=arg[a]
    arg[a]=0

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from collections import Counter
from numba import jit

n = int(input())
a = list(map(int, input().split()))
arr = defaultdict(int)
q = int(input())
bc = []
for _ in range(q):
    b, c = map(int, input().split())
    bc.append((b, c))


@jit('void(i8, i8[:], i8[:], i8, i8[:])')
def solve(n, a, arr, q, bc):
    for k, v in Counter(a).items():
        arr[k] = v

    q = int(input())

    for b, c in bc:
        arr[c] += arr[b]
        arr[b] = 0
        print(sum([x * y for x, y in arr.items()]))


solve(n, a, arr, q, bc)

Submission status: Runtime Error

Solution code:
def sum_dict(d, sum, b, c):
    val = 0
    if b in d:
        val = d[b]
        sum -= (b * val)
        del d[b]
        d[c] = d.get(c, 0) + val
        sum += (c * val)
    return sum, d
    
n = int(input())
a = [int(x) for x in input().split()]
d = {}
for i in a:
    d[i] = d.get(i, 0) + 1
s = sum(a)
q = int(input())
for i in range(q):
    b, c = map(int, input().split())
    s, d = sum_dict(d, b, c)
    print(s)

Submission status: Runtime Error

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


q=int(input())
for i in range(q):
  s=0
  b,c=map(int,input().split())
  for j in a:
    if a[j]==b:
      a[j]=c
      s+=a[j]
    else:s+=a[j]
  print(s)

Submission status: Runtime Error

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

m = {}
for i in a:
    if i in m.keys():
        m[i] = m[i] + 1
    else:
        m[i] = 1

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

Submission status: Runtime Error

Solution code:
from collections import Counter
a=list(map(int,input().split()))
s=sum(a)
d=Counter(a)
for i in range(q):
    b,c=map(int,input().split())
    if b in d:
        l=d[b]
        d[b]=0
        d[c]+=l
        s+=(c-b)*l
        print(s)
    else:print(s)

Submission status: Runtime Error

Solution code:
import numpy as np
import sys
N=int(sys.stdin.readline())
A=list(map(int,sys.stdin.readline().split()))
Q=int(sys.stdin.readline())
A=sorted(A)
A=np.array(A)
b=[]
c=[]
for _ in range(Q):
  B,C=map(int,sys.stdin.readline().split())
  b.append(B)
  c.append(C)
for i in range(Q):
  A[A==b[i]]=c[i]
  print(A)
  print(sum(A))

Submission status: Runtime Error

Solution code:
N = int(input())
A = input()
for _ in range(int(input())):
    A.replace(input(), input())
print(sum(map(int, A)))

Submission status: Runtime Error

Solution code:
n = int(input())
a = list(map(int,input().split()))
q = int(input())
for i in range(q):
	b,c = map(int,input().split())
	a[b-1] = a[c-1]
	print(sum(a))

Submission status: Runtime Error

Solution code:
R = lambda: map(int, input().split())
R()
a = [0] * 100001
s = 0
for x in R():
  s += x
  a[x] += 1
q, = R()
for _ in range(q):
  b, c = R()
  s += (c - b) * a[b]
  print(s)
  a[c]+=d[b]
  a[b] = 0

Submission status: Runtime Error

Solution code:
n = int(input())
m = {}
tot = 0
for a in map(int,input().split()):
  tot += m
  if a not in m:
    m[a]=0
  m[a] += 1
q = int(input())
for step in range(q):
  b,c = map(int,input().split())
  if c not in m:
    m[c] = 0
  if b in m:
    m[c] += m[b]
    tot += m[b]*(c-b)
    m[b] = 0
  print(tot)

Submission status: Runtime Error

Solution code:
from collections import Counter

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

L = Counter(a_L)
L = dict(L)
all_sum = sum(a_L)

ans_L = []
for i in range(q):
    b,c = map(int,input().split())
    if L[b] != 0:
        diff = (c-b) * L[b]
        all_sum = all_sum+diff
        L[c] += L[b]
    ans_L.append(all_sum)


for i in ans_L:
    print(i)

Submission status: Runtime Error

Solution code:
N = int(input())
list_A = [int(item) for item in input().split()]
Q = int(input())
list_bc = []
for i in range(Q):
    list_bc.append([int(item) for item in input().split()])

for i in range(Q):
    B = list_bc[i][0]
    C = list_bc[i][1]
    list_A = sorted(list_A)
    # list_A = [C if item == B else item for item in list_A]
    if B in list_A:
        index = list_A.index(B)
    for i in range(index, N):
        if list_A[i] != B:
            continue
        else:
            list_A[i] = C
    print(sum(list_A))

Submission status: Runtime Error

Solution code:
from collections import Counter

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

L = Counter(a_L)
L = dic(L)
all_sum = sum(a_L)

ans_L = []
for i in range(q):
    b,c = map(int,input().split())
    if L[b] != 0:
        diff = (c-b) * L[b]
        all_sum = all_sum+diff
        L[c] += L[b]
    ans_L.append(all_sum)


for i in ans_L:
    print(i)

Submission status: Runtime Error

Solution code:
n = int(input())
a = map(str, input().split())
a = " ".join(a)

m = int(input())
for i in range(m):
               b, c = map(str,input().split())
               #ans = sum([int(i) for i in a])
               a=a.replace(b,c)
               a=a.replace(" ","+")
               
               print(eval(a))

Submission status: Runtime Error

Solution code:
import sys, math

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

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

if(__name__ == "__main__"):

    

    N= int( input().strip() )

    Max = 10**5
    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 = []
    for i in range(N_Queries):
        BC_str =  input().strip().split()
        BC = [ int(BC_str[0]), int(BC_str[1]) ]
        BCs.append(BC)

    for i in range(N_Queries):
        B= BCs[i][0]
        C= BCs[i][1]
        sum = calcSum(AList, B, C, sum)
        print(sum)

Submission status: Runtime Error

Solution code:
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())
    nb = d.pop(b)
    delta = (c-b)*nb
    s += delta
    print(s)
    if c in d:
        d[c] += nb
    else:
        d[c] = nb

Submission status: Runtime Error

Solution code:
n=int(input())
arr=list(map(int,input().strip().split()))
k=int(input())
d=dict()
for i in range(n):
    d[arr[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]*a
    e2=d[b]*b
    sumi=sumi+e2-e1
    print(sumi)
    d[b]=d[b]+d[a]
    d[a]=0

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

#define endl "\n"
#define INF INT_MAX
#define all(x) x.begin(), x.end()

using namespace std;

typedef long long ll;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<vector<int>> matrix;

typedef pair<int, int> pii;
typedef vector<pair<int, int>> vpii;

int main()
{
   ios_base::sync_with_stdio(false);
   cin.tie(nullptr); 

   ll q, n, m, sum = 0, b, c;
   cin >> n;
   multiset<ll> s;
   for (int i = 0; i < n; ++i) {
      cin >> m;
      sum += m;
      s.insert(m);
   }
   cin >> q;
   
   while (q--) {
      cin >> b >> c;
      ll count = s.count(b);
      s.erase(b);
      for (int i = 0; i < count; ++i) {
         s.insert(c);
      }
      sum -= b*count;
      sum += c*count;
      cout << sum << endl;
   }
    
   return 0;
} //AntiD2ta

Submission status: Runtime Error

Solution code:
n = int(input())
list_in = list(map(int, input().split()))
q = int(input())
for i in range(q+1):
    b,c = input().split()
    b = int(b)
    c = int(c)
    for j in range(n):
        if list_in[j]==b:
            list_in[j]=c
    print(sum(list_in))

Submission status: Runtime Error

Solution code:
#atcoder template
def main():
    import sys
    imput = sys.stdin.readline
    #文字列入力の時は上記はerrorとなる。
    #ここにコード
    #input
    N = int(input())
    A = list(map(int, input().split()))
    D = Counter(A)
    S = sum(A)
    Q = int(input())
    B = [0] * Q
    C = [0] * Q
    for i in range(Q):
        b, c = map(int, input().split())
        x = D[b]
        y = D[c]
        temp = -x * b + x * c
        print(S+temp)
        S += temp
        D[b] = 0
        D[c] += x  

    #N = 1のときなどcorner caseを確認！
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
n = int(input())
dic = {}
list = [int(i) for i in input().split()]
for i in list:
    if i not in dic:
        dic[i] = 0
    dic[i] += 1
q = int(input())
ans = sum(list)
for j in range(q):
    b,c = (int(x) for x in input().split())
    if b not in dic:
        pass
    else:
        if c not in dic:
            dic[c] = dic[b]
        else:
            dic[c] += dic[b]
    ans = ans + (c-b)*dic[b]
    dic[b] = 0
    print(ans)

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
n=int(input())
A=list(map(int,input().split()))
A.sort()
q=int(input())
for i in range(q):
  b,c=map(int,input().split())
  a=set(A)
  if b in a:
    k=A.count(b)
    x=A.index(b)
    f=x+k
    for i in range(x,f):
      A[i]=c
    ans=sum(A)
  print(ans)

Submission status: Runtime Error

Solution code:
#%%
N = int(input())
L = [int(i) for i in input().split()]
Q = int(input())
order = [[] for _ in range(Q)]
for i in range(Q):
    order[i] = [int(i) for i in input().split()]
#%%
cnt = {}
for i in L:
    if i in cnt:
        cnt[i] += 1
        
    else:
        cnt[i] = 1

ans = [sum(L)]
for i in order:
    temp = cnt[i[0]] * (i[1] - i[0])
    ans.append(temp + ans[-1])
    print(ans[-1])
    
    if i[1] in cnt:
        cnt[i[1]] += cnt[i[0]]
    else:
        cnt[i[1]] = cnt[i[0]]

    del cnt[i[0]]

Submission status: Runtime Error

Solution code:
#include<bits/stdc++.h>
using namespace std;
int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	uint64_t sum=0;
	map<int,int>mapper;
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		int temp;
		cin>>temp;
		if(mapper.find(temp)==mapper.end()){
			mapper[temp]=0;
		}
		mapper[temp]++;
		sum+=temp;
	}
	int q;
	cin>>q;
	for(int i=0;i<q;i++){
		int temp,temp1;
		cin>>temp>>temp1;
		if(mapper.find(temp1)==mapper.end()){
			sum-=temp*mapper[temp];
			sum+=temp1*mapper[temp];
			mapper[temp1]=mapper[temp];
			mapper.erase(temp);
		}else{
			sum-=temp*mapper[temp];
			sum+=temp1*mapper[temp];
			int val=mapper[temp];
			mapper.erase(temp);
			mapper[temp1]=mapper[temp1]+val;
		}
		cout<<sum<<"\n";
	}
}

Submission status: Runtime Error

Solution code:
N = int(input())
A = list(map(int, input().split()))
Q = int(input())
B = []
C = []
for i in range(Q):
    b, c = list(map(int, input().split()))
    B.append(b)
    C.append(c)

total = sum(A)

for i in range(Q):
    count = A.count(B[i])

    d = C[i] - B[i]
    total += count * B
    print(total)

    A = [C[i] if x == B[i] else x for x in A]

Submission status: Runtime Error

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

r = [0] * (10^5)
for a in a_list:
    r[a-1] += a

for i in range(Q):
    b, c = map(int, input().split())
    tmp = r[b-1] // b
    r[b-1] = 0
    r[c-1] += tmp * c
    print(sum(r))

Submission status: Runtime Error

Solution code:
a = input()
sequence_integer = [int(idx) for idx in input().split()]
num = int(input())
data = []
for idx in range(num):
  data.append([int(idx) for idx in input().split()])
for idx, jdx in data:
  sequence_integer[sequence_integer.index(idx)] = jdx
  print(sum([int(idx) for idx in sequence_integer]))