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:
import sys
import collections

input = sys.stdin.readline


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


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






if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

numdic = {}
#print(a)
s = 0
for i in a:
  s += i
  #print(i)
  if i in numdic:
    numdic[i] += 1
  else:
    numdic[i] = 1
#print(numdic)

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

Submission status: Accepted

Solution code:
## necessary imports
import sys
input = sys.stdin.readline
#from math import ceil, floor, factorial;

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

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

## nCr function efficient using Binomial Cofficient
def nCr(n, k): 
    if(k > n - k): 
        k = n - k 
    res = 1
    for i in range(k): 
        res = res * (n - i) 
        res = res / (i + 1) 
    return int(res) 

## upper bound function code -- such that e in a[:i] e < x;
def upper_bound(a, x, lo=0):
    hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if a[mid] < x:
            lo = mid+1
        else:
            hi = mid
    return lo

## prime factorization
def primefs(n):
    ## if n == 1    ## calculating primes
    primes = {}
    while(n%2 == 0 and n > 0):
        primes[2] = primes.get(2, 0) + 1
        n = n//2
    for i in range(3, int(n**0.5)+2, 2):
        while(n%i == 0 and n > 0):
            primes[i] = primes.get(i, 0) + 1
            n = n//i
    if n > 2:
        primes[n] = primes.get(n, 0) + 1
    ## prime factoriazation of n is stored in dictionary
    ## primes and can be accesed. O(sqrt n)
    return primes

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

## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
    temp = a
    a = b
    b = temp
    return a,b

# find function with path compression included (recursive)
# def find(x, link):
#     if link[x] == x:
#         return x
#     link[x] = find(link[x], link);
#     return link[x];

# find function with path compression (ITERATIVE)
def find(x, link):
    p = x;
    while( p != link[p]):
        p = link[p];
    
    while( x != p):
        nex = link[x];
        link[x] = p;
        x = nex;
    return p;


# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
    x = find(x, link)
    y = find(y, link)
    if size[x] < size[y]:
        x,y = swap(x,y)
    if x != y:
        size[x] += size[y]
        link[y] = x

## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n): 
    prime = [True for i in range(n+1)] 
    p = 2
    while (p * p <= n): 
        if (prime[p] == True): 
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    return prime

#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e6 + 5)
def spf_sieve():
    spf[1] = 1;
    for i in range(2, MAXN):
        spf[i] = i;
    for i in range(4, MAXN, 2):
        spf[i] = 2;
    for i in range(3, ceil(MAXN ** 0.5), 2):
        if spf[i] == i:
            for j in range(i*i, MAXN, i):
                if spf[j] == j:
                    spf[j] = i;
    ## function for storing smallest prime factors (spf) in the array

################## un-comment below 2 lines when using factorization #################
# spf = [0 for i in range(MAXN)]
# spf_sieve() 
def factoriazation(x):
    ret = {};
    while x != 1:
        ret[spf[x]] = ret.get(spf[x], 0) + 1;
        x = x//spf[x]
    return ret
    ## this function is useful for multiple queries only, o/w use
    ## primefs function above. complexity O(log n)

## taking integer array input
def int_array():
    return list(map(int, input().strip().split()))
## taking string array input
def str_array():
    return input().strip().split();

#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');

################### ---------------- TEMPLATE ENDS HERE ---------------- ###################

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

Submission status: Accepted

Solution code:
import collections

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


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

q=int(input())

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

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

    print(a_sum)

Submission status: Accepted

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

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

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

for i in l:
    print(i)

Submission status: Accepted

Solution code:
import sys
from collections import Counter

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

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

Submission status: Accepted

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

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

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

outsum=sum(alist)

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

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

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

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from collections import defaultdict


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

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

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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

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

    q = int(input())

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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


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


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

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

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

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

    for que in queries:
        b, c = que

        if b not in d:
            print(total)
            continue

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

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

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

        print(total)


def main():
    solve()


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from math import ceil, floor, sqrt, sin, cos, pi
from itertools import accumulate, permutations, combinations
from fractions import gcd # 最大公約数
from collections import deque, Counter
from operator import itemgetter
from heapq import heappop,heappush
sys.setrecursionlimit(10**7)
def lcm(x, y): return ((x * y) // gcd(x, y)) # 最小公倍数
# list(map(int, input().split()))

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

Submission status: Accepted

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

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

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

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

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

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

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




######################################################################################################

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

    print(ans)

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
from collections import Counter

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

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

if __name__ == '__main__':
    main()

Submission status: Accepted

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

from collections import Counter
count = Counter(al)

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

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

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

Submission status: Accepted

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

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

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

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

Submission status: Accepted

Solution code:
from collections import Counter, defaultdict

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

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

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

Submission status: Accepted

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

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

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

Submission status: Accepted

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

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

s = sum(a)

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

Submission status: Accepted

Solution code:
n  =int(input())

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

Submission status: Accepted

Solution code:
from collections import Counter
import sys


def input(): return sys.stdin.readline().strip()
def I(): return int(input())
def LI(): return list(map(int, input().split()))
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def S(): return input()
def LS(): return input().split()


n = I()
a = LI()
q = I()
bcs = LIR(q)
sum_a = sum(a)
counter = Counter(a)
for b, c in bcs:
    sum_a += c * counter[b] - b * counter[b]
    print(sum_a)
    counter[c] += counter[b]
    counter[b] = 0

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)]
goukeiti=sum(A)
atai=[0]*(10**5+1)
for i in A:
    atai[i-1]+=1
for i in BC:
    if atai[i[0]-1]!=0:
        kotae=atai[i[0]-1]*i[1]-atai[i[0]-1]*(i[0])
        atai[i[1]-1]+=atai[i[0]-1]
        atai[i[0]-1]=0
        goukeiti+=kotae
        print(goukeiti)
    else:
        print(goukeiti)

Submission status: Accepted

Solution code:

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

q=int(input())

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


    q-=1

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import collections

N = int(input())

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

A_count = collections.Counter(A)

Q = int(input())

total = sum(A)

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

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

    print(total)

Submission status: Accepted

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

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
import sys
import math
from collections import deque
from collections import Counter

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


#隣接リスト 1-order
def make_adjlist_d(n, edges):
    res = [[] for _ in range(n + 1)]
    for edge in edges:
        res[edge[0]].append(edge[1])
        res[edge[1]].append(edge[0])
    return res


def make_adjlist_nond(n, edges):
    res = [[] for _ in range(n + 1)]
    for edge in edges:
        res[edge[0]].append(edge[1])
    return res


#nCr
def cmb(n, r):
    return math.factorial(n) // math.factorial(r) // math.factorial(n - r)


def main():
    N = NI()
    A = NLI()
    Q = NI()
    querys = [NLI() for _ in range(Q)]
    res = sum(A)
    Dic = dict(Counter(A))
    for b, c in querys:
        Dic.setdefault(c, 0)
        Dic.setdefault(b, 0)
        gap = (c-b) * Dic[b]
        Dic[c] += Dic[b]
        del Dic[b]
        res += gap
        print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

Submission status: Accepted

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

from collections import Counter
A = Counter(A)

for i in range(Q):
  B, C = map(int, input().split())
  try:
    var = A[B]
    ans += var*(C-B)
    A.pop(B)
    try:
      A[C] += var
    except:
      A[C] = var
    print(ans)
  except:
    print(ans)

Submission status: Accepted

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

Submission status: Accepted

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


Max=100000

ARR=[0] * Max

for i in range(N):
    ARR[A[i]-1]+=1

ans = 0

for i in range(Max):
    ans+=ARR[i]*(i+1)

Bt=[0]*Q
Ct=[0]*Q
for i in range(Q):
    Btt,Ctt=map(int, input().split())
    Bt[i]=Btt
    Ct[i]=Ctt

for i in range(Q):
    B=Bt[i]
    C=Ct[i]
    ans-=ARR[B-1]*B
    ans+=ARR[B-1]*C
    ARR[C-1]+=ARR[B-1]
    ARR[B-1]=0
    print(ans)

Submission status: Accepted

Solution code:
n=int(input())
l=[int(i) for i in input().split()]
s=sum(l)
d={}
for i in range(n):
  if(l[i] in d):
    d[l[i]]+=1
  else:
    d[l[i]]=1
q=int(input())
for w in range(q):
  b,c=(int(i) for i in input().split())
  if(b in d):
    s-=(d[b]*b)
    s+=(d[b]*c)
    if(c in d):
        d[c]+=d[b]
    else:
        d[c]=d[b]
    d[b]=0
  print(s)