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 defaultdict

N = int(input())
A = list(map(int,input().split()))
Q = int(input())
dic = defaultdict(int)
s = 0
for n in A:
    dic[n] += 1
    s += n
for _ in range(Q):
    b,c = map(int,input().split())
    s += (c-b)*dic[b]
    dic[c] += dic[b]
    dic[b] = 0
    print(s)

Submission status: Accepted

Solution code:
from collections import defaultdict
from collections import Counter
n = int(input())
a = list(map(int,input().split()))
q = int(input())
c = defaultdict(lambda: 0)
tmp = Counter(a)
for i, j in tmp.most_common():
	c[i] = j
s = sum(a)
for _ in range(q):
	mae, ato = map(int,input().split())
	kazu = c[mae]
	c[ato] += kazu
	c[mae] = 0
	s += (ato-mae)*kazu
	print(s)

Submission status: Accepted

Solution code:
"""
    こんにちは。これはクシャルです
    
    Author : thekushalghosh (クシャル)
    Team   : CodeDiggers
 
    I prefer Python language over the C++ language :p :D
        
    Visit my website : thekushalghosh.github.io
"""
import sys,math,cmath,time
start_time = time.time()
##########################################################################
################# ---- THE ACTUAL CODE STARTS BELOW ---- #################

def solve():
    n = inp()
    a = inlt()
    q = inp()
    w = sum(a)
    qw = counter(a)
    for i in range(q):
        b,c = invr()
        w = w + ((c - b) * qw[b - 1])
        qw[b - 1],qw[c - 1] = 0,qw[c - 1] + qw[b - 1]
        print(w)
            
################## ---- THE ACTUAL CODE ENDS ABOVE ---- ##################
##########################################################################
 
def main():
    global tt
    if not ONLINE_JUDGE:
        sys.stdin = open("input.txt","r")
        sys.stdout = open("output.txt","w")
    t = 1
    for tt in range(t):
        solve()
    if not ONLINE_JUDGE:
        print("Time Elapsed :",time.time() - start_time,"seconds")
        sys.stdout.close()
    
#---------------------- USER DEFINED INPUT FUNCTIONS ----------------------#
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    return(input().strip())
def invr():
    return(map(int,input().split()))
 
#------------------ USER DEFINED PROGRAMMING FUNCTIONS ------------------#
def counter(a):
    q = [0] * 100000
    for i in range(len(a)):
        q[a[i] - 1] = q[a[i] - 1] + 1
    return(q)
 
def string_counter(a):
    q = [0] * 26
    for i in range(len(a)):
        q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
    return(q)

#-----------------------------------------------------------------------#    
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
    input = sys.stdin.readline
main()

Submission status: Accepted

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

df = {}
original_sum = 0 
for a in A:
    if not a in df.keys():
        df[a] = 1
    else:
        df[a] += 1
    original_sum += a

result = []
now_sum = original_sum

for i in range(Q):
    if (B_C[i][0] in df.keys()):
        if (df[B_C[i][0]] > 0):
            now_sum += (B_C[i][1] -B_C[i][0]) * df[B_C[i][0]]
            if B_C[i][1] in df.keys():
                df[B_C[i][1]] += df[B_C[i][0]]
            else:
                df[B_C[i][1]] = df[B_C[i][0]]
            df[B_C[i][0]] = 0
    result.append(now_sum)

for i in range(Q):
    print(result[i])

Submission status: Accepted

Solution code:
from collections import defaultdict
n=int(input())
a=list(map(int,input().split()))
q=int(input())
d=defaultdict(int)
s=0
for i in range(n):
    d[a[i]]+=1
    s+=a[i]
for i in range(q):
    b,c=map(int,input().split())
    k=0
    if(d[b]>0):
        k=d[b]*b
        d[c]+=d[b]
        s-=k
        s+=(d[b]*c)
        d[b]=0
    print(s)

Submission status: Accepted

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

from collections import Counter
sum_ = sum(A)

Counter_A = Counter(A)

for q in range(Q):
    B,C = list(map(int,input().split()))
    B_num = Counter_A[B]
       
    sum_ = sum_+(C-B)*B_num
    print(sum_)
    
    #Counter 更新
    Counter_A[B]=0
    Counter_A[C]=Counter_A[C]+B_num

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline
from collections import Counter
N = int(input())
A = list(map(int, input().split()))
Q = int(input())

counter = Counter(A)
A_sum = sum(A)
for _ in range(Q):
    b, c = map(int, input().split())
    num_b = counter.get(b, 0)
    A_sum = A_sum + (c - b) * num_b
    del counter[b]
    counter[c] = counter.get(c, 0) + num_b
    print(A_sum)

Submission status: Accepted

Solution code:
N = int(input())
l = [0]*(10**5+1)
A = list(map(int,input().split()))
Q = int(input())
for a in A:
  l[a] += a
suml = sum(l)
for _ in range(Q):
  b,c = map(int,input().split())
  suml += ((l[b]//b)*c - l[b])
  l[c] += (l[b]//b)*c
  l[b] = 0
  print(suml)

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
	return list(map(int,input().split()))
def m(): #複数文字
	return map(int,input().split())
def onem(): #Nとかの取得
	return int(input())
def s(x): #圧縮
	a = []
	if len(x) == 0:
		return []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa != x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x): #listをスペースごとに分ける
	return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
	return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans

"""
def nibu(x,n,r):
	ll = 0
	rr = r
	while True:
		mid = (ll+rr)//2

	if rr == mid:
		return ll
	if (ここに評価入れる):
		rr = mid
	else:
		ll = mid+1
"""


n = onem()

a = l()
ans = sum(a)

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

for i in range(n):
	po[a[i]] += 1

q = onem()

for i in range(q):
	b,c = m()

	ans += (c-b)*po[b]
	po[c] += po[b]
	po[b] = 0
	print(ans)

Submission status: Accepted

Solution code:
n = int(input())
lis = list(map(int,input().split()))
q = int(input())
now = [0 for i in range(10 ** 5)]
for num in lis:
    now[num-1] += 1
ans = 0
for i in range(10 ** 5):
    ans += now[i] * (i+1)
  # print(ans)
for turn in range(q):
    b,c = map(int,input().split())
    num = now[b-1]
    now[b-1] = 0
    now[c-1] += num
    print(ans-b*num+c*num)
    ans -= b*num
    ans += c*num
  #     print(now)

Submission status: Accepted

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

M = 10**5+3
s = sum(A)
L = [0]*(M+1)
for a in A:
    L[a] += 1

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

Submission status: Accepted

Solution code:
from collections import Counter
import copy
N = int(input())
A = list(map(int,input().split()))
c = Counter(A)
Q = int(input())
total = sum(A)
for i in range(Q):
    x,y = map(int,input().split())
    num = copy.deepcopy(c[x])
    total = total + ((y-x)*num)
    c[x] = 0
    c[y] += num
    print(total)

Submission status: Accepted

Solution code:
from collections import Counter

def resolve():
    n = int(input())
    a = list(map(int, input().split()))
    acc = sum(a)
    counter = Counter(a)
    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
            acc += counter[b] * c - counter[b] * b
            counter[c] += counter[b]
            counter[b] = 0
        print(acc)

if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
import collections
from collections import defaultdict

def main():
    N = int(input())
    A = list(map(int, input().split()))
    Q = int(input())
    BC = []
    for q in range(Q):
        b, c = map(int, input().split())
        BC.append((b, c))
    
    C = dict(collections.Counter(A))
    s = sum(A)
    ans = []
    for b, c in BC:
        cb = C.get(b, 0)
        delta = cb * (c - b)
        s += delta
        ans.append(s)
        C[c] = C.get(c, 0) + cb
        C[b] = 0
    
    print(*ans, sep='\n')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n=I()
  l=LI()

  k=I()
  d={}
  for x in l:
    if x in d:
      d[x]+=1
    else:
      d[x]=1

  sm=sum(l)

  ans=[]
  for _ in range(k):
    a,b=LI()
    if a in d:
      x=d[a]
      d[a]=0

      aa=a*x
      bb=b*x

      sm+=(bb-aa)
      ans.append(sm)

      if b in d:
        d[b]+=x
      else:
        d[b]=x

    else:
      ans.append(sm)

  for x in ans:
    print(x)

main()
# print(main())

Submission status: Accepted

Solution code:
import math as mt
import collections as cc
I=lambda:list(map(int,input().split()))
n,=I()
l=I()
f=cc.defaultdict(int)
for i in l:
    f[i]+=1
s=sum(l)
for i in range(int(input())):
    x,y=I()
    if f[x]==0:
        print(s)
    else:
        s-=f[x]*x
        s+=f[x]*y
        f[y]+=f[x]
        f[x]=0
        print(s)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
n=int(input())
arr=[int(i) for i in input().split()]
q=int(input())
q_arr=[]
for i in range(q):
    q_arr.append([int(j) for j in input().split()])
from collections import defaultdict
cnt=defaultdict(lambda :0)
sum_=sum(arr)
for i in arr:
    cnt[i]+=1
#print(cnt)
for j in q_arr:
    if cnt[j[0]]:
        sum_+=(j[1]-j[0])*(cnt[j[0]])
        cnt[j[1]]+=cnt[j[0]]
        cnt[j[0]]=0
    print(sum_)

Submission status: Accepted

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

lis = [0]*(10**5 + 1)
total = 0
for a in A:
    lis[a] += 1
    total += a

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

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    a = list(map(int,input().split()))
    q = int(input())
    b = [0] * q
    c = [0] * q
    for i in range(q):
        bb,cc = map(int,input().split())
        b[i] = bb
        c[i] = cc
    import collections
    cnt = collections.Counter(a)
    S = sum(a)

    for i in range(q):
        now_b = b[i]
        now_c = c[i]
        now_cnt = cnt[now_b]
        sub = (now_c - now_b) * now_cnt
        S += sub
        cnt[now_b] = 0
        cnt[now_c] += now_cnt
        # print(now_b,now_c,now_cnt)
        # print(cnt)
        print(S)

if __name__=='__main__':
    main()

Submission status: Accepted

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

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

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

ans = sum(A)

for b,c in BC:
  x = count[b]
  y = c - b
  ans += x * y
  print(ans)
  count[b] = 0
  count[c] += x

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
q = int(input())
cur = [0]*(10**5+1)

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

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

Submission status: Accepted

Solution code:
N = int(input())
A = [int(_) for _ in input().split()]
Q = int(input())
BC = [[int(_) for _ in input().split()] for _ in range(Q)]


class SegmentTree():
    def __init__(self, array, f, ti):
        """
        Parameters
        ----------
        array : list
            to construct segment tree from
        f : func
            binary operation of the monoid
        ti : 
            identity element of the monoid
        """
        self.f = f
        self.ti = ti
        self.n = n = 2**(len(array).bit_length())
        self.dat = dat = [ti] * n + array + [ti] * (n - len(array))
        for i in range(n - 1, 0, -1):  # build
            dat[i] = f(dat[i << 1], dat[i << 1 | 1])

    def update(self, p, v):  # set value at position p (0-indexed)
        f, n, dat = self.f, self.n, self.dat
        p += n
        dat[p] = v
        while p > 1:
            p >>= 1
            dat[p] = f(dat[p << 1], dat[p << 1 | 1])

    def query(self, l, r):  # result on interval [l, r) (0-indexed)
        f, ti, n, dat = self.f, self.ti, self.n, self.dat
        res = ti
        l += n
        r += n
        while l < r:
            if l & 1:
                res = f(res, dat[l])
                l += 1
            if r & 1:
                r -= 1
                res = f(dat[r], res)
            l >>= 1
            r >>= 1
        return res


array = [0] * (10**5 + 1)
for a in A:
    array[a] += a
st = SegmentTree(array, f=lambda x, y: x + y, ti=0)
for b, c in BC:
    st.update(c, st.query(c, c + 1) + st.query(b, b + 1) * c // b)
    st.update(b, 0)
    print(st.query(0, 10**5 + 1))

Submission status: Accepted

Solution code:
N = int(input())
l = [int(x) for x in input().split()]
Q = int(input())
ans = sum(l)
from collections import defaultdict
d = defaultdict(int)
for i in range(N):
    d[l[i]] += 1
for i in range(Q):
    b,c = [int(x) for x in input().split()]
    ans = ans + (c-b)*d[b]
    d[c] += d[b]
    d[b] = 0
    print(ans)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.buffer.readline
read = sys.stdin.read
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    N = int(readline())
    A = [0] *(10**5+1)
    total = 0
    for a in map(int, readline().split()):
        total += a
        A[a] += 1


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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
n = int(input())
A = [int(i) for i in input().split()]
my_dict = defaultdict(int)
for i in A:
    my_dict[i] += 1
ans = sum(A) # sum up once
Q = int(input())
for q in range(Q):
    b, c = [int(i) for i in input().split()]
    if b in my_dict:
        my_dict[c] += my_dict[b]
        ans += my_dict[b] * (c-b)
        my_dict[b] = 0
    print(ans)

Submission status: Accepted

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

base=sum(A)

from collections import Counter
ad=Counter(A)
for _ in range(Q):
    b, c=map(int, input().split())
    if ad[b]!=0:
        base+=(c-b)*ad[b]
        ad[c]+=ad[b]
        ad[b]=0
    print(base)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
BC = [list(map(int,input().split())) for _ in range (Q)]

dic = dict()
ans = sum(A)
for a in A:
    if a in dic:
        dic[a] += 1
    else:
        dic[a] = 1

for b,c in BC:
    if not (b in dic) or dic[b]==0:
        print(ans)
        continue
    
    sa = (c-b)*dic[b]
    ans += sa
    print(ans)

    if c in dic:
        dic[c] += dic[b]
    else:
        dic[c] = dic[b]
    dic[b] = 0

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
from collections import *

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

Submission status: Accepted

Solution code:
import collections

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


q=int(input())

anscol = collections.Counter(a_list)
#print(anscol)

goukei=sum(a_list)

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

Submission status: Accepted

Solution code:
from collections import Counter

n = int(input())
aa = tuple(map(int, input().split()))
actr = Counter(aa)
q = int(input())

ans = sum([a * n for a, n in actr.items()])
for i in range(q):
    b, c = map(int, input().split())
    n = actr[b]
    ans = ans - b * n + c * n
    actr[c] += n
    del actr[b]
    print(ans)

Submission status: Accepted

Solution code:
import collections,sys
input=sys.stdin.readline
n=int(input())
l=list(map(int,input().split()))

c = collections.Counter(l)
q=int(input())
ans=0
for x in c:
  ans+=x*c[x]
for _ in range(q):
  a,b=map(int,input().split())
  if not a in c:
    print(ans)
  elif c[a]==0:
    print(ans)
  else:
    if b in c:
      c[b]+=c[a]
    else:
      c[b]=c[a]
    ans+=(b*c[a]-a*c[a])
    print(ans)
    c[a]=0

Submission status: Accepted

Solution code:
from collections import defaultdict

n = int(input())
A = list(map(int, input().split()))
q = int(input())
BC = [tuple(map(int, input().split())) for _ in range(q)]
total = sum(A)
d = defaultdict(int)
for a in A:
    d[a] += 1
for b, c in BC:
    total = total - b*d[b] + c*d[b]
    d[c] += d[b]
    d[b] = 0
    print(total)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys
import collections
sys.setrecursionlimit(10 ** 8)

def Z(): return int(input())
def ZZ(): return [int(_) for _ in input().split()]

def main():
    N = Z()
    A = ZZ()
    D = collections.Counter(A)
    s = sum(A)

    Q = Z()
    ans = []
    for _ in range(Q):
        b, c = ZZ()
        if D[b]:
            s += (c-b)*D[b]
            D[c] += D[b]
            D[b] = 0
        ans.append(s)
    for i in range(Q):
        print(ans[i])

    return

if __name__ == '__main__':
    main()

Submission status: Accepted

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

A.sort()
s = sum(A)
A_dict = dict()
A_dict[A[0]] = 1
for i, value in enumerate(A):
    if i == 0: continue
    bA = A[i-1]
    if value == bA:
        A_dict[A[i]] += 1
    else:
        A_dict[A[i]] = 1

# print(A_dict)

for i in range(Q):
    B, C = map(int, input().split())
    if B in A_dict:
        s += (C - B) * A_dict[B]
        if C in A_dict:
            A_dict[C] += A_dict.pop(B)
        else:
            A_dict[C] = A_dict.pop(B)
    print(s)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
M = max(a)
counts = [0 for _ in range(100000+1)]
s = sum(a)
for i in range(n):
  counts[a[i]] += 1
for i in range(int(input())):
  b, c = map(int, input().split())
  move = counts[b]
  counts[b] = 0
  counts[c] += move
  s += (c - b)*move
  print(s)

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int,input().split()))
q = int(input())
bcl = [list(map(int,input().split())) for nesya in range(q)]
hoge = dict()
for num in a:
  if num in hoge:
    hoge[num] += 1
  else:
    hoge[num] = 1
total = 0
for k,v in hoge.items():
  total += k*v
for bc in bcl:
  b = bc[0]
  c = bc[1]
  if b in hoge:
    total += (c-b)*hoge[b]
  print(total)
  if b in hoge:
    if c in hoge:
      hoge[c] += hoge[b]
    else:
      hoge[c] = hoge[b]
    hoge[b] = 0

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import Counter, defaultdict
# for use in beginner level contests where speed is key

_ = int(input())

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

nrows = int(input())

grid = []
for _ in range(nrows):
    grid.append(list(map(int,input().split())))

c = Counter(lst)
res = sum(lst)

for old, new in grid:
    diff = new - old
    res += c[old]*diff
    print(res)
    c[new] = c[new] + c[old]
    c[old] = 0

Submission status: Accepted

Solution code:
import collections
N = int(input())
A = list(map(int,input().split()))
Q = int(input())
a = collections.Counter(A)
tmp = sum(A)

for i in range(Q):
  B,C = map(int,input().split())
  tmp += (a[B]*C -a[B]*B)
  if C in a:
    a[C] += a[B]
  else:
    a[C]=a[B]
  del a[B]
  print(tmp)

Submission status: Accepted

Solution code:
from collections import defaultdict
N=int(input())
A=list(map(int, input().split()))
D=defaultdict(int)
for a in A:
    D[a]+=1

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

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

ls = [0 for _ in range(10**5 + 1)]
ans = 0
for a in an:
  ls[a] += 1
  ans += a
for b, c in bc:
  x = ls[b]
  ls[c] += x
  ls[b] = 0
  ans = ans - x * b + x * c
  print(ans)

Submission status: Accepted

Solution code:
from sys import stdin,stdout
input = stdin.readline
print = stdout.write
from collections import Counter
n = int(input())
a = list(map(int,input().split()))
c = Counter(a)
s = sum(a)
for _ in range(int(input())):
    b1,c1 = map(int,input().split())
    if b1 in c and c[b1]:
      s+=c[b1]*c1-c[b1]*b1
      c[c1]= c.get(c1,0)+c[b1]
      c[b1]=0
    print(str(s)+'\n')

Submission status: Accepted

Solution code:
n=int(input())

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

s=sum(l)
d={}
for i in l:
    d[i]=d.get(i,0)+1

for i in range(int(input())):

    a,b=map(int,input().split())
    if a not in d:
        print(s)
        continue
    
    x=d[a]
    d[a]-=x
    d[b]=d.get(b,0)+x
    s-=x*a
    s+=x*b
    print(s)

Submission status: Accepted

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



A = list(A)

hashmap = {}
s = 0
for i in range(len(A)):
	s += A[i]
	hashmap[A[i]] = hashmap.get(A[i], [0, A[i]]) 
	hashmap[A[i]][0] += 1

for _ in range(Q):
	# replace every element whose value is B with C
	B, C = map(int, input().split())

	if B in hashmap:
		num = hashmap[B][0]
		del hashmap[B]
		s -= num * B
		s += num * C

		hashmap[C] = hashmap.get(C, [0, C])
		hashmap[C][0] += num
	print(s)

Submission status: Accepted

Solution code:
import itertools
import decimal
import math
from collections import Counter
import sys
input = sys.stdin.readline

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

Counts = Counter(ListA)
Sum = sum(ListA)

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

Submission status: Accepted

Solution code:
from collections import defaultdict

N=int(input())
A=[int(x) for x in input().split()]
Q=int(input())
D=[0 for i in range(100001)]
ans=0
for a in A:
    D[a]+=1
for i in range(100001):
    ans+=i*D[i]

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

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int, input().split()))
cnt = [0]*100010
for i in range(N):
    cnt[A[i]] += 1

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

Submission status: Accepted

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

D={}
for x in A:
    if x in D:
        D[x]+=1
    else:
        D[x]=1

S=sum(A)

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

    if B in D:
        S+=(C-B)*D[B]
        if C in D:
            D[C]+=D[B]
        else:
            D[C]=D[B]

        D[B]=0

    print(S)

Submission status: Accepted

Solution code:
from collections import defaultdict
import sys

def read_int():
    l = sys.stdin.readline().rstrip('\n').split(' ')
    return int(l[0])

def read_int_list():
    l = sys.stdin.readline().rstrip('\n').split(' ')                                                  
    return [int(i) for i in l]

N = read_int()
A = read_int_list()
Q = read_int()                                                                                        
BC = []
for _ in range(Q):                                                                                    
    BC.append(read_int_list())                                                                        

_sum = sum(A)                                                                                         

n2c = defaultdict(int)                                                                                

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

for bc in BC:                                                                                         
    b = bc[0]                                                                                         
    c = bc[1]                                                                                         
    b_cnt = n2c[b]                                                                                    
    n2c[b] = 0                                                                                        
    n2c[c] += b_cnt                                                                                   
    _sum += b_cnt * (c - b)                                                                           
    print(_sum)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(i) for i in input().split()]
num = 100002
count = [0]*num
tot = 0
for a in A:
    count[a] += 1
    tot += a
    
Q = int(input())

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

Submission status: Accepted

Solution code:
n = int(input())
alist = list(map(int,input().split()))
query = int(input())
bc = [list(map(int,input().split()))for i in range(query)]

ssum = 0
amx = max(alist)
bcmx = 0
for i in range(query):
    if bcmx < bc[i][1]:
        bcmx = bc[i][1]
mx = max(amx,bcmx)
qlist = [0]*(mx+1)
for a in alist:
    qlist[a] += 1
    ssum += a
anslist = []
for q in range(query):
    b = bc[q][0]
    c = bc[q][1]
    ssum += qlist[b]*(c-b)
    qlist[c] += qlist[b]
    qlist[b] = 0
    anslist.append(ssum)
for ans in anslist:
    print(ans)


'''
adic = {}
ssum = 0
for a in alist:
    if a not in adic:
        adic[a] = 0
    adic[a] += 1
    ssum += a
for q in range(query):
'''

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
    a = [int(i) for i in ipt().split()]
    d = defaultdict(int)
    sum = 0
    for i in a:
        sum += i
        d[i] += 1
    q = int(ipt())
    for _ in range(q):
        b,c = map(int,ipt().split())
        sum += d[b]*(c-b)
        print(sum)
        d[c] += d[b]
        d[b] = 0
    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
A = list(map(int,input().split()))
X = [0] * (10 ** 5 + 1)
wa = 0
for i in range (N):
    X[A[i]] += 1
    wa += A[i]
Q = int(input())
for i in range(Q):
    b,c = map(int,input().split())
    wa = wa + X[b] * (c - b)
    print(wa)
    X[c] += X[b]
    X[b] = 0

Submission status: Accepted

Solution code:
n = int(input())
a = list(map(int, input().split()))
num = {}
ans = 0
for i in a:
    num.setdefault(i, 0)
    num[i] += 1
    ans += i
q = int(input())
for i in range(q):
    b, c = map(int, input().split())
    num.setdefault(b, 0)
    ans += (c - b) * num[b]
    if c in num.keys():
        num[c] += num[b]
        del num[b]
    else:
        num[c] = num[b]
        del num[b]
    print(ans)

Submission status: Accepted

Solution code:
# import sys

# n = int(input())

# result = []
# k = 26
# i = 1

# while k < n:
# 	n -= k
# 	k *= 26
# 	i += 1

# length = i
# n -= 1

# pow26 = 1
# for i in range(length):


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

count = {}
for x in a:
	if x in count:
		count[x] += 1
	else:
		count[x] = 1

s = sum(a)

Q = int(input())
for q in range(Q):
	a, b = map(int, input().split())
	acount = count[a] if a in count else 0
	s -= a * acount 
	s += b * acount
	count[a] = 0
	if b not in count:
		count[b] = acount
	else:
		count[b] += acount
	print(s)