jiahuimbzuai/CoQuIR huggingface dataset:
//  [go]
package main

import (
	"fmt"
)

func COM(n, k int64) int64 {
	r := int64(1)
	for i := int64(0); i < k; i++ {
		r = ModMul(r, n-i)
		r = ModDiv(r, i+1)
	}

	return r
}

const (
	MOD = 1000000000 + 7
)

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	return a * b % MOD
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	value int
	index int
	A, B  int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (pq QS) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *QS) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Q)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *QS) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func FactoredPrimeNumber(num int) map[int]int {
	m := map[int]int{}
	return factor(m, num, 2)
}

func factor(result map[int]int, num, pnum int) map[int]int {
	if pnum*pnum > num {
		if num != 1 {
			result[num] += 1
		}
		return result
	}

	if num%pnum == 0 {
		num /= pnum
		result[pnum]++
	} else {
		pnum++
	}
	return factor(result, num, pnum)
}

func GCD(a, b int64) int64 {
	if b == 0 {
		return a
	}
	return GCD(b, a%b)
}

func LCM(a, b int64) int64 {
	return a * b / GCD(a, b)
}

func main() {
	var A, B, C int
	fmt.Scanf("%d %d %d\n", &A, &B, &C)
	min := A + B
	if min > B+C {
		min = B + C
	}
	if min > C+A {
		min = C + A
	}

	fmt.Println(min)
}

func Reverse(runes []rune) []rune {
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return runes
}
//  [go]
package main

import (
  "fmt"
)

func maxInt(a ...int) int {m := a[0]; for _, x := range a {if x > m {m = x}}; return m}
func minInt(a ...int) int {m := a[0]; for _, x := range a {if x < m {m = x}}; return m}

func sumInt(a ...int) int {s := 0; for _, v := range a {s += v}; return s}

func main() {
  t := make([]int, 3)
  for i := 0; i < 3; i++ {
    fmt.Scan(&t[i])
  }
  fmt.Println(sumInt(t...) - maxInt(t...))
}
//  [go]
package main

import (
  "fmt"
)

func main() {
  var p, q, r int
  fmt.Scanf("%d %d %d", &p, &q, &r)
  
  ans := r
  if p + q < r {
    ans = p + q
  }
  fmt.Printf("%d\n", ans)
}
//  [go]
package main

import (
	"fmt"
)

func main(){
	var s []int
	var a int

	for i:=0;i<3;i++{
		s = append(s,fmt.Scan(&a))
	}
	fmt.Println(s)
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
	"unsafe"
)

func main() {
	// P, Q, R := sc.nextInt(), sc.nextInt(), sc.nextInt()
	PQR := sc.nextInts()
	minv := 101
	for i := 0; i < 3; i++ {
		for j := 0; j < 3; j++ {
			if i == j {
				continue
			}
			tmp := PQR[i] + PQR[j]
			if minv > tmp {
				minv = tmp
			}
		}
	}
	fmt.Println(minv)
}

var (
	sc scanner
)

func init() {
	sc = scanner{
		buf: make([]string, 0, 0),
		cur: 0,
		r:   bufio.NewReader(os.Stdin),
	}
}

type scanner struct {
	buf []string
	cur int
	r   *bufio.Reader
}

func (s *scanner) readln() {
	rbuf := make([]byte, 0, 0)
	for {
		line, prefix, err := s.r.ReadLine()
		if err != nil {
			panic(err)
		}
		rbuf = append(rbuf, line...)
		if prefix == false {
			break
		}
	}
	s.cur = 0
	s.buf = strings.Split(*(*string)(unsafe.Pointer(&rbuf)), " ")
}
func (s *scanner) isFull() bool {
	if s.cur == len(s.buf) {
		return true
	}
	return false
}
func (s *scanner) resetCur() {
	s.cur = 0
}
func (s *scanner) next() string {
	if s.cur == 0 {
		s.readln()
	}
	res := s.buf[s.cur]
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}
func (s *scanner) nexts() []string {
	s.readln()
	s.resetCur()
	return s.buf
}
func (s *scanner) nextInt() int {
	if s.cur == 0 {
		s.readln()
	}
	res, _ := strconv.Atoi(s.buf[s.cur])
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}
func (s *scanner) nextInts() []int {
	s.readln()
	res := make([]int, len(s.buf))
	for i := range s.buf {
		res[i], _ = strconv.Atoi(s.buf[i])
	}
	s.resetCur()
	return res
}
func (s *scanner) nextFloat() float64 {
	if s.cur == 0 {
		s.readln()
	}
	res, _ := strconv.ParseFloat(s.buf[s.cur],
		64)
	s.cur++
	if s.isFull() {
		s.resetCur()
	}
	return res
}
func (s *scanner) nextFloats() []float64 {
	s.readln()
	res := make([]float64, len(s.buf))
	for i := range s.buf {
		res[i], _ = strconv.ParseFloat(s.buf[i],
			64)
	}
	s.resetCur()
	return res
}
func digits(x int) int {
	return len(strconv.Itoa(x))
}
func powInt(x, p int) (result int) {
	result = 1
	for i := 0; i < p; i++ {
		result *= x
	}
	return
}
func max(x, y int) int {
	return int(math.Max(float64(x), float64(y)))
}
func min(x, y int) int {
	return int(math.Min(float64(x), float64(y)))
}
func abs(x int) int {
	return int(math.Abs(float64(x)))
}
func varDump(value ...interface{}) {
	for _, v := range value {
		fmt.Fprintf(os.Stderr, "%#v\n", v)
	}
}
func yes() {
	fmt.Println("Yes")
}
func no() {
	fmt.Println("No")
}

// Pair a
type Pair struct {
	first  int
	second int
}

// Queue a
type Queue struct {
	v []Pair
}

// Push for queue
func (q *Queue) Push(v Pair) {
	q.v = append(q.v, v)
}

// Pop for queue
func (q *Queue) Pop() Pair {
	r := q.v[0]
	q.v = q.v[1:]
	return r
}

// Front for queue
func (q Queue) Front() Pair {
	return q.v[0]
}

// Empty return true if empty
func (q Queue) Empty() bool {
	return len(q.v) == 0
}
//  [ruby]
m=gets.split.map(&:to_i)
n= m.combination(2).to_a
r=[]
for i in 0..n.length-1
    r<<n[i].inject(&:+);
end

p r.min
//  [ruby]
a, b, c = gets.split(" ").map(&:to_i)
puts [a+b, a+c, b+a, b+c, c+a, c+b].min
//  [ruby]
ports = gets.split("\s").map(&:to_i)
p ports.inject(:+) - ports.max
//  [ruby]
s=gets.split("").map &:to_i
s.sort!
puts s[0]+s[1]
//  [ruby]
s=gets.split("").map &:to_i
s.sort!
puts s[0]*s[1]
//  [ruby]
p, q, r = gets.split.map &:to_i
p [p+q, q+r, r+p].min
//  [rust]
fn main() {
    let pqr = read_vec::<usize>();

    let mut mi = usize::max_value();
    for i in 0..2 {
        for j in i+1..3 {
            let sum = pqr[i] + pqr[j];
            if mi > sum {
                mi = sum;
            }
        }
    }
    println!("{}", mi);
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace().map(|e| e.parse().ok().unwrap()).collect()
}
//  [rust]
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}



use std::cmp;
use std::iter::Iterator;

fn main() {
    input! {
        a:usize,
        b:usize,
        c:usize,
    }

    let mut vec = Vec::new();

    vec.push(a+b);
    vec.push(a+c);
    vec.push(b+c);


    let min = vec.iter().min().unwrap();

    println!("{}", min);

}
//  [rust]
#[allow(unused_imports)]
use std::char::*;
#[allow(unused_imports)]
use std::cmp::*;
use std::io::*;
use std::str::FromStr;
#[allow(unused_imports)]
use std::collections::*;

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

#[derive(PartialEq, PartialOrd)]
pub struct Total<T>(pub T);

impl<T: PartialEq> Eq for Total<T> {}

impl<T: PartialOrd> Ord for Total<T> {
    fn cmp(&self, other: &Total<T>) -> std::cmp::Ordering {
        self.0.partial_cmp(&other.0).unwrap()
    }
}

//const MAX:usize = 100006;
//const INF:u64 = u64::max_value();

fn main() {
    let a:Vec<u32> = (0..3).map(|_| read()).collect();

    println!("{}", min(a[0]+a[1], min(a[1]+a[2],a[0]+a[2])));

}
//  [rust]
#![allow(unused_imports)]
use ascii::{AsciiChar, AsciiStr};
use itertools::Itertools;
use proconio::{input, marker::Usize1};

fn main() {
    input! {
        p: usize,
        q: usize,
        r: usize
    };
    println!("{}", vec![p + q, q + r, r + p].into_iter().min().unwrap());
}
//  [swift]
var arr=readLine()!.characters.split{$0==" "}.map{Int(String($0))!}

var max = 0;
arr.forEach {
  if( max < $0 ) {
    ( max = $0 )
  }
}

for var i = 0; i < 3; i += 1 {
    if( max == arr[i] ) {
		arr.removeAtIndex(i)
      	break
    }
}

print( arr[0] + arr[1] )
//  [swift]
/// Swift5 -> Swift2.2

extension String {
    // split(separator:maxSplits:omittingEmptySubsequences:)
    func split(separator separator: Character) -> [String] {
        return self.characters.split(separator).map(String.init)
    }
}
extension Array {
    // init(repeating:count:)
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
    // lastIndex(where:)
    func lastIndex(where predicate: (Element) -> Bool) -> Int? {
      	for i in stride(from: count - 1, through: 0, by: -1) {
          	if predicate(self[i]) {
              	return i
            }
        }
      	return nil
    }
}
extension Array where Element: Comparable {
    // sorted()
    func sorted() -> [Element] {
        return self.sort( { $0 < $1 } )
    }
    // max()
    func max() -> Element? {
        guard self.count > 0 else { return nil }
        return self.reduce(self.first!) { return Swift.max($0, $1) }
    }
}
extension String {
    // Sequence#enumerated()
  	// public func enumerate<Seq : SequenceType>(base: Seq) -> EnumerateSequence<Seq>
    func enumerated() -> EnumerateSequence<[Character]> {
        return Array(self.characters).enumerate()
    }
}
// stride(from:through:by:)
func stride(from start: Int, through end: Int, by stride: Int) -> StrideThrough<Int> {
    return start.stride(through: end, by: stride)
}
// stride(from:to:by)
func stride(from start: Int, to end: Int, by stride: Int) -> StrideTo<Int> {
    return start.stride(to: end, by: stride)
}

/// end

let input = readLine()!.split(separator: " ").map { Int($0)! }
let P = input[0]
let Q = input[1]
let R = input[2]

print(min(P + Q, Q + R, R + P))
//  [swift]
let inp = readLine()!.split(separator: " ").map { Int($0)! }

let p = inp[0]
let q = inp[1]
let r = inp[2]

print(min(min(p + r, p + q), r + q))
//  [swift]
let tmp = readLine()!.characters.split(" ").map{Int(String($0))!}
print((0..<2).reduce(0){$0 + tmp[$1]})
//  [swift]
import Foundation
 
let number = Int(readLine()!)!

//標準入力二行目以降
var weights = [Int]()
let input_line = readLine()! 

for i in 0..<number {
    let splits = input_line.componentsSeparatedByString(" ") //components(separatedBy:)と実質同じ
	weights.append(Int(splits[i])!)
}

let sumOfWeights = weights.reduce(0, combine: { $0 + $1 }) //重しの総和
var position = 1
var lhsWeight = weights[position - 1]

while sumOfWeights / 2 > lhsWeight {
    position += 1
    lhsWeight += weights[position - 1]
}

if abs(sumOfWeights - (lhsWeight * 2)) <= abs(sumOfWeights - ((lhsWeight - weights[position - 1]) * 2)) {
  print(abs(sumOfWeights - (lhsWeight * 2)))
} else {
  print(abs(sumOfWeights - ((lhsWeight - weights[position - 1]) * 2)))
}
//  [swift]
import Foundation
 
let input_line = readLine()!
 
let split = input_line.componentsSeparatedByString(" ") //components(separatedBy:)と実質同じ
let P = Int(split[0])!
let Q = Int(split[1])!
let R = Int(split[1])!
 
let value1 = P + Q
let value2 = P + R
let value3 = Q + R

if value1 <= value2 && value1 <= value3 {
    print(value1)
} else if value2 <= value3 {
    print(value2)
} else {
    print(value3)
}
//  [typescript]
import * as fs from 'fs';


// a→b b→c c→a
//in
// 6 2 2
//out
// 5
const main = (inp: string) => {

    const [a, b, c]: number[] = inp.split(' ').map(Number);
    const route1: number = a + b;
    const route2: number = b + c;
    const route3: number = c + a;

    console.log(Math.min(route1, route2, route3));
};

main(fs.readFileSync('/dev/stdin', 'utf8').trim());
//  [typescript]
{
  const main = (input: string) => {
    const read = reader(input)
    const [p, q, r] = read.ns()

    console.log(Math.min(p + q, q + r, r + p))
  }

  const reader = (str: string) => {
    const lines = str.trim().split('\n')
    const s = () => lines.shift() || ''
    const n = () => Number(s())

    const ss = () => s().split(' ')
    const ns = () => ss().map(Number)
    const nls = () => lines.map(Number)

    return { lines, s, n, ss, ns, nls }
  }

  const getInput = () => require('fs').readFileSync('/dev/stdin', 'utf8')

  main(getInput())
}
//  [typescript]
const input = require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);
const nin=()=>{const r = input[0];input.shift();return Number(r);}
const sin=()=>{const r = input[0];input.shift();return String(r);}
const out = (...a) => {console.log(...a);}
const min = (...a) => {return Math.min(...a);}
const rep = (n, callback) => {for(let i = 0;i < n; i++){callback();}}
const main = () => {
  let [p, q, r] = [nin(),nin(),nin()];
  out(min(p + q, q + r, r + p));
}
main();
//  [typescript]
const input = require('fs').readFileSync('/dev/stdin', 'utf8').slice(' ')

console.log(Math.min(input[0]+input[1], input[0]+input[2], input[2]+input[1]))
//  [python]
def main():
    n, *i = map(int, open(0).read().split())
    a = i[:n]
    _ = i[n]
    s = sum(a)

    m = [0] * (10 ** 5 + 1)
    for x in a:
        m[x] += 1

    ans = []
    for b, c in zip(*[iter(i[n + 1:])] * 2):
        m[c] += m[b]
        s += (c - b) * m[b]
        m[b] = 0
        ans.append(s)

    print("\n".join(map(str, ans)))


if __name__ == '__main__':
    main()
//  [python]
# D - Replacing
def main():
    N, *X = map(int, open(0).read().split())
    A, BC = X[:N], X[N + 1 :]
    cnt = [0] * (10 ** 5 + 1)
    for a in A:
        cnt[a] += 1
    total = sum(A)
    res = []
    for b, c in zip(*[iter(BC)] * 2):
        total += (c - b) * cnt[b]
        res.append(total)
        cnt[c] += cnt[b]
        cnt[b] = 0
    print("\n".join(map(str, res)))


if __name__ == "__main__":
    main()
//  [python]
def main():
    n, *i = map(int, open(0).read().split())
    a = i[:n]
    _ = i[n]
    s = sum(a)

    m = [0] * (10 ** 5 + 1)
    for x in a:
        m[x] += 1

    ans = []
    for b, c in zip(*[iter(i[n + 1:])] * 2):
        m[c] += m[b]
        s += (c - b) * m[b]
        m[b] = 0
        ans.append(s)

    print("\n".join(map(str, ans)))

if __name__ == '__main__':
    main()
//  [python]
n=int(input())
dict={}
a=list(map(int,input().split()))
for i in a:
  if i not in dict:
    dict[i]=1
  else:
    dict[i]+=1
q=int(input())
for i in range(q):
  b,c=map(int,input().split())
  ans=0
  if c in dict and b in dict:
    dict[c]+=dict[b]
  elif c not in dict and b in dict:
    dict[c]=dict[b]
  dict[b]=0
  ans=0
  for j in dict:
    ans+=dict[j]*j
  print(ans)
//  [python]
n=int(input())
dict={}
a=list(map(int,input().split()))
for i in a:
  if i not in dict:
    dict[i]=1
  else:
    dict[i]+=1
q=int(input())
for i in range(q):
  b,c=map(int,input().split())
  ans=0
  if c in dict:
    dict[c]+=dict[b]
  else:
    dict[c]=dict[b]
  dict[b]=0
  ans=0
  for j in dict:
    ans+=dict[j]*j
  print(ans)
//  [python]
n=int(input())
dict={}
a=list(map(int,input().split()))
for i in a:
  if i not in dict:
    dict[i]=1
  else:
    dict[i]+=1
q=int(input())
for i in range(q):
  b,c=map(int,input().split())
  ans=0
  for j in dict:
    if j==b:
      ans+=c*dict[b]
    else:
      ans+=j*dict[j]
  if b in dict and c not in dict:
    dict[c]=dict[b]
    dict[b]=0
  elif b in dict and c in dict:
    dict[c]+=dict[b]
    dict[b]=0
  print(ans)
//  [java]
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Map<Long,Long> map = new HashMap<>();
        long ans = 0;
        for(int i = 0; i < n; i++) {
            Long key = sc.nextLong();
            ans += key;
            if(map.containsKey(key)) {
                map.put(key, map.get(key) + 1);
            }else {
                map.put(key, 1l);
            }
        }
        int q = sc.nextInt();
        int[] b = new int[q];
        long[] c = new long[q];
        for (int i = 0; i < q; i++) {
            b[i] = sc.nextInt();
            c[i] = sc.nextLong();
        }
        for (int i = 0; i < q; i++) {
            int key = b[i];
            long val = c[i];
            if(map.containsKey((long)key)) {
                long tmp3 = map.get((long)key);
                ans += (val - key) * tmp3;
                if(map.containsKey(val)) {
                    map.put(val, map.get((long)key) + map.get(val));
                } else {
                    map.put(val, map.get((long)key));
                }
                map.remove(key);
            }
            System.out.println(ans);
        }
    }
}
//  [java]
import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] a=new int[N];
        int[] count=new int[(int)Math.pow(10,5)];
        long res = 0;

        for(int i=0; i<N; i++){
            a[i]=sc.nextInt();
            count[a[i]]++;
            res = res + (long)a[i];
        }

        int Q = sc.nextInt();
        
        for(int i=0; i<Q; i++){
            int b=sc.nextInt();
            int c=sc.nextInt();
            res = res + (c-b)*count[b];
            count[c] += count[b];
            count[b] = 0;
            System.out.println(res);
        }

        
        
        
        
        
        
        
        
        
        }
    }
//  [java]
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ArrayList<Long > a = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            a.add(sc.nextLong());
        }
        int q = sc.nextInt();
        int[] b = new int[q];
        long[] c = new long[q];
        for (int i = 0; i < q; i++) {
            b[i] = sc.nextInt();
            c[i] = sc.nextLong();
        }
        for (int i = 0; i < q; i++) {
            int tmp1 = b[i];
            long tmp2 = c[i];
            Collections.replaceAll(a, (long)tmp1, tmp2);
            long ans = 0;
            for (int j = 0; j < n; j++) {
                ans += a.get(j);
            }
            System.out.println(ans);
        }
    }
}
//  [cpp]
#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
//#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
	tmp = tmp << dig & ma1;
	tmp = tmp * 10 + (tmp >> 8) & ma2;
	tmp = tmp * 100 + (tmp >> 16) & ma3;
	tmp = tmp * 10000 + (tmp >> 32) & ma4;
	ci += 72 - dig >> 3;
	return tmp;
}

//がんばってputintつくるかぁ
const int MAX = 10000;
const int dm = 1 << 17;
char dn[dm], * di = dn, * owad = dn + dm - 20;
class shuturyoku_unko {
public:
	char C[MAX * 4];
	shuturyoku_unko() : C() {
		rep(i, MAX) {
			int X = i;
			rep(j, 4) {
				C[i * 4 + 3 - j] = '0' + X % 10;
				X /= 10;
			}
		}
	}
	void putint(ll A) {
		if (owad < di) {
			fwrite(dn, 1, di - dn, stdout);
			di = dn;
		}
		int dig = 1;
		if (A >= 100000000) {
			if (A >= 10000000000) dig = 3;
			else if (A >= 1000000000) dig = 2;
			memcpy(di + 4 + dig, C + A % 10000 * 4, 4);
			A /= 10000;
			memcpy(di + dig, C + A % 10000 * 4, 4);
			A /= 10000;
			memcpy(di, C + A * 4 + 4 - dig, dig);
			di += 8 + dig;
		}
		else if (A >= 10000) {
			if (A >= 10000000) dig = 4;
			else if (A >= 1000000) dig = 3;
			else if (A >= 100000) dig = 2;
			memcpy(di + dig, C + A % 10000 * 4, 4);
			A /= 10000;
			memcpy(di, C + A * 4 + 4 - dig, dig);
			di += 4 + dig;
		}
		else {
			if (A >= 1000) dig = 4;
			else if (A >= 100) dig = 3;
			else if (A >= 10) dig = 2;
			memcpy(di, C + A * 4 + 4 - dig, dig);
			di += dig;
		}
		*di++ = '\n';
	}
} f;



int A[100001];
int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint();
	ll kotae = 0;
	rep(i, N) {
		int kari = getint();
		A[kari]++;
		kotae += kari;
	}

	int Q = getint();
	rep(i, Q) {
		int b = getint();
		int c = getint();

		A[c] += A[b];
		kotae += A[b] * ll(c - b);
		A[b] = 0;

		f.putint(kotae);
	}


	fwrite(dn, 1, di - dn, stdout);

	Would you please return 0;
}
//  [cpp]
#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>

using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 1 << 17, CL = 12;
char cn[CM + CL], * ci = cn + CM + CL, * owa = cn + CM, ct;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	if (ci - owa > 0) {
		memcpy(cn, owa, CL);
		ci -= CM;
		fread(cn + CL, 1, CM, stdin);
	}
	ll tmp = *(ll*)ci;
	int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
	tmp = tmp << dig & ma1;
	tmp = tmp * 10 + (tmp >> 8) & ma2;
	tmp = tmp * 100 + (tmp >> 16) & ma3;
	tmp = tmp * 10000 + (tmp >> 32) & ma4;
	ci += 72 - dig >> 3;
	return tmp;
}

//がんばってputintつくるかぁ
const int MAX = 10000;
const int dm = 1 << 17;
char dn[dm], * di = dn, * owad = dn + dm - 20;
class shuturyoku_unko {
public:
	char C[MAX * 4];
	shuturyoku_unko() : C() {
		rep(i, MAX) {
			int X = i;
			rep(j, 4) {
				C[i * 4 + 3 - j] = '0' + X % 10;
				X /= 10;
			}
		}
	}
	void putint(ll A) {
		if (owad < di) {
			fwrite(dn, 1, di - dn, stdout);
			di = dn;
		}
		int dig = 1;
		if (A >= 100000000) {
			if (A >= 10000000000) dig = 3;
			else if (A >= 1000000000) dig = 2;
			memcpy(di + 4 + dig, C + A % 10000 * 4, 4);
			A /= 10000;
			memcpy(di + dig, C + A % 10000 * 4, 4);
			A /= 10000;
			memcpy(di, C + A * 4 + 4 - dig, dig);
			di += 8 + dig;
		}
		else if (A >= 10000) {
			if (A >= 10000000) dig = 4;
			else if (A >= 1000000) dig = 3;
			else if (A >= 100000) dig = 2;
			memcpy(di + dig, C + A % 10000 * 4, 4);
			A /= 10000;
			memcpy(di, C + A * 4 + 4 - dig, dig);
			di += 4 + dig;
		}
		else {
			if (A >= 1000) dig = 4;
			else if (A >= 100) dig = 3;
			else if (A >= 10) dig = 2;
			memcpy(di, C + A * 4 + 4 - dig, dig);
			di += dig;
		}
		*di++ = '\n';
	}
} f;



int A[100001];
int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint();
	ll kotae = 0;
	rep(i, N) {
		int kari = getint();
		A[kari]++;
		kotae += kari;
	}

	int Q = getint();
	rep(i, Q) {
		int b = getint();
		int c = getint();

		A[c] += A[b];
		kotae += A[b] * ll(c - b);
		A[b] = 0;

		f.putint(kotae);
	}


	fwrite(dn, 1, di - dn, stdout);

	Would you please return 0;
}
//  [cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <bitset>
#include <queue>
using namespace std;
using ll = long long int;
using P = pair<int, int>;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i <= (int)(n); i++)
const ll INF = 1LL << 60;
ll mod = 1000000007;

vector<int> num(100005,0);

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    int sum = 0;
    rep(i,n) {
        cin >> a[i];
        num[a[i]]++;
        sum += a[i];
    }
    int q;
    cin >> q;
    rep(i,q) {
        int b, c, tmp;
        cin >> b >> c;
        sum = sum - num[b] * b + num[b] * c;
        num[c] += num[b];
        num[b] = 0;
        cout << sum << endl;
    }
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int main(){
  int n;
  cin >> n;
  
  map<int, int> m;
  int x;
  for(int i=0; i<n; i++){
    cin >> x;
    if(m.count(x))
      m[x]++;
    else
      m[x] = 1;
  }
  
  cin >> x;

  for(int i=0; i<x; i++){
    int b, c;
    cin >> b >> c;
    
    if(m.count(c))
      m[c] += m[b];
    else
      m[c] = m[b];
    
    m.erase(b);
    
    long long ans = 0;
    for(auto p : m){
      auto key = p.first;
      auto value = p.second;
      ans += key * value;  
    }
    cout << ans << endl;
  }
}
//  [cpp]
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main(){
    int n,a[100000],q,b,c;
    long long int sum=0;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    cin>>q;
    for(int i=0;i<q;i++){
        sum=0;
        cin>>b>>c;
        for(int i=0;i<n;i++){
            if(a[i]==b){
                a[i]=c;
                sum+=a[i];
            }else sum+=a[i];
        }
        cout<<sum<<"\n";
    }
}
//  [c]
#include <float.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <math.h>
#ifdef __cplusplus
#include <bits/stdc++.h>
#endif

#define getchar getchar
#define putchar putchar
int32_t nextint(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); bool s=false; if(c=='-'){s=true;c=getchar();} uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
int64_t nextlong(void){ char c=getchar(); while(c!='-'&&(c<'0'||'9'<c)) c=getchar(); int s=0; if(c=='-'){s=1;c=getchar();} uint64_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return s?-x:x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }

int a[100001];
int main(void){
	int n=nextint();
	long sum=0;
	for(int i=0; i<n; i++){
		int A=nextint();
		sum+=A;
		a[A]++;
	}
	int q=nextint();
	while(q-->0){
		int B=nextint();
		int C=nextint();
		int k=a[B];
		sum += (long)(C-B)*k;
		printf("%ld\n", sum);
		a[C]+=a[B];
		a[B]=0;
	}
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int acs(const void *a, const void *b) { 
  return *(int*)a - *(int*)b;
} /* 1,2,3,4.. */
int des(const void *a, const void *b) {
  return *(int*)b - *(int*)a;
} /* 8,7,6,5.. */
int cmp_char(const void *a, const void *b) { 
  return *(char*)a - *(char*)b;
} /* a,b,c,d.. */
int cmp_str(const void *a, const void *b) {
  return strcmp(*(const char **)a, *(const char **)b);
} /* aaa,aab.. */
#define min(a,b) (a < b ? a : b)
#define max(a,b) (a > b ? a : b)
#define rep(i, l, r) for (int i = l; i < r; i++)
#define MAX 100001
#define MOD 1000000007
#define INF 1000000009
typedef long long int lli;

int main(void) {
  int N, Q, A;
  int a[MAX] = {0}, B[MAX], C[MAX];
  scanf("%d", &N);
  rep(ni, 0, N) {
    scanf("%d", &A);
    a[A]++;
  }
  scanf("%d", &Q);
  rep(qi, 0, Q) scanf("%d %d", &B[qi], &C[qi]);

  long long int sum = 0;
  rep(ni, 0, MAX) sum += a[ni] * ni;

  rep(qi, 0, Q) {
    int add = C[qi] - B[qi];
    sum += add * a[B[qi]];  // 増加分 × 個数
    a[C[qi]] += a[B[qi]]; a[B[qi]] = 0;
    printf("%lld\n", sum);
  }
  return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int main(void){
	int n;
	int list[100005];

	scanf("%d", &n);
	int in;
	long sum = 0;
	for(int i = 0; i < 100001; list[i++] = 0);
	for(int i = 0; i < n; i++){
		scanf("%d", &in);
		list[in]++;
		sum += in;
	}
	int q;
	scanf("%d", &q);
	int to;
	int from;
	for(int i = 0; i < q; i++){
		scanf("%d %d", &from, &to);
		sum += (to - from) * list[from];
		list[to] += list[from];
		list[from] = 0;
		printf("%ld\n", sum);
	}
	return 0;
}
//  [c]
#include<stdio.h>
 
int main(){
    int N, Q, a[1<<19], b[1<<19], c[1<<19];
    long int S=0;
    scanf("%d", &N);
    for(int i=0; i<N; i++){
        scanf("%d", &a[i]);
    }
    scanf("%d", &Q);
    for(int i=0; i<Q; i++){
        scanf("%d%d", &b[i], &c[i]);
    }
    for(int i=0; i<Q; i++){
        for(int j=0;j<N;j++){
            if(a[j] == b[i]){
                a[j] = c[i];
            }
        } 
        for(int j=0; j<N;j++){
           S = S + a[j];
        }
        printf("%ld\n", S);
        S = 0;
    }
    return 0;
}
//  [c]
#include<stdio.h>
int main()
{
    int n,q,i,j,a,b;
    long long int s=0;
    scanf("%d",&n);
    int ara[10^5];
    for(i=0; i<n; i++)
    {
        scanf("%d",&ara[i]);
    }
    scanf("%d",&q);
    for(i=0; i<q; i++)
    {
        scanf("%d%d",&a,&b);

        long long int s=0;
        for(j=0; j<n; j++)
        {
            if(ara[j]==a)
            {
                ara[j]=b;
            }
            s=s+ara[j];
        }
        printf("%lld\n",s);
    }
    return 0;
}
//  [c]
#include<stdio.h>
int main()
{
    int n,q,i,j,k;
    scanf("%d",&n);
    int ara[10^6];
    int a[2];
    long long int s[1];
    for(i=0; i<n; i++)
    {
        scanf("%d",&ara[i]);
    }
    scanf("%d",&q);
    for(i=0; i<q; i++)
    {
        for(j=0;j<2;j++)
        {
         scanf("%d",&a[j]);
        }
         s[0]=0;
        for(k=0; k<n; k++)
        {
            if(ara[k]==a[0])
            {
                ara[k]=a[1];
            }
        s[0]=s[0]+ara[k];
        }

        printf("%lld\n",s[0]);
    }
    return 0;
}
//  [javascript]
"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(myOut);

function main(){
  var n = next();
  var d = xArray(0,1e5+1);
  var tot = 0;
  for(var i = 0; i < n; i++){
    var a = next();
    d[a]++;
    tot += a;
  }
  var q = next(), ans = Array(q);
  for(var i = 0; i < q; i++){
    var b = next(), c = next();
    d[c] += d[b];
    tot += d[b]*(c-b);
    ans[i] = tot;
    d[b] = 0;
  }
  return ans.join("\n");
}
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const A = arg[1].split(" ").map(n=>parseInt(n));
    const Q = parseInt(arg[2].split(" ")[0]);
    const BC = arg.slice(3, Q + 3);
    
    let map = {};
    let sum = A.reduce((m,n)=>m+n);
    
    let answer = [];
    
    for(let i=0; i<N; i++) {
        if(!map[A[i]]) {
            map[A[i]] = 1;
        } else {
            map[A[i]]++;
        }
    }
    
    // console.log(JSON.stringify(map));
    // console.log(BC);

    for(let i=0; i<Q; i++) {
        const B = parseInt(BC[i].split(" ")[0]);
        const C = parseInt(BC[i].split(" ")[1]);
        
        let abs = C - B;
        
        
        if(map[B]) {
            sum += abs * map[B];
            
            if(map[C]) {
                map[C] += map[B];
            } else {
                map[C] = map[B];
            }
            
            map[B] = false;
        }
        
        answer.push(sum);
    }
    
    console.log(answer.join("\n"));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function Main(input) {
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});
    var N = parseInt(input[0],10);
    var Q = parseInt(input[2], 10);
    var vec_A = input[1].map(e => parseInt(e, 10));
    var v = Array.from({ length: 100000 }, () => 0);;
    for (i = 0; i < v.length; i ++){
        v[vec_A[i]- 1]++;
    }
    ary_bc = Array.from({ length: Q }, () => 0);
    for (var i = 0; i < Q; i++){
        ary_bc[i] = input[i+3].map(e => parseInt(e, 10));
    }
    var vec_S = Array.from({ length: Q }, () => 0);
    var S = sum(vec_A);
    var b, c;

    for (i = 0; i < Q; i++){
        b = ary_bc[i][0];
        c = ary_bc[i][1];
        S += v[b - 1] * (c - b); 
        v[c - 1] += v[b - 1]
        v[b - 1] = 0;
        vec_S[i] = S;
    }
	console.log(vec_S.join('\n'));
}   

var sum  = function(arr) {
    var sum = 0;
    arr.forEach(function(elm) {
        sum += elm;
    });
    return sum;
};

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
    /** 入力値の作成 */
    const arr = input.trim().split('\n');
    const N = Number(arr.shift());
    let Ai = arr.shift().split(' ').map(Number);
    const Q = Number(arr.shift());
    let BiCi = [];
    for(let i=0; i<arr.length; i++){
        BiCi.push(arr[i].trim().split(' ').map(Number));
    }
    /** ここから本処理 */
    let box = new Array(100000).fill(0);
    for(let i=0; i<Ai.length; i++){
        box[Ai[i]]++;
    }
    let sum = Ai.reduce((a,b) => a+b);
    for(let i=0; i<BiCi.length; i++){
        sum +=  (BiCi[i][1] - BiCi[i][0]) * box[BiCi[i][0]];
        box[BiCi[i][1]] += box[BiCi[i][0]];
        box[BiCi[i][0]] = 0;
        console.log(sum);
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
    /** 入力値の作成 */
    const arr = input.trim().split('\n');
    const N = Number(arr.shift());
    const Ai = arr.shift().split(' ').map(Number);
    const Q = Number(arr.shift());
    let BiCi = [];
    for(let i=0; i<arr.length; i++){
        BiCi.push(arr[i].trim().split(' ').map(Number));
    }
    /** ここから本処理 */
    let box = new Array(100000).fill(0);
    for(let i=0; i<Ai.length; i++){
        box[Ai[i]]++;
    }
    log(box);
    let sum = Ai.reduce((a,b) => a+b);
    for(let i=0; i<BiCi.length; i++){
        sum +=  (BiCi[i][1] - BiCi[i][0]) * box[BiCi[i][0]];
        box[BiCi[i][1]] += box[BiCi[i][0]];
        box[BiCi[i][0]] = 0;
        console.log(sum);
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input){
    /** 入力値の作成 */
    const arr = input.trim().split('\n');
    const N = Number(arr.shift());
    const Ai = arr.shift().split(' ').map(Number);
    const Q = Number(arr.shift());
    let BiCi = [];
    for(let i=0; i<arr.length; i++){
        BiCi.push(arr[i].trim().split(' ').map(Number));
    }
    /** ここから本処理 */
    let box = new Array(100000).fill(0);
    for(let i=0; i<Ai.length; i++){
        box[Ai[i]]++;
    }
    log(box);
    let sum = Ai.reduce((a,b) => a+b);
    for(let i=0; i<BiCi.length; i++){
        sum +=  (BiCi[i][1] - BiCi[i][0]) * box[BiCi[i][0]];
        box[BiCi[i][1]] += box[BiCi[i][0]];
        box[BiCi[i][0]] = 0;
        console.log(sum);
    }
}
//  [go]
package main

import (
	"bufio"
	"io"
	"os"
	"strconv"
)

func main() {
	w := bufio.NewWriter(os.Stdout)
	defer w.Flush()

	sc := NewScanner(os.Stdin)
	n := sc.Int()

	m := make(map[int]int)
	var sum int

	for i := 0; i < n; i++ {
		n := sc.Int()
		m[n]++
		sum += n
	}

	q := sc.Int()
	for i := 0; i < q; i++ {
		b, c := sc.Int(), sc.Int()

		count, ok := m[b]
		if !ok {
			w.WriteString(strconv.Itoa(sum))
			w.WriteByte('\n')
			continue
		}

		sum -= b * count
		sum += c * count
		w.WriteString(strconv.Itoa(sum))
		w.WriteByte('\n')

		delete(m, b)
		m[c] += count
	}
}

// generated by https://github.com/murosan/gollect

type Scanner struct {
	r     io.Reader
	buf   []byte
	delim byte
	size, eof,
	start, end int
}

func NewScanner(r io.Reader) *Scanner { return NewScannerSize(r, 4096) }
func NewScannerSize(r io.Reader, size int) *Scanner {
	return &Scanner{
		r:     r,
		buf:   make([]byte, size),
		delim: ' ',
		size:  size, start: size, end: size,
	}
}

func (s *Scanner) Int() int { return ParseInt(s.bytes()) }

func (s *Scanner) bytes() []byte { b, _ := s.next(); return b }
func (s *Scanner) next() (b []byte, size int) {
	for n := 0; ; {
		for i := s.end; i < s.size; i++ {
			if s.buf[i] == s.delim || s.buf[i] == '\n' || i == s.eof {
				b, size = s.buf[s.start:i], i-s.start
				s.start, s.end = i+1, i+1
				return
			}
		}
		s.end = s.size
		if n++; n == 2 {
			panic("lack of buffer size")
		}
		s.read()
	}
}
func (s *Scanner) read() {
	copy(s.buf, s.buf[s.start:s.end])
	s.end -= s.start
	s.start = 0
	n, _ := s.r.Read(s.buf[s.end:])
	s.eof = s.end + n
}

func ParseInt(b []byte) (n int) {
	var i int
	if b[0] == '-' {
		i++
	}
	for ; i < len(b); i++ {
		n *= 10
		n += int(b[i] - '0')
	}
	if b[0] == '-' {
		return -n
	}
	return
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
)

const (
	SCANNER_BUF_SIZE = 2 << 20

	INF = int64(math.MaxInt64)
	MOD = 1e9 + 7
)

var (
	writer  *bufio.Writer
	scanner *bufio.Scanner
)

func init() {
	writer = bufio.NewWriter(os.Stdout)
	scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, SCANNER_BUF_SIZE), SCANNER_BUF_SIZE)
}

func printf(f string, a ...interface{}) {
	fmt.Fprintf(writer, f, a...)
}

func sint64() int64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := int64(0)
	if bb[0] == '-' {
		for _, b := range bb[1:] {
			i *= 10
			i -= int64(b - '0')
		}
		return i
	}
	for _, b := range bb {
		i *= 10
		i += int64(b - '0')
	}
	return i
}

func suint64() uint64 {
	scanner.Scan()
	bb := scanner.Bytes()
	i := uint64(0)
	for _, b := range bb {
		i *= 10
		i += uint64(b - '0')
	}
	return i
}

func sstring() string {
	scanner.Scan()
	return scanner.Text()
}

func gcd(a, b int64) int64 {
	for b != 0 {
		a, b = b, a%b
	}
	return a
}

func lcm(a, b int64) int64 {
	return a * b / gcd(a, b)
}

func abs(a int64) int64 {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r < a {
			a = r
		}
	}
	return a
}

func max(a int64, rest ...int64) int64 {
	for _, r := range rest {
		if r > a {
			a = r
		}
	}
	return a
}

func main() {
	defer writer.Flush()
	n := sint64()
	a := map[int64]int64{}
	for ; n > 0; n-- {
		a[sint64()]++
	}
	totalSum := int64(0)
	for k, v := range a {
		totalSum += k*v
	}
	q := sint64()
	for ; q > 0; q-- {
		b := sint64()
		c := sint64()
		count := a[b]
		totalSum += (c-b)*count
		printf("%d\n", totalSum)
		delete(a, b)
		a[c] += count
	}
}
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	slice := make([]int, n)
	for i := 0; i < n; i++ {
		if i != n-1 {
			fmt.Scanf("%d", &slice[i])
		} else {
			fmt.Scanf("%d\n", &slice[i])
		}
	}

	var q, b, c int
	fmt.Scanf("%d\n", &q)
	out := make([]int, q)
	for i := 0; i < q; i++ {
		fmt.Scanf("%d %d\n", &b, &c)
		for j := 0; j < n; j++ {
			if slice[j] == b {
				slice[j] = c
			}
			out[i] += slice[j]
		}
	}

	for _, j := range out {
		fmt.Println(j)
	}

}
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	slice := make([]int, n)
	for i := 0; i < n; i++ {
		if i != n-1 {
			fmt.Scanf("%d", &slice[i])
		} else {
			fmt.Scanf("%d\n", &slice[i])
		}
	}

	var q, b, c int
	fmt.Scanf("%d\n", &q)
	out := make([]int, q)
	for i := 0; i < q; i++ {
		fmt.Scanf("%d %d\n", &b, &c)
		for j := 0; j < n; j++ {
			if slice[j] == b {
				slice[j] = c
			}
		}

		for _, j := range slice {
			out[i] += j
		}

	}

	for _, j := range out {
		fmt.Println(j)
	}

}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func main() {
	scanInit()

	n := nextInt()
	m := map[int]int{}
	sum := 0
	for i := 0; i < n; i++ {
		tmp := nextInt()
		m[tmp]++
		sum += tmp
	}

	q := nextInt()
	for i := 0; i < q; i++ {
		from := nextInt()
		to := nextInt()

		fromcnt := m[from]
		m[to] += fromcnt
		sum -= from * fromcnt
		sum += to * fromcnt

		fmt.Println(sum)
	}

}

// ---- readfunc
var sc = bufio.NewScanner(os.Stdin)

func scanInit() {
	const cap = 200 * 1024 // default=64*1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [ruby]
N = gets.to_i
counts = Array.new(100000+1, 0)
sum = 0
A = gets.split.each do |i|
  i = i.to_i
  counts[i] += 1
  sum += i
end
Q = gets.to_i

1.upto(Q) do
  b, c = gets.split.map(&:to_i)
  num = counts[b]
  sum += (c - b) * num
  puts sum
  counts[b] = 0
  counts[c] += num
end
//  [ruby]
n = gets.to_i
a = gets.split.map(&:to_i).to_a
q = gets.to_i

dict = [0] * (10**5+1)
ans = a.sum

a.each do |a|
  dict[a] += 1
end

q.times do
  b, c = gets.split.map(&:to_i)
  s = dict[b]
  dict[b] = 0
  ans += c*s
  ans -= b*s
  dict[c] += s
  puts ans
end
//  [ruby]
n = gets.to_i
a = gets.split.map(&:to_i)

count = Array.new(10**5 + 1, 0)
a.each do |aa|
    count[aa] += 1
end
sum = a.inject(:+)
q = gets.to_i
q.times do
    b, c = gets.split.map(&:to_i)
    count[c] += count[b]
    sum += count[b] * (c - b)
    count[b] = 0
    puts sum
end
//  [ruby]
n = gets.to_i
hash = {}
gets.split.map(&:to_i).each do |num|
  hash[num] ||= 0
  hash[num] += 1
end

q = gets.to_i
q.times do
  b, c = gets.split.map(&:to_i)
  hash[c] ||= 0
  hash[c] += hash[b].to_i
  hash[b] = 0

  sum = 0
  hash.each do |num, count|
    sum += num * count
  end
  puts sum
end
//  [ruby]
n = gets.to_i
a = gets.split(" ").map(&:to_i)
z = []
a.length.times{ |i|
  z[a[i]] = a.count(a[i])
}
sum = a.sum
q = gets.to_i
q.times{
  b, c = gets.split(" ").map(&:to_i)
  if z[b] != nil && z[b] > 0
    sum += (c -b) * z[b]
    z[c] ||= 0
    z[c] += z[b]
    z[b] = 0
  end
  p sum
}
//  [ruby]
n = gets.to_i
a = gets.split(" ").map(&:to_i)
q = gets.to_i
q.times{
  b, c = gets.split(" ").map(&:to_i)
  if a.include?(b)
    a.count(b).times{
      a[a.index(b)] = c  
    }
  end
  p a.sum
}
//  [rust]
use proconio::input;

#[proconio::fastout]
pub fn main() {
    input! {
    a:[usize],
    bc:[(usize,usize)],
    }
    let mut acnt = vec![0; 100010];
    let mut s = 0;
    for aval in a {
        s += aval;
        acnt[aval] += 1;
    }
    for (b, c) in bc {
        let bcnt = acnt[b];
        s += c * bcnt;
        s -= b * bcnt;
        acnt[c] += bcnt;
        acnt[b] -= bcnt;
        println!("{}", s);
    }
}
//  [rust]
use proconio::*;

#[fastout]
fn run() {
    input! {
        n: usize,
        a: [usize; n],
        q: usize,
        ask: [(usize, usize); q],
    }
    let m = 100_000;
    let mut cnt = vec![0; m + 1];
    let mut sum = 0;
    for a in a {
        cnt[a] += 1;
        sum += a;
    }
    for (b, c) in ask {
        sum += cnt[b] * (c - b);
        cnt[c] += cnt[b];
        cnt[b] = 0;
        println!("{}", sum);
    }
}

fn main() {
    run();
}
//  [rust]
use std::cmp::*;
use std::io::*;

fn main() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.trim().split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let a: Vec<usize> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();
    let q: usize = itr.next().unwrap().parse().unwrap();

    let mut cnt = vec![0; 100010];
    for i in 0..n {
        cnt[a[i]] += 1;
    }
    let mut sum = a.iter().sum::<usize>();

    let mut out = Vec::new();
    for _ in 0..q {
        let b: usize = itr.next().unwrap().parse().unwrap();
        let c: usize = itr.next().unwrap().parse().unwrap();
        // b -> c
        let v1 = cnt[c] * c;
        let v2 = cnt[b] * b;
        sum -= v2 + v1;
        cnt[c] += cnt[b];
        cnt[b] = 0;
        sum += cnt[c] * c;
        writeln!(out, "{}", sum).ok();
    }
    stdout().write_all(&out).unwrap();
}
//  [rust]
#[allow(unused_imports)]
use proconio::{
    fastout, input,
};

#[fastout]
fn main() {
    input! {
        n: usize,
        a: [i32; n],
        q: usize,
        bc: [(i32, i32); q],
    }
    let mut counter = std::collections::HashMap::new();
    for &v in a.iter() {
        let e = counter.entry(v).or_insert(0);
        *e += 1;
    }
    let mut sum = a.iter().map(|&x| x as i64).sum::<i64>();
    for &(b, c) in bc.iter() {
        let increase = {
            let e = counter.entry(b).or_insert(0);
            sum += ((c - b) as i64) * (*e as i64);
            *e
        };
        let e = counter.entry(c).or_insert(0);
        *e += increase;
        println!("{}", sum);
    }
}
//  [rust]
#![allow(dead_code)]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}
fn read_vec2<T: std::str::FromStr>(n: usize) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}
use std::collections::HashMap;
fn main() {
    let _n: usize = read();
    let a: Vec<i32> = read_vec();
    let q: usize = read();
    let mut hm = HashMap::new();
    let mut ans = 0;
    for i in a {
        *hm.entry(i).or_insert(0) += 1;
        ans += i;
    }
    for _ in 0..q {
        let bc: Vec<i32> = read_vec();
        if let Some(&x) = hm.get(&bc[0]) {
            ans += (bc[1] - bc[0]) * x;
            *hm.entry(bc[1]).or_insert(0) += x;
            *hm.entry(bc[0]).or_insert(0) = 0;
        }
        println!("{}", ans);
    }
}