Skip to content

Instantly share code, notes, and snippets.

@uchidama
Created July 9, 2021 17:42
Show Gist options
  • Save uchidama/c7c7cf50ada9b9857d75064774c06082 to your computer and use it in GitHub Desktop.
Save uchidama/c7c7cf50ada9b9857d75064774c06082 to your computer and use it in GitHub Desktop.
AtCoder Beginner Contest 171 [ D - Replacing ] https://atcoder.jp/contests/abc171/tasks/abc171_d
'''
[問題]
https://atcoder.jp/contests/abc171/tasks/abc171_d
'''
import sys
sys.setrecursionlimit(10 ** 6) # 再帰上限の引き上げ
input = sys.stdin.readline
INF = 2 ** 63 - 1
LIMIT = 10**5 + 7
A_NUM = [0] * LIMIT
N = int(input())
A = list(map(int, input().split()))
# 数列A内の数の出現回数を数えておく。ついでに合計も出す
A_SUM = 0
for a in A:
A_NUM[a] += 1
A_SUM += a
# クエリ処理。A_SUMに差分を増減。置き換えた数の出現回数を正しく反映
Q = int(input())
for _ in range(Q):
B, C = map(int, input().split())
A_SUM += (C - B) * A_NUM[B]
A_NUM[C] += A_NUM[B]
A_NUM[B] = 0
print(A_SUM)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment