#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;
}


#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;
}


#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;
}


#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;
  }
}


#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";
    }
}


#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;
	}
}


#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;
}


#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;
}


#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;
}


#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;
}


#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;
}


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


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


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


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


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


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);
    }
}


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
}


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
	}
}


package main

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

const INFINITY = math.MaxInt64/2 - 1

func exec(stdin *Stdin, stdout *Stdout) {
	n := stdin.ReadInt()
	a := stdin.ReadIntSlice(n)

	d := map[int]int{}
	sum := 0
	for _, v := range a {
		sum += v
		if _, ok := d[v]; !ok {
			d[v] = 0
		}
		d[v]++
	}

	q := stdin.ReadInt()
	for i := 0; i < q; i++ {
		b := stdin.ReadInt()
		c := stdin.ReadInt()

		if _, ok := d[b]; !ok {
			stdout.Println(sum)
			continue
		}
		v := d[b]
		sum -= b * v
		sum += c * v
		d[b] -= v
		if _, ok := d[c]; !ok {
			d[c] = 0
		}
		d[c] += v
		stdout.Println(sum)
	}
}

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), INFINITY)
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

func (s *Stdin) ReadIntSlice(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadInt()
	}
	return a
}

func (s *Stdin) ReadStringSlice(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = s.Read()
	}
	return a
}

func (s *Stdin) ReadFloat64Slice(n int) []float64 {
	a := make([]float64, n)
	for i := 0; i < n; i++ {
		a[i] = s.ReadFloat64()
	}
	return a
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}

func Min(a int, b ...int) int {
	for _, v := range b {
		if v < a {
			a = v
		}
	}
	return a
}

func Max(a int, b ...int) int {
	for _, v := range b {
		if a < v {
			a = v
		}
	}
	return a
}

func Abs(x int) int {
	if x > 0 {
		return x
	} else {
		return x * -1
	}
}

func Pow(x, y int) int {
	z := 1
	for y > 0 {
		if y%2 == 0 {
			x *= x
			y /= 2
		} else {
			z *= x
			y -= 1
		}
	}
	return z
}

func IsPrime(x int) bool {
	if x < 2 {
		return false
	}

	for i := 2; i*i <= x; i++ {
		if x%i == 0 {
			return false
		}
	}
	return true
}

// 2以上n未満の素数を列挙する
func Primes(n int) []int {
	isprime := make([]bool, n)
	for i := 2; i < n; i++ {
		isprime[i] = true
	}

	for i := 2; i*i <= n; i++ {
		if !isprime[i] {
			continue
		}

		for j := i + i; j < n; j += i {
			isprime[j] = false
		}
	}

	primes := []int{}
	for i := 2; i < n; i++ {
		if isprime[i] {
			primes = append(primes, i)
		}
	}
	return primes
}

// nを素因数分解する。
// 結果 ... key=素因数 value=数
func PrimeDivision(n int) map[int]int {
	d := map[int]int{}
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			if _, ok := d[i]; !ok {
				d[i] = 0
			}
			d[i]++
			n /= i
		}
	}

	if n > 1 {
		if v, ok := d[n]; ok {
			d[n] = v + 1
		} else {
			d[n] = 1
		}
	}
	return d
}

func Gcd(x, y int) int {
	if x < y {
		x, y = y, x
	}

	for y > 0 {
		x, y = y, x%y
	}

	return x
}

func Lcm(x, y int) int {
	return x * y / Gcd(x, y)
}

func CeilDiv(x, y int) int {
	if x%y == 0 {
		return x / y
	} else {
		return x/y + 1
	}
}

func LCS(s, t string) string {
	n := len(s)
	m := len(t)
	dp := make([][]int, n+1)
	for i := 0; i <= n; i++ {
		dp[i] = make([]int, m+1)
	}

	for i := 1; i <= n; i++ {
		for j := 1; j <= m; j++ {
			if s[i-1] == t[j-1] {
				dp[i][j] = dp[i-1][j-1] + 1
			} else {
				dp[i][j] = Max(dp[i-1][j], dp[i][j-1])
			}
		}
	}

	x := n
	y := m
	u := make([]byte, dp[n][m])
	i := dp[n][m] - 1
	for x > 0 && y > 0 {
		if dp[x][y] == dp[x-1][y] {
			x--
		} else if dp[x][y] == dp[x][y-1] {
			y--
		} else {
			x--
			y--
			u[i] = s[x]
			i--
		}
	}

	return string(u)
}

// [0..n) から r個選んだ組合せを生成する。
// r < 0 の場合はすべての組合せを生成する。
func Combinations(n int, r int) [][]int {
	a := [][]int{}
	for i := uint(0); i < (1 << uint(n)); i++ {
		b := []int{}
		for j := uint(0); j < uint(n); j++ {
			if i&(uint(1)<<j) != 0 {
				b = append(b, int(j))
			}
		}

		if r < 0 || len(b) == r {
			a = append(a, b)
		}
	}
	return a
}

// [0..n)の順列を生成する。
func Permutations(n int) [][]int {
	type e struct {
		bit uint
		a   []int
	}

	q := []*e{}
	for i := 0; i < n; i++ {
		q = append(q, &e{bit: 1 << uint(i), a: []int{i}})
	}

	p := [][]int{}
	for x := 0; x < len(q); x++ {
		cur := q[x]
		if cur.bit == (1<<uint(n) - 1) {
			p = append(p, cur.a)
			continue
		}

		for i := 0; i < n; i++ {
			if cur.bit&(1<<uint(i)) != 0 {
				continue
			}

			m := len(cur.a) + 1
			b := make([]int, m)
			copy(b, cur.a)
			b[m-1] = i
			q = append(q, &e{bit: cur.bit | (1 << uint(i)), a: b})
		}
	}
	return p
}

func ReverseSlice(v interface{}) {
	if reflect.TypeOf(v).Kind() == reflect.Slice {
		slice := reflect.ValueOf(v)
		for i1, n := 0, slice.Len(); i1 < n/2; i1++ {
			i2 := n - i1 - 1
			v1 := reflect.ValueOf(slice.Index(i1).Interface())
			slice.Index(i1).Set(slice.Index(i2))
			slice.Index(i2).Set(v1)
		}
	}
}

func ReverseString(s string) string {
	t := []rune(s)
	ReverseSlice(t)
	return string(t)
}

func ToStringSlice(slice interface{}) []string {
	// 本来はerrを返却すべき。 利用する側(=自分)は引数がsliceであることを知っている。
	if reflect.TypeOf(slice).Kind() != reflect.Slice {
		panic(fmt.Sprintf("%v is not slice", slice))
	}

	src := reflect.ValueOf(slice)
	n := src.Len()
	dst := make([]string, n)
	for i := 0; i < n; i++ {
		dst[i] = fmt.Sprintf("%v", src.Index(i))
	}
	return dst
}


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

}


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

}


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()
}


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


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


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


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


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
}


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
}


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);
    }
}


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();
}


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();
}


#[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);
    }
}


#![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);
    }
}


use std::*;
use std::io::{stderr, stdin, stdout, BufReader, BufWriter, Cursor, Read, Write};
use std::iter::Iterator;
use std::str::FromStr;
#[allow(unused_imports)]
use std::fmt::{Display, Formatter};
use std::collections::HashMap;

#[allow(dead_code)]
fn main() {
  let stdin = stdin();
  let r = &mut BufReader::new(stdin.lock());
  let stdout = stdout();
  let w = &mut BufWriter::new(stdout.lock());
  let stderr = stderr();
  let err = &mut BufWriter::new(stderr.lock());
  run(r, w, err);
  w.flush().unwrap();
  err.flush().unwrap();
}

macro_rules! _ft { () => (impl FnOnce(&mut Cursor<Vec<u8>>, &mut Vec<u8>, &mut Vec<u8>)); }

#[allow(dead_code)]
fn test(input: &str, output: &str, f: _ft!()) {
  let r = &mut Cursor::new(input.as_bytes().to_vec());
  let w: &mut Vec<u8> = &mut Vec::new();
  let err: &mut Vec<u8> = &mut Vec::new();
  f(r, w, err);
  let mut stderr = stderr();
  writeln!(stderr, "{}", String::from_utf8(err.to_vec()).unwrap()).unwrap();
  stderr.flush().ok();
  assert_eq!(String::from_utf8(w.to_vec()).unwrap(), output)
}

#[allow(dead_code)]
macro_rules! t {
  ($f: ident => $input: expr, $output: expr) => (
    #[test]
    fn $f() { test($input, $output, run); }
  );
}

macro_rules! _display_st {
    ($f: expr; $name: expr, ) => (write!($f, "{}", $name)?);
    ($f: expr; $name: expr) => (_display_st!($f; $name, ));
    ($f: expr; $name: expr, $($rest: expr),+, ) => (
      _display_st!($f; $name);
      write!($f, " ")?;
      _display_st!($f; $($rest, )+);
    );
    ($f: expr; $name: expr, $($rest: expr),+) => (_display_st!($f; $name, $($rest, )+));
}

/// 構造体を作成する
#[allow(unused_macros)]
macro_rules! st {
  ($name: ident => $($p: ident : $t: ty),+) => (
    struct $name { $($p : $t),+ }
    impl FromStr for $name {
      type Err = ();
      fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut iter = s.split_whitespace();
        Ok(Self {
          $($p: iter.next().unwrap().parse::<$t>().unwrap(),)+
        })
      }
    }
    impl Display for $name {
      fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        _display_st!(f; $(&self.$p, )+);
        Ok(())
      }
    }
  );
  ($name: ident => $($($p: ident),+: $t: ty);+) => (st!($name => $($($p : $t),+),+););
  ($name: ident => $($($p: ident),+: $($t: ty),+);+) => (st!($name => $($($p : $t),+),+););
  ($name: ident => $($p: ident),+: $t: ty) => (st!($name => $($p : $t),+););
  ($name: ident => $($p: ident),+: $($t: ty),+) => (st!($name => $($p : $t),+););
}

fn _read_iter<R: Read>(reader: &mut R) -> impl Iterator<Item=char> + '_ {
  reader.by_ref()
    .bytes()
    .map(|c| c.unwrap() as char)
    .skip_while(|c| c.is_whitespace())
}

#[allow(dead_code)]
fn read<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = _read_iter(reader).take_while(|c| !c.is_whitespace()).collect::<String>();
  str.parse::<F>().ok().unwrap()
}

#[allow(dead_code)]
fn read_line<F: FromStr, R: Read>(reader: &mut R) -> F {
  let str = _read_iter(reader).take_while(|c| c != &'\n').collect::<String>();
  let str = if str.ends_with('\r') { &str[0..str.len() - 1] } else { &str };
  str.parse::<F>().ok().unwrap()
}

#[allow(dead_code)]
fn read1<R: Read, T>(reader: &mut R, mut f: impl FnMut(char) -> T) -> T {
  f(_read_iter(reader).next().unwrap())
}

#[allow(dead_code)]
fn read1_line<R: Read, T>(reader: &mut R, f: impl FnMut(char) -> T) -> Vec<T> {
  _read_iter(reader).take_while(|c| c != &'\n').map(f).collect::<Vec<_>>()
}

/// 1要素読む
#[allow(unused_macros)]
macro_rules! r {
  ($stream: expr) => (read::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));

  ($stream: expr; $t: ty) => (read::<$t, _>($stream));
  ($stream: expr; $t: ty; 1~) => (r!($stream; $t) - 1);

  ($stream: expr; $($t: ty),+) => (($(r!($stream; $t)),*));
  ($stream: expr; $($t: ty),+; 1~) => (($(r!($stream; $t) - 1),*));

  ($stream: expr; $t: ty; $n: expr) => (
    (0..$n).map(|_| r!($stream; $t)).collect::<Vec<_>>()
  );
  ($stream: expr; $t: ty; $n: expr; 1~) => (
    (0..$n).map(|_| r!($stream; $t) - 1).collect::<Vec<_>>()
  );

  ($stream: expr; $t: ty; $h: expr, $w: expr) => (
    (0..$h).map(|_| (0..$w).map(|_| r!($stream; $t)).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
  ($stream: expr; $t: ty; $h: expr, $w: expr; 1~) => (
    (0..$h).map(|_| (0..$w).map(|_| r!($stream; $t) - 1).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
}

/// 1文字読む
#[allow(unused_macros)]
macro_rules! r1 {
  ($stream: expr) => (read1($stream, |c| c));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $f: expr) => (read1($stream, $f));
  ($stream: expr; $f: expr; $n: expr) => ((0..$n).map(|_| r1!($stream; $f)).collect::<Vec<_>>());
  ($stream: expr; $f: expr; $h: expr, $w: expr) => (
    (0..$h).map(|_| (0..$w).map(|_| r1!($stream; $f)).collect::<Vec<_>>()).collect::<Vec<_>>()
  );
}

/// 1行読む
#[allow(unused_macros)]
macro_rules! rl {
  ($stream: expr) => (read_line::<String, _>($stream));
  ($stream: expr, ) => (r!($stream));
  ($stream: expr; ) => (r!($stream));
  ($stream: expr; $t: ty) => (read_line::<$t,  _>($stream));
  ($stream: expr; $t: ty; $n: expr) => ((0..$n).map(|_| rl!($stream; $t)).collect::<Vec<_>>());
}

macro_rules! _writes {
  ($stream: expr; $arg0: expr, $($arg: expr),*) => ({
    write!($stream, "{}", $arg0).ok();
    $(write!($stream, " {}", $arg).ok();)*
  });
}

/// 変数を出力
#[allow(unused_macros)]
macro_rules! w {
  ($stream: expr) => (write!($stream, " ").ok());
  ($stream: expr; ) => (w!($stream));
  ($stream: expr, ) => (w!($stream));

  ($stream: expr; $arg: expr) => (write!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (w!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => (_writes!($stream; $arg0, $($arg),+));
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (w!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (write!($stream, $($arg)*).ok());
}

/// 変数を改行付きで出力
#[allow(unused_macros)]
macro_rules! wl {
  ($stream: expr) => (writeln!($stream).ok());
  ($stream: expr, ) => (wl!($stream));
  ($stream: expr; ) => (wl!($stream));

  ($stream: expr; $arg: expr) => (writeln!($stream, "{}", $arg).ok());
  ($stream: expr; $arg: expr, ) => (wl!($stream; $arg));

  ($stream: expr; $arg0: expr, $($arg: expr),+) => ({
    _writes!($stream; $arg0, $($arg),+);
    wl!($stream)
  });
  ($stream: expr; $arg0: expr, $($arg: expr),+, ) => (wl!($stream; $arg0, $($arg),*));

  ($stream: expr, $($arg: tt)*) => (writeln!($stream, $($arg)*).ok());
}

/// ベクタを出力
#[allow(unused_macros)]
macro_rules! w_vec {
  ($stream: expr; $vec: expr) => ({
    let mut iter = $vec.iter();
    match iter.next() { Some(&i) => { w!($stream; i); }, None => {}, }
    for &i in iter { w!($stream; i); }
  });

  ($stream: expr; $vec: expr; $n: expr) => (w_vec!($stream; $vec => |e| e, " "; $n));
  ($stream: expr; $vec: expr => $f: expr; $n: expr) => (w_vec!($stream; $vec => $f, ""; $n));
  ($stream: expr; $vec: expr => $f: expr, $del: expr; $n: expr) => (
    w!($stream; $f($vec[0]));
    for i in 1..$n { w!($stream, "{}{}", $del, $f($vec[i as usize])); }
  );
}

/// ベクタを改行付きで出力
#[allow(unused_macros)]
macro_rules! wl_vec {
  ($stream: expr; $vec: expr) => (for &i in $vec.iter() { wl!($stream; i); });

  ($stream: expr; $vec: expr; $n: expr) => (wl_vec!($stream; $vec => |e| e; $n));
  ($stream: expr; $vec: expr => $f: expr; $n: expr) => (
    for i in 0..$n { wl!($stream; $f($vec[i as usize])); }
  );

  ($stream: expr; $vec: expr; $h: expr, $w: expr) => (wl_vec!($stream; $vec => |e| e, " "; $h, $w));
  ($stream: expr; $vec: expr => $f: expr; $h: expr, $w: expr) => (
    wl_vec!($stream; $vec => $f, ""; $h, $w)
  );
  ($stream: expr; $vec: expr => $f: expr, $del: expr; $h: expr, $w: expr) => (
    for i in 0..$h {
      w!($stream; $f($vec[i as usize][0]));
      for j in 1..$w { w!($stream, "{}{}", $del, $f($vec[i as usize][j as usize])); }
      wl!($stream);
    }
  );
}

#[allow(unused_variables)]
fn run<R: Read, W: Write, E: Write>(r_: &mut R, w_: &mut W, err: &mut E) {
  let n = r!(r_; usize);
  let a = r!(r_; i64; n);
  let q = r!(r_; usize);
  st!(BC => b, c: i64);
  let bc = rl!(r_; BC; q);

  let mut d = HashMap::new();
  let mut sum = 0;
  for i in 0..n {
    let v = a[i];
    if d.contains_key(&v) { *d.get_mut(&v).unwrap() += 1; }
    else { d.insert(v, 1usize); }
    sum += v;
  }

  for i in 0..q {
    let d_b = bc[i].b;
    if !d.contains_key(&d_b) {
      wl!(w_; sum);
      continue;
    }
    let d_c = bc[i].c;
    let value = d[&d_b];
    sum += value as i64 * (d_c - d_b);
    if d.contains_key(&d_c) { *d.get_mut(&d_c).unwrap() += value; }
    else { d.insert(d_c, value); }
    *d.get_mut(&d_b).unwrap() += 0;
    wl!(w_; sum);
  }
}

t!(td1 => r"4
1 2 3 4
3
1 2
3 4
2 4", r"11
12
16
");
t!(td2 => r"4
1 1 1 1
3
1 2
2 1
3 5", r"8
4
4
");
t!(td3 => r"2
1 2
3
1 100
2 100
100 1000", r"102
200
2000
");


import Foundation
let main: () = {
    let N = nextInt()
    let A = listOfInt()
    var S = IntArray(100001)
    let Q = nextInt()
    for a in A { S[a] += 1 }
    var ans = 0
    for (n, s) in S.enumerated() { ans += n * s }
    repeate(Q) {
        let (b, c) = *listOfInt()
        S[c] += S[b]
        ans += S[b] * (c - b)
        S[b] = 0
        print(ans)
    }
}()

struct SimpleModInt {
    let MOD = 998244353
    var value: Int {
        didSet {
            value %= MOD
        }
    }
    init(_ initialValue: Int) {
        value = initialValue
        value %= MOD
    }
    init(_ initialValue: SimpleModInt) {
        value = initialValue.value
        value %= MOD
    }
}
infix operator <-: AssignmentPrecedence
extension SimpleModInt {
    static func + (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value + right) }
    static func + (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value + right.value) }
    static func - (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value - right) }
    static func - (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value - right.value) }
    static func * (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value * right) }
    static func * (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value * right.value) }
    static func <- (left: inout SimpleModInt, right: Int) { left.value = right }
    static func <- (left: inout SimpleModInt, right: SimpleModInt) { left.value = right.value }
    static func += (left: inout SimpleModInt, right: Int) { left.value += right }
    static func += (left: inout SimpleModInt, right: SimpleModInt) { left.value += right.value }
    static func -= (left: inout SimpleModInt, right: Int) { left.value -= right }
    static func -= (left: inout SimpleModInt, right: SimpleModInt) { left.value -= right.value }
    static func *= (left: inout SimpleModInt, right: Int) { left.value *= right }
    static func *= (left: inout SimpleModInt, right: SimpleModInt) { left.value *= right.value }
    static func == (left: SimpleModInt, right: Int) -> Bool { left.value == SimpleModInt(right).value }
    static func == (left: SimpleModInt, right: SimpleModInt) -> Bool { left.value == right.value }
    static func != (left: SimpleModInt, right: Int) -> Bool { left.value != SimpleModInt(right).value }
    static func != (left: SimpleModInt, right: SimpleModInt) -> Bool { left.value != right.value }
}

//----------------------------------

let dx = [1, 0, -1, 0] //[1, 0, -1, 0, -1,  1, -1, 1]
let dy = [0, 1, 0, -1] //[0, 1, 0, -1, -1, -1,  1, 1]

@inlinable func gcd(_ a: Int, _ b: Int) -> Int { (b > 0) ? gcd(b, a % b) : a }
@inlinable func lcm(_ a: Int, _ b: Int) -> Int { a / gcd(a, b) * b }

//----------------------------------

infix operator  =~ : ComparisonPrecedence
infix operator !=~ : ComparisonPrecedence
func =~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { !(right ~= left) }
func =~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { !(right ~= left) }

func =~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { right.contains(left) }
func !=~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { !right.contains(left) }

infix operator /^ : MultiplicationPrecedence
infix operator /^= : AssignmentPrecedence
func /^ <T: FixedWidthInteger>(left: T, right: T) -> T { (left + (right - 1)) / right }
func /^= <T: FixedWidthInteger>(left: inout T, right: T) { left = (left + (right - 1)) / right }

@inlinable func chmax<T: Comparable>(_ m: inout T, _ q: T) { if (m < q) { m = q } }
@inlinable func chmin<T: Comparable>(_ m: inout T, _ q: T) { if (m > q) { m = q } }
@inlinable func chRmax<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m < q) { m = q; return true } else { return false } }
@inlinable func chRmin<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m > q) { m = q; return true } else { return false } }

prefix operator *
prefix func * <T> (a: [T]) -> (T, T) { (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T) { (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4], a[5]) }

func printErr(_ str: String, terminator: String = "\n") {
    let s = str + terminator
    FileHandle.standardError.write(s.data(using: .utf8)!)
    FileHandle.standardError.synchronizeFile()
}

@inlinable func next() -> String { readLine()! }
@inlinable func nextInt() -> Int { Int(next())! }
@inlinable func nextDouble() -> Double { Double(next())! }
@inlinable func listOfString() -> [String] { next().split(separator: " ").map(String.init) }
@inlinable func listOfInt() -> [Int] { listOfString().map { Int($0)! } }
@inlinable func listOfInt(_ offset: Int = 0) -> [Int] { listOfString().map { Int($0)! + offset } }
@inlinable func listOfInt(_ offsets: Int ...) -> [Int] { listOfString().enumerated().map { Int($0.element)! + offsets[$0.offset % offsets.count] } }
@inlinable func listOfDouble(_ offset: Double = 0.0) -> [Double] { listOfString().map { Double($0)! + offset } }
@inlinable func listOfDouble(_ offsets: Double ...) -> [Double] { listOfString().enumerated().map { Double($0.element)! + offsets[$0.offset % offsets.count] } }

extension Int {
    init(s: String) { self.init(s)! }
    var isEven: Bool { self.isMultiple(of: 2) }
    var isOdd: Bool { !self.isEven }
    var isTrue: Bool { self != 0 }
    var isFalse: Bool { !self.isTrue }
    var toString: String { String(self) }
    var toChar: Character { Character(UnicodeScalar(UInt8(self))) }
}
func + (left: Int, right: Bool) -> Int { left + (right ? 1 : 0) }
extension Character {
    var asciiCode: Int { Int(self.asciiValue!) }
    var string: String { String(self) }
}
extension String {
    @inlinable subscript (position: Int) -> Character { self[self.index(self.startIndex, offsetBy: position)] }
    @inlinable func repeate(_ times: Int) -> String { String(repeating: self, count: times) }
    //  @inlinable subscript (n: Int) -> String { String(self[self.index(self.startIndex, offsetBy: n)]) }
    //  @inlinable subscript (n: Int) -> Int { Int(self[self.index(self.startIndex, offsetBy: n)].asciiValue!) }
    var toInt: Int { Int(self)! }
}
extension String { // VB like
    @inlinable func _index(_ position: Int) -> String.Index! {
        if !(0 ..< self.count ~= position) { return nil }
        return self.index(self.startIndex, offsetBy: position)
    }
    @inlinable func mid(from index: Int, length: Int) -> String! {
        if let startPosition = self._index(index) {
            if let endPosition = self._index(index + length - 1) {
                return String(self[startPosition...endPosition])
            } else {
                let endPosition = self.index(before: self.endIndex)
                return String(self[startPosition...endPosition])
            }
        }
        return ""
    }
    @inlinable func left(_ length: Int) -> String { String(self.prefix(length)) }
    @inlinable func right(_ length: Int) -> String { String(self.suffix(length)) }
}

extension Dictionary {
    @inlinable mutating func getOrSet(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored }
        else {
            let newValue = defaultValue()
            self[key] = newValue
            return newValue
        }
    }
    @inlinable mutating func getOrElse(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored } else { return defaultValue() }
    }
    @inlinable func containsKey(_ key: Key) -> Bool { self.keys.contains(key) }
}

extension Set {
    static func += (left: inout Set<Element>, right: Element) { left.insert(right) }
    static func -= (left: inout Set<Element>, right: Element) { left.remove(right) }
}

extension Array {
    static func += (left: inout Array<Element>, right: Element) { left.append(right) }
    init(_ size: Int, _ initValue: ((Int) -> Element)) {
        self = [Element]()
        for index in 0 ..< size {
            let value = initValue(index)
            self.append(value)
        }
    }
    init(_ size: Int, _ initValue: (() -> Element)) {
        self = [Element]()
        for _ in 0 ..< size {
            let value = initValue()
            self.append(value)
        }
    }
}
typealias IntArray = Array<Int>
typealias DoubleArray = Array<Double>
typealias BoolArray = Array<Bool>
typealias StringArray = Array<String>

extension Array where Element == Int {
    init(_ size: Int) {
        self = [Element](repeating: 0, count: size)
    }
}
extension Array where Element == Double {
    init(_ size: Int) {
        self = [Element](repeating: 0.0, count: size)
    }
}
extension Array where Element == Bool {
    init(_ size: Int) {
        self = [Element](repeating: false, count: size)
    }
}
extension Array where Element == String {
    init(_ size: Int) {
        self = [Element](repeating: "", count: size)
    }
}

extension Array {
    @inlinable func count(_ predicate: ((Element) -> Bool)) -> Int {
        var cnt = 0; for e in self { if (predicate(e)) { cnt += 1 } }
        return cnt
    }
    @inlinable func groupBy<K>(_ keySelector: (Element) -> K) -> [K : [Element]] {
        var destination = [K : [Element]]()
        for element in self {
            let key = keySelector(element)
            var list = destination.getOrSet(key) { [Element]() }
            list.append(element)
            destination[key] = list
        }
        return destination
    }
    @inlinable func groupByIndexed<K>(_ keySelector: (Element) -> K) -> [K : [Int]] {
        var destination = [K : [Int]]()
        for element in self.enumerated() {
            let key = keySelector(element.element)
            var list = destination.getOrSet(key) { [Int]() }
            list.append(element.offset)
            destination[key] = list
        }
        return destination
    }
}

extension Array {
    func binarySearch(_ element: Element, by compare: (Element, Element) -> Int, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            let cmp = compare(midVal, element)
            if (cmp < 0) { low = mid + 1 }          //-1
            else if (0 < cmp) { high = mid - 1 }    // 1
            else { return mid } // key found        // 0
        }
        return -(low + 1)  // key not found
    }
}
extension Array where Element : Comparable {
    func binarySearch(_ element: Element, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            if (midVal < element) { low = mid + 1 }
            else if (midVal > element) { high = mid - 1 }
            else { return mid } // key found
        }
        return -(low + 1)  // key not found
    }
}

extension Array where Element == Int {
    @inlinable func distinct() -> [Element] {
        var set = Set<Element>(), ary = [Element]()
        for n in self.indices { if !set.contains(self[n]) { ary.append(self[n]); set.insert(self[n]) } }
        return ary
    }
    @inlinable func any(_ predicate: (Element) -> Bool) -> Bool {
        var any = false; for element in self { if predicate(element) { any = true } }
        return any
    }
    @inlinable func all(_ predicate: (Element) -> Bool) -> Bool {
        self.allSatisfy(predicate)
    }
    @inlinable func sum() -> Element { self.reduce(0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}

extension Array where Element == Double {
    @inlinable func sum() -> Element { self.reduce(0.0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0.0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}
extension Array where Element == String {
    @inlinable func toIntDouble() -> (Int, Double) { (Int(self[0])!, Double(self[1])!) }
    @inlinable func toIntString() -> (Int, String) { (Int(self[0])!, self[1]) }
    @inlinable func toIntIntString() -> (Int, Int, String) { (Int(self[0])!, Int(self[1])!, self[2]) }
}

@inlinable func block( _ action: () -> Void) {
    action()
}
@inlinable func repeate(_ times1: Int, _ action: () -> Void) {
    for _ in 0 ..< times1 { action() }
}
@inlinable func repeate(_ times1: Int, _ action: (Int) -> Void) {
    for index1 in 0 ..< times1 {
        action(index1)
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ action: (Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            action(index1, index2)
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ action: (Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                action(index1, index2, index3)
            }
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ times4: Int, _ action: (Int, Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                for index4 in 0 ..< times4 {
                    action(index1, index2, index3, index4)
                }
            }
        }
    }
}

func measureTimeSeconds(block: (() -> Void)) -> Double {
    let startTime = Date()
    block()
    let duration = -startTime.timeIntervalSinceNow
    return duration
}


import Foundation
let main: () = {
    let N = nextInt()
    let A = listOfInt()
    var S = IntArray(100001)
    let Q = nextInt()
    for a in A {
        S[a] += 1
    }
    var ans = 0
    for (n, s) in S.enumerated() {
        ans += n * s
    }
    repeate(Q) {
        let (b, c) = *listOfInt()
        S[c] += S[b]
        ans += S[b] * (c - b)
        S[b] = 0
        print(ans)
    }
}()

struct SimpleModInt {
    let MOD = 998244353
    var value: Int {
        didSet {
            value %= MOD
        }
    }
    init(_ initialValue: Int) {
        value = initialValue
        value %= MOD
    }
    init(_ initialValue: SimpleModInt) {
        value = initialValue.value
        value %= MOD
    }
}
infix operator <-: AssignmentPrecedence
extension SimpleModInt {
    static func + (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value + right) }
    static func + (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value + right.value) }
    static func - (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value - right) }
    static func - (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value - right.value) }
    static func * (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value * right) }
    static func * (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value * right.value) }
    static func <- (left: inout SimpleModInt, right: Int) { left.value = right }
    static func <- (left: inout SimpleModInt, right: SimpleModInt) { left.value = right.value }
    static func += (left: inout SimpleModInt, right: Int) { left.value += right }
    static func += (left: inout SimpleModInt, right: SimpleModInt) { left.value += right.value }
    static func -= (left: inout SimpleModInt, right: Int) { left.value -= right }
    static func -= (left: inout SimpleModInt, right: SimpleModInt) { left.value -= right.value }
    static func *= (left: inout SimpleModInt, right: Int) { left.value *= right }
    static func *= (left: inout SimpleModInt, right: SimpleModInt) { left.value *= right.value }
    static func == (left: SimpleModInt, right: Int) -> Bool { left.value == SimpleModInt(right).value }
    static func == (left: SimpleModInt, right: SimpleModInt) -> Bool { left.value == right.value }
    static func != (left: SimpleModInt, right: Int) -> Bool { left.value != SimpleModInt(right).value }
    static func != (left: SimpleModInt, right: SimpleModInt) -> Bool { left.value != right.value }
}

//----------------------------------

let dx = [1, 0, -1, 0] //[1, 0, -1, 0, -1,  1, -1, 1]
let dy = [0, 1, 0, -1] //[0, 1, 0, -1, -1, -1,  1, 1]

@inlinable func gcd(_ a: Int, _ b: Int) -> Int { (b > 0) ? gcd(b, a % b) : a }
@inlinable func lcm(_ a: Int, _ b: Int) -> Int { a / gcd(a, b) * b }

//----------------------------------

infix operator  =~ : ComparisonPrecedence
infix operator !=~ : ComparisonPrecedence
func =~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { !(right ~= left) }
func =~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { !(right ~= left) }

func =~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { right.contains(left) }
func !=~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { !right.contains(left) }

infix operator /^ : MultiplicationPrecedence
infix operator /^= : AssignmentPrecedence
func /^ <T: FixedWidthInteger>(left: T, right: T) -> T { (left + (right - 1)) / right }
func /^= <T: FixedWidthInteger>(left: inout T, right: T) { left = (left + (right - 1)) / right }

@inlinable func chmax<T: Comparable>(_ m: inout T, _ q: T) { if (m < q) { m = q } }
@inlinable func chmin<T: Comparable>(_ m: inout T, _ q: T) { if (m > q) { m = q } }
@inlinable func chRmax<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m < q) { m = q; return true } else { return false } }
@inlinable func chRmin<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m > q) { m = q; return true } else { return false } }

prefix operator *
prefix func * <T> (a: [T]) -> (T, T) { (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T) { (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4], a[5]) }

func printErr(_ str: String, terminator: String = "\n") {
    let s = str + terminator
    FileHandle.standardError.write(s.data(using: .utf8)!)
    FileHandle.standardError.synchronizeFile()
}

@inlinable func next() -> String { readLine()! }
@inlinable func nextInt() -> Int { Int(next())! }
@inlinable func nextDouble() -> Double { Double(next())! }
@inlinable func listOfString() -> [String] { next().split(separator: " ").map(String.init) }
@inlinable func listOfInt() -> [Int] { listOfString().map { Int($0)! } }
@inlinable func listOfInt(_ offset: Int = 0) -> [Int] { listOfString().map { Int($0)! + offset } }
@inlinable func listOfInt(_ offsets: Int ...) -> [Int] { listOfString().enumerated().map { Int($0.element)! + offsets[$0.offset % offsets.count] } }
@inlinable func listOfDouble(_ offset: Double = 0.0) -> [Double] { listOfString().map { Double($0)! + offset } }
@inlinable func listOfDouble(_ offsets: Double ...) -> [Double] { listOfString().enumerated().map { Double($0.element)! + offsets[$0.offset % offsets.count] } }

extension Int {
    init(s: String) { self.init(s)! }
    var isEven: Bool { self.isMultiple(of: 2) }
    var isOdd: Bool { !self.isEven }
    var isTrue: Bool { self != 0 }
    var isFalse: Bool { !self.isTrue }
    var toString: String { String(self) }
    var toChar: Character { Character(UnicodeScalar(UInt8(self))) }
}
func + (left: Int, right: Bool) -> Int { left + (right ? 1 : 0) }
extension Character {
    var asciiCode: Int { Int(self.asciiValue!) }
    var string: String { String(self) }
}
extension String {
    @inlinable subscript (position: Int) -> Character { self[self.index(self.startIndex, offsetBy: position)] }
    @inlinable func repeate(_ times: Int) -> String { String(repeating: self, count: times) }
    //  @inlinable subscript (n: Int) -> String { String(self[self.index(self.startIndex, offsetBy: n)]) }
    //  @inlinable subscript (n: Int) -> Int { Int(self[self.index(self.startIndex, offsetBy: n)].asciiValue!) }
    var toInt: Int { Int(self)! }
}
extension String { // VB like
    @inlinable func _index(_ position: Int) -> String.Index! {
        if !(0 ..< self.count ~= position) { return nil }
        return self.index(self.startIndex, offsetBy: position)
    }
    @inlinable func mid(from index: Int, length: Int) -> String! {
        if let startPosition = self._index(index) {
            if let endPosition = self._index(index + length - 1) {
                return String(self[startPosition...endPosition])
            } else {
                let endPosition = self.index(before: self.endIndex)
                return String(self[startPosition...endPosition])
            }
        }
        return ""
    }
    @inlinable func left(_ length: Int) -> String { String(self.prefix(length)) }
    @inlinable func right(_ length: Int) -> String { String(self.suffix(length)) }
}

extension Dictionary {
    @inlinable mutating func getOrSet(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored }
        else {
            let newValue = defaultValue()
            self[key] = newValue
            return newValue
        }
    }
    @inlinable mutating func getOrElse(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored } else { return defaultValue() }
    }
    @inlinable func containsKey(_ key: Key) -> Bool { self.keys.contains(key) }
}

extension Set {
    static func += (left: inout Set<Element>, right: Element) { left.insert(right) }
    static func -= (left: inout Set<Element>, right: Element) { left.remove(right) }
}

extension Array {
    static func += (left: inout Array<Element>, right: Element) { left.append(right) }
    init(_ size: Int, _ initValue: ((Int) -> Element)) {
        self = [Element]()
        for index in 0 ..< size {
            let value = initValue(index)
            self.append(value)
        }
    }
    init(_ size: Int, _ initValue: (() -> Element)) {
        self = [Element]()
        for _ in 0 ..< size {
            let value = initValue()
            self.append(value)
        }
    }
}
typealias IntArray = Array<Int>
typealias DoubleArray = Array<Double>
typealias BoolArray = Array<Bool>
typealias StringArray = Array<String>

extension Array where Element == Int {
    init(_ size: Int) {
        self = [Element](repeating: 0, count: size)
    }
}
extension Array where Element == Double {
    init(_ size: Int) {
        self = [Element](repeating: 0.0, count: size)
    }
}
extension Array where Element == Bool {
    init(_ size: Int) {
        self = [Element](repeating: false, count: size)
    }
}
extension Array where Element == String {
    init(_ size: Int) {
        self = [Element](repeating: "", count: size)
    }
}

extension Array {
    @inlinable func count(_ predicate: ((Element) -> Bool)) -> Int {
        var cnt = 0; for e in self { if (predicate(e)) { cnt += 1 } }
        return cnt
    }
    @inlinable func groupBy<K>(_ keySelector: (Element) -> K) -> [K : [Element]] {
        var destination = [K : [Element]]()
        for element in self {
            let key = keySelector(element)
            var list = destination.getOrSet(key) { [Element]() }
            list.append(element)
            destination[key] = list
        }
        return destination
    }
    @inlinable func groupByIndexed<K>(_ keySelector: (Element) -> K) -> [K : [Int]] {
        var destination = [K : [Int]]()
        for element in self.enumerated() {
            let key = keySelector(element.element)
            var list = destination.getOrSet(key) { [Int]() }
            list.append(element.offset)
            destination[key] = list
        }
        return destination
    }
}

extension Array {
    func binarySearch(_ element: Element, by compare: (Element, Element) -> Int, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            let cmp = compare(midVal, element)
            if (cmp < 0) { low = mid + 1 }          //-1
            else if (0 < cmp) { high = mid - 1 }    // 1
            else { return mid } // key found        // 0
        }
        return -(low + 1)  // key not found
    }
}
extension Array where Element : Comparable {
    func binarySearch(_ element: Element, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            if (midVal < element) { low = mid + 1 }
            else if (midVal > element) { high = mid - 1 }
            else { return mid } // key found
        }
        return -(low + 1)  // key not found
    }
}

extension Array where Element == Int {
    @inlinable func distinct() -> [Element] {
        var set = Set<Element>(), ary = [Element]()
        for n in self.indices { if !set.contains(self[n]) { ary.append(self[n]); set.insert(self[n]) } }
        return ary
    }
    @inlinable func any(_ predicate: (Element) -> Bool) -> Bool {
        var any = false; for element in self { if predicate(element) { any = true } }
        return any
    }
    @inlinable func all(_ predicate: (Element) -> Bool) -> Bool {
        self.allSatisfy(predicate)
    }
    @inlinable func sum() -> Element { self.reduce(0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}

extension Array where Element == Double {
    @inlinable func sum() -> Element { self.reduce(0.0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0.0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}
extension Array where Element == String {
    @inlinable func toIntDouble() -> (Int, Double) { (Int(self[0])!, Double(self[1])!) }
    @inlinable func toIntString() -> (Int, String) { (Int(self[0])!, self[1]) }
    @inlinable func toIntIntString() -> (Int, Int, String) { (Int(self[0])!, Int(self[1])!, self[2]) }
}

@inlinable func block( _ action: () -> Void) {
    action()
}
@inlinable func repeate(_ times1: Int, _ action: () -> Void) {
    for _ in 0 ..< times1 { action() }
}
@inlinable func repeate(_ times1: Int, _ action: (Int) -> Void) {
    for index1 in 0 ..< times1 {
        action(index1)
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ action: (Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            action(index1, index2)
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ action: (Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                action(index1, index2, index3)
            }
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ times4: Int, _ action: (Int, Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                for index4 in 0 ..< times4 {
                    action(index1, index2, index3, index4)
                }
            }
        }
    }
}

func measureTimeSeconds(block: (() -> Void)) -> Double {
    let startTime = Date()
    block()
    let duration = -startTime.timeIntervalSinceNow
    return duration
}


func readInt() -> Int {
    return Int(readLine()!)!
}

func readTwoInts(separator: String.Element = " ") -> (a: Int, b: Int) {
    let ints = readLine()!.split(separator: separator).map { Int($0)! }
    return (a: ints[0], b: ints[1])
}

func readInts(separator: String.Element = " ") -> [Int] {
    return readLine()!.split(separator: separator).map { Int($0)! }
}

// 普通にやるとTLE
// どの要素がどれだけあるかを持っておいて、差分更新をする
func mainD() {
    let N = readInt()
    var numbers = readInts()
    let Q = readInt()
    let pairs = (0..<Q).map { _ in readTwoInts() }

    var counts: [Int] = .init(repeating: 0, count: 1_000_00 + 1)

    for number in numbers {
        counts[number] += 1
    }

    var sum = 0
    for pair in pairs {
        let changed = counts[pair.a]
        counts[pair.b] += counts[pair.a]
        counts[pair.a] = 0

        if sum == 0 {
            sum = counts.enumerated().reduce(0) { $0 + ($1.offset * $1.element) }
            print(sum)
        } else {
            sum += (pair.b - pair.a) * changed
            print(sum)
        }
    }

//    var sums: [Int] = .init(repeating: 0, count: Q)
//    var index = 0
//    for pair in pairs {
//        numbers = numbers.map { number in
//            let newNumber = number == pair.a ? pair.b : number
//            sums[index] += newNumber
//            return newNumber
//        }
//
//        index += 1
//    }
//
//    for sum in sums {
//        print(sum)
//    }
}
mainD()


import Foundation
let main: () = {
    let N = nextInt()
    let A = listOfInt()
    var S = IntArray(N + 1)
    let Q = nextInt()
    for a in A {
        S[a] += 1
    }
    var ans = 0
    for (n, s) in S.enumerated() {
        ans += n * s
    }
    repeate(Q) {
        let (b, c) = *listOfInt()
        S[c] += S[b]
        ans += S[b] * (c - b)
        S[b] = 0
        print(ans)
    }
}()

struct SimpleModInt {
    let MOD = 998244353
    var value: Int {
        didSet {
            value %= MOD
        }
    }
    init(_ initialValue: Int) {
        value = initialValue
        value %= MOD
    }
    init(_ initialValue: SimpleModInt) {
        value = initialValue.value
        value %= MOD
    }
}
infix operator <-: AssignmentPrecedence
extension SimpleModInt {
    static func + (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value + right) }
    static func + (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value + right.value) }
    static func - (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value - right) }
    static func - (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value - right.value) }
    static func * (left: SimpleModInt, right: Int) -> SimpleModInt { SimpleModInt(left.value * right) }
    static func * (left: SimpleModInt, right: SimpleModInt) -> SimpleModInt { SimpleModInt(left.value * right.value) }
    static func <- (left: inout SimpleModInt, right: Int) { left.value = right }
    static func <- (left: inout SimpleModInt, right: SimpleModInt) { left.value = right.value }
    static func += (left: inout SimpleModInt, right: Int) { left.value += right }
    static func += (left: inout SimpleModInt, right: SimpleModInt) { left.value += right.value }
    static func -= (left: inout SimpleModInt, right: Int) { left.value -= right }
    static func -= (left: inout SimpleModInt, right: SimpleModInt) { left.value -= right.value }
    static func *= (left: inout SimpleModInt, right: Int) { left.value *= right }
    static func *= (left: inout SimpleModInt, right: SimpleModInt) { left.value *= right.value }
    static func == (left: SimpleModInt, right: Int) -> Bool { left.value == SimpleModInt(right).value }
    static func == (left: SimpleModInt, right: SimpleModInt) -> Bool { left.value == right.value }
    static func != (left: SimpleModInt, right: Int) -> Bool { left.value != SimpleModInt(right).value }
    static func != (left: SimpleModInt, right: SimpleModInt) -> Bool { left.value != right.value }
}

//----------------------------------

let dx = [1, 0, -1, 0] //[1, 0, -1, 0, -1,  1, -1, 1]
let dy = [0, 1, 0, -1] //[0, 1, 0, -1, -1, -1,  1, 1]

@inlinable func gcd(_ a: Int, _ b: Int) -> Int { (b > 0) ? gcd(b, a % b) : a }
@inlinable func lcm(_ a: Int, _ b: Int) -> Int { a / gcd(a, b) * b }

//----------------------------------

infix operator  =~ : ComparisonPrecedence
infix operator !=~ : ComparisonPrecedence
func =~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { !(right ~= left) }
func =~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { !(right ~= left) }

func =~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { right.contains(left) }
func !=~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { !right.contains(left) }

infix operator /^ : MultiplicationPrecedence
infix operator /^= : AssignmentPrecedence
func /^ <T: FixedWidthInteger>(left: T, right: T) -> T { (left + (right - 1)) / right }
func /^= <T: FixedWidthInteger>(left: inout T, right: T) { left = (left + (right - 1)) / right }

@inlinable func chmax<T: Comparable>(_ m: inout T, _ q: T) { if (m < q) { m = q } }
@inlinable func chmin<T: Comparable>(_ m: inout T, _ q: T) { if (m > q) { m = q } }
@inlinable func chRmax<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m < q) { m = q; return true } else { return false } }
@inlinable func chRmin<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m > q) { m = q; return true } else { return false } }

prefix operator *
prefix func * <T> (a: [T]) -> (T, T) { (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T) { (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4], a[5]) }

func printErr(_ str: String, terminator: String = "\n") {
    let s = str + terminator
    FileHandle.standardError.write(s.data(using: .utf8)!)
    FileHandle.standardError.synchronizeFile()
}

@inlinable func next() -> String { readLine()! }
@inlinable func nextInt() -> Int { Int(next())! }
@inlinable func nextDouble() -> Double { Double(next())! }
@inlinable func listOfString() -> [String] { next().split(separator: " ").map(String.init) }
@inlinable func listOfInt() -> [Int] { listOfString().map { Int($0)! } }
@inlinable func listOfInt(_ offset: Int = 0) -> [Int] { listOfString().map { Int($0)! + offset } }
@inlinable func listOfInt(_ offsets: Int ...) -> [Int] { listOfString().enumerated().map { Int($0.element)! + offsets[$0.offset % offsets.count] } }
@inlinable func listOfDouble(_ offset: Double = 0.0) -> [Double] { listOfString().map { Double($0)! + offset } }
@inlinable func listOfDouble(_ offsets: Double ...) -> [Double] { listOfString().enumerated().map { Double($0.element)! + offsets[$0.offset % offsets.count] } }

extension Int {
    init(s: String) { self.init(s)! }
    var isEven: Bool { self.isMultiple(of: 2) }
    var isOdd: Bool { !self.isEven }
    var isTrue: Bool { self != 0 }
    var isFalse: Bool { !self.isTrue }
    var toString: String { String(self) }
    var toChar: Character { Character(UnicodeScalar(UInt8(self))) }
}
func + (left: Int, right: Bool) -> Int { left + (right ? 1 : 0) }
extension Character {
    var asciiCode: Int { Int(self.asciiValue!) }
    var string: String { String(self) }
}
extension String {
    @inlinable subscript (position: Int) -> Character { self[self.index(self.startIndex, offsetBy: position)] }
    @inlinable func repeate(_ times: Int) -> String { String(repeating: self, count: times) }
    //  @inlinable subscript (n: Int) -> String { String(self[self.index(self.startIndex, offsetBy: n)]) }
    //  @inlinable subscript (n: Int) -> Int { Int(self[self.index(self.startIndex, offsetBy: n)].asciiValue!) }
    var toInt: Int { Int(self)! }
}
extension String { // VB like
    @inlinable func _index(_ position: Int) -> String.Index! {
        if !(0 ..< self.count ~= position) { return nil }
        return self.index(self.startIndex, offsetBy: position)
    }
    @inlinable func mid(from index: Int, length: Int) -> String! {
        if let startPosition = self._index(index) {
            if let endPosition = self._index(index + length - 1) {
                return String(self[startPosition...endPosition])
            } else {
                let endPosition = self.index(before: self.endIndex)
                return String(self[startPosition...endPosition])
            }
        }
        return ""
    }
    @inlinable func left(_ length: Int) -> String { String(self.prefix(length)) }
    @inlinable func right(_ length: Int) -> String { String(self.suffix(length)) }
}

extension Dictionary {
    @inlinable mutating func getOrSet(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored }
        else {
            let newValue = defaultValue()
            self[key] = newValue
            return newValue
        }
    }
    @inlinable mutating func getOrElse(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored } else { return defaultValue() }
    }
    @inlinable func containsKey(_ key: Key) -> Bool { self.keys.contains(key) }
}

extension Set {
    static func += (left: inout Set<Element>, right: Element) { left.insert(right) }
    static func -= (left: inout Set<Element>, right: Element) { left.remove(right) }
}

extension Array {
    static func += (left: inout Array<Element>, right: Element) { left.append(right) }
    init(_ size: Int, _ initValue: ((Int) -> Element)) {
        self = [Element]()
        for index in 0 ..< size {
            let value = initValue(index)
            self.append(value)
        }
    }
    init(_ size: Int, _ initValue: (() -> Element)) {
        self = [Element]()
        for _ in 0 ..< size {
            let value = initValue()
            self.append(value)
        }
    }
}
typealias IntArray = Array<Int>
typealias DoubleArray = Array<Double>
typealias BoolArray = Array<Bool>
typealias StringArray = Array<String>

extension Array where Element == Int {
    init(_ size: Int) {
        self = [Element](repeating: 0, count: size)
    }
}
extension Array where Element == Double {
    init(_ size: Int) {
        self = [Element](repeating: 0.0, count: size)
    }
}
extension Array where Element == Bool {
    init(_ size: Int) {
        self = [Element](repeating: false, count: size)
    }
}
extension Array where Element == String {
    init(_ size: Int) {
        self = [Element](repeating: "", count: size)
    }
}

extension Array {
    @inlinable func count(_ predicate: ((Element) -> Bool)) -> Int {
        var cnt = 0; for e in self { if (predicate(e)) { cnt += 1 } }
        return cnt
    }
    @inlinable func groupBy<K>(_ keySelector: (Element) -> K) -> [K : [Element]] {
        var destination = [K : [Element]]()
        for element in self {
            let key = keySelector(element)
            var list = destination.getOrSet(key) { [Element]() }
            list.append(element)
            destination[key] = list
        }
        return destination
    }
    @inlinable func groupByIndexed<K>(_ keySelector: (Element) -> K) -> [K : [Int]] {
        var destination = [K : [Int]]()
        for element in self.enumerated() {
            let key = keySelector(element.element)
            var list = destination.getOrSet(key) { [Int]() }
            list.append(element.offset)
            destination[key] = list
        }
        return destination
    }
}

extension Array {
    func binarySearch(_ element: Element, by compare: (Element, Element) -> Int, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            let cmp = compare(midVal, element)
            if (cmp < 0) { low = mid + 1 }          //-1
            else if (0 < cmp) { high = mid - 1 }    // 1
            else { return mid } // key found        // 0
        }
        return -(low + 1)  // key not found
    }
}
extension Array where Element : Comparable {
    func binarySearch(_ element: Element, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            if (midVal < element) { low = mid + 1 }
            else if (midVal > element) { high = mid - 1 }
            else { return mid } // key found
        }
        return -(low + 1)  // key not found
    }
}

extension Array where Element == Int {
    @inlinable func distinct() -> [Element] {
        var set = Set<Element>(), ary = [Element]()
        for n in self.indices { if !set.contains(self[n]) { ary.append(self[n]); set.insert(self[n]) } }
        return ary
    }
    @inlinable func any(_ predicate: (Element) -> Bool) -> Bool {
        var any = false; for element in self { if predicate(element) { any = true } }
        return any
    }
    @inlinable func all(_ predicate: (Element) -> Bool) -> Bool {
        self.allSatisfy(predicate)
    }
    @inlinable func sum() -> Element { self.reduce(0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}

extension Array where Element == Double {
    @inlinable func sum() -> Element { self.reduce(0.0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0.0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}
extension Array where Element == String {
    @inlinable func toIntDouble() -> (Int, Double) { (Int(self[0])!, Double(self[1])!) }
    @inlinable func toIntString() -> (Int, String) { (Int(self[0])!, self[1]) }
    @inlinable func toIntIntString() -> (Int, Int, String) { (Int(self[0])!, Int(self[1])!, self[2]) }
}

@inlinable func block( _ action: () -> Void) {
    action()
}
@inlinable func repeate(_ times1: Int, _ action: () -> Void) {
    for _ in 0 ..< times1 { action() }
}
@inlinable func repeate(_ times1: Int, _ action: (Int) -> Void) {
    for index1 in 0 ..< times1 {
        action(index1)
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ action: (Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            action(index1, index2)
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ action: (Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                action(index1, index2, index3)
            }
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ times4: Int, _ action: (Int, Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                for index4 in 0 ..< times4 {
                    action(index1, index2, index3, index4)
                }
            }
        }
    }
}

func measureTimeSeconds(block: (() -> Void)) -> Double {
    let startTime = Date()
    block()
    let duration = -startTime.timeIntervalSinceNow
    return duration
}


_ = Int(readLine()!)!
let AN = readLine()!.split(separator: " ").compactMap { Int($0) }
let Q = Int(readLine()!)!
let BCQ: [(Int, Int)] = (1...Q).map { _ in
    let bc = readLine()!.split(separator: " ").compactMap { Int($0) }
    return (bc[0], bc[1])
}

var dict = [Int: Int]()
for an in AN {
    if dict[an] == nil {
        dict[an] = 1
    } else {
        dict[an]! += 1
    }
}

var sum = dict.reduce(0) { $0 + ($1.key * $1.value) }
for bc in BCQ {
    if dict[bc.0] != nil {
        let diff = (bc.1 - bc.0) * dict[bc.0]!
        sum += diff

        if dict[bc.1] != nil {
            dict[bc.1]! += dict[bc.0]!
        } else {
            dict[bc.1] = dict[bc.0]
        }
    }
    print(sum)
}


import Foundation

var n = Int(readLine()!)!
var a = readLine()!.split(separator: " ").map{ Int($0)! }
var q = Int(readLine()!)!
var bc = (0..<q).map{ _ in readLine()!.split(separator: " ").map{ Int($0)! } }

for i in 0..<q {
    a = a.map{ $0 == bc[i][0] ? bc[i][1] : $0 }
    print(a.reduce(0, +))
}


{
  const run = (input: string) => {
    let split = input.trim().split("\n")
    const n = parseInt(split[0])
    const tmpList = split[1].split(" ").map(v => parseInt(v))

    let tmpSum = 0
    const list = {}
    for (let i = 0; i < n; i++) {
      const v = tmpList[i]
      list[v] = list[v] ? list[v] + 1 : 1
      tmpSum += v
    }

    const q = parseInt(split[2])

    const result = []
    const max = 3 + q
    for (let i = 3; i < max; i++) {
      const [from, to] = split[i].split(" ").map(v => parseInt(v))
      if (list[from]) {
        tmpSum = tmpSum - (from * list[from]) + (to * list[from])
        list[to] = list[from] + (list[to] || 0)
        list[from] = 0
      }

      result.push(tmpSum)
    }

    return result.join("\n")
  }

  const Main = (input: string) => {
    console.log(run(input))
  };

  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}


// import std = require('tstl')

{
  type Print = void | string | number | string[] | number[]
  let outs: Print[] = []

  const main = (): Print => {
    const r = _io()
    const [N] = r.nn()
    const A = r.nn()
    const [Q] = r.nn()
    const bc = r.nnls()

    const counts = {}
    let sum = 0

    const res: string[] = []

    A.forEach((a) => {
      if (!counts[a]) counts[a] = 0
      sum += a
      counts[a]++
    })

    //

    bc.forEach(([b, c]) => {
      if (!counts[b]) {
        res.push(String(sum))
        return
      }
      const d = c - b

      sum += counts[b] * d

      res.push(String(sum))

      if (!counts[c]) counts[c] = 0
      counts[c] += counts[b]
      counts[b] = 0
    })

    return res.join('\n')
  }

  const _io = (i = 0) => {
    const str = require('fs').readFileSync('/dev/stdin', 'utf8')
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')

    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map((v) => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  outs.push(main())

  console.log(
    outs
      .map((line) => (typeof line === 'object' ? line.join(' ') : String(line)))
      .join('\n')
  )
}


import * as fs from 'fs';

// main
function main(input: string[]) {
    // param
    var n: number;
    var an: number[] = [];
    var q: number;
    var bq: number[] = [];
    var cq: number[] = [];
    var ans: number;
    // init
    n = Number(input.shift());
    an = input.shift().split(" ").map(x => Number(x));
    q = Number(input.shift());
    for (var qx = 0; qx < q; qx++) {
        [bq[qx], cq[qx]] = input[qx].split(" ").map(x => Number(x));
    }
    // solve
    ans = an.reduce((x, y) => x + y);
    var an1 = new Array(100001).fill(0);
    for (var nx = 0; nx < n; nx++) {
        an1[an[nx]]++;
    }
    for (var qx = 0; qx < q; qx++) {
        ans -= bq[qx] * an1[bq[qx]];
        ans += cq[qx] * an1[bq[qx]];
        an1[cq[qx]] += an1[bq[qx]];
        an1[bq[qx]] = 0;
        // answer
        console.log(ans);
    }
}

// graph lib
/*
function GRAPH_enumPattern(cur: number[], pat: number[][]): number[][] {
    var arr = [];
    for (var patx = 0; patx < pat.length; patx++) {
        var pos = [cur[0] + pat[patx][0], cur[1] + pat[patx][1]];
        arr.push(pos);
    }
    return arr;
}
*/

// math lib
/*
function Math_max(arr: number[]): number { return arr.reduce((x, y) => Math.max(x, y)); }
function Math_min(arr: number[]): number { return arr.reduce((x, y) => Math.min(x, y)); }
function Math_gcd(): number {
    var ans = arguments[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < arguments.length; i++) {
        ans = f(ans, arguments[i]);
    }
    return ans
};
function Math_gcdArray(values: number[]): number {
    var ans = values[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < values.length; i++) {
        ans = f(ans, values[i]);
    }
    return ans
};
function Math_lcm(): number {
    var a = arguments
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_lcmArray(values: number[]): number {
    var a = values
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_primeList(value: number): number[] {
    var ans = [];
    var arr = new Array(value).fill(0);
    for (var i = 2; i < value; i++) {
        if (arr[i] == 0) {
            for (var j = i; j < value; j += i) {
                if (arr[j] == 0) arr[j] = i;
            }
        }
    }
    for (var i = 2; i < value; i++) {
        if (arr[i] == i) ans.push(i);
    }
    return ans;
}
function Math_primeFactor(p: number[], value: number): number[][] {
    var ans: number[][] = [];
    var valmax = value / 2;;
    for (var i = 0; i < p.length; i++) {
        var prime = p[i];
        if (valmax < prime) break;
        var count = 0;
        while (value % prime == 0) {
            value /= prime;
            count++;
        }
        if (count != 0) {
            ans.push([prime, count]);
        }
        if (value == 1) break;
    }
    return ans;
}
*/

// union-find lib
/*
var g_uf_root: number[];
var g_uf_count: number[];
function UF_initRoot(num: number) {
    g_uf_root = new Array(num).fill(-1);
    g_uf_count = new Array(num).fill(1);
}
function UF_getRoot(index: number) {
    if (g_uf_root[index] < 0) {
        return index;
    } else {
        var work0: number = UF_getRoot(g_uf_root[index]);
        g_uf_root[index] = work0;
        return work0
    }
}
function UF_mergeRoot(a: number, b: number) {
    var root0: number = UF_getRoot(a);
    var root1: number = UF_getRoot(b);
    if (root0 == root1) return;
    if (root0 > root1) [root0, root1] = [root1, root0];
    g_uf_count[root0] += g_uf_count[root1];
    g_uf_count[root1] = 0;
    g_uf_root[root1] = root0;
}
*/

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();


import * as fs from 'fs';

// main
function main(input: string[]) {
    // param
    var n: number;
    var ans: number;
    // init
    n = Number(input[0]);
    ans = 0;
    // solve
    var narr = new Array(n + 1).fill(0);
    for (var nx = 1; nx <= n; nx++) {
        for (var nxx = nx; nxx <= n; nxx += nx) {
            narr[nxx] ++;
        }
    }
    for (var nx = 1; nx <= n; nx ++) {
        ans += nx * narr[nx];
    }
    // answer
    console.log(ans);
}

// graph lib
/*
function GRAPH_enumPattern(cur: number[], pat: number[][]): number[][] {
    var arr = [];
    for (var patx = 0; patx < pat.length; patx++) {
        var pos = [cur[0] + pat[patx][0], cur[1] + pat[patx][1]];
        arr.push(pos);
    }
    return arr;
}
*/

// math lib
/*
function Math_max(arr: number[]): number { return arr.reduce((x, y) => Math.max(x, y)); }
function Math_min(arr: number[]): number { return arr.reduce((x, y) => Math.min(x, y)); }
function Math_gcd(): number {
    var ans = arguments[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < arguments.length; i++) {
        ans = f(ans, arguments[i]);
    }
    return ans
};
function Math_gcdArray(values: number[]): number {
    var ans = values[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < values.length; i++) {
        ans = f(ans, values[i]);
    }
    return ans
};
function Math_lcm(): number {
    var a = arguments
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_lcmArray(values: number[]): number {
    var a = values
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_primeList(value: number): number[] {
    var ans = [];
    var arr = new Array(value).fill(0);
    for (var i = 2; i < value; i++) {
        if (arr[i] == 0) {
            for (var j = i; j < value; j += i) {
                if (arr[j] == 0) arr[j] = i;
            }
        }
    }
    for (var i = 2; i < value; i++) {
        if (arr[i] == i) ans.push(i);
    }
    return ans;
}
function Math_primeFactor(p: number[], value: number): number[][] {
    var ans: number[][] = [];
    var valmax = value / 2;
    for (var i = 0; i < p.length; i++) {
        var prime = p[i];
        if (valmax < prime) break;
        var count = 0;
        while (value % prime == 0) {
            value /= prime;
            count++;
        }
        if (count != 0) {
            ans.push([prime, count]);
        }
        if (value == 1) break;
    }
    if (ans.length == 0 && value != 1) ans.push([value, 1]);
    return ans;
}
*/

// union-find lib
/*
var g_uf_root: number[];
var g_uf_count: number[];
function UF_initRoot(num: number) {
    g_uf_root = new Array(num).fill(-1);
    g_uf_count = new Array(num).fill(1);
}
function UF_getRoot(index: number) {
    if (g_uf_root[index] < 0) {
        return index;
    } else {
        var work0: number = UF_getRoot(g_uf_root[index]);
        g_uf_root[index] = work0;
        return work0
    }
}
function UF_mergeRoot(a: number, b: number) {
    var root0: number = UF_getRoot(a);
    var root1: number = UF_getRoot(b);
    if (root0 == root1) return;
    if (root0 > root1) [root0, root1] = [root1, root0];
    g_uf_count[root0] += g_uf_count[root1];
    g_uf_count[root1] = 0;
    g_uf_root[root1] = root0;
}
*/

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();