using System;
using static System.Console;
using static System.Math;
using System.Numerics;
using System.Collections.Generic;


namespace AtCoder
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var s = ReadLine().Split(' ');
            long ans = 0;
            int n = int.Parse(s[0]);
            var list = new List<int>();
            Vector2[] tyouhuku = new Vector2[n];
            int c, b;

            bool b = true;
            int num = 0;
            for (int i = 0; i < n; i++)
            {
                b = int.Parse(s[i]);
                if (list.Contains(b))
                {
                    b = true;
                    for (int i = 0; i < n; i++)
                    {
                        if (tyouhuku[i].x == b)
                        {
                            tyouhuku.y++;
                            b = false;
                            break;
                        }
                    }
                    if (b == true)
                    {
                        tyouhuku[num] = new Vector2(b, 1);
                        num++;
                    }
                }
                else
                {
                    list.Add(b);
                }
            }

            for (int i = 0; i < n; i++)
            {
                var s2 = ReadLine().Split(' '); ;
                b = int.Parses(s2[i]);
                if (list.Contains(b))
                {
                    c = int.Parse(s[1]);
                    int index = list.IndexOf(b);
                    list.RemoveAt(index);
                    list.Add(c);
                    for (int i = 0; i < num; i++)
                    {
                        if (tyouhuku[i].x == b)
                        { tyouhuku[i].x = c; }
                    }
                }
            }

            for (int i = 0; i < list.Count(); i++)
            {
                ans += list[i];
            }
            for (int i = 0; i < tyouhuku.Length; i++)
            {
                ans += tyouhuku.x * tyouhuku.y;
            }



            WriteLine(ans);
            Out.Flush();
        }

    }

    public static class MyMath
    {
        public static long Factorical(long n)
        { return n <= 1 ? 1L : n * Factorical(n - 1); }
        public static long Permutation(long n, long m)
        { return m == 0 ? 1L : (m == n) ? Permutation(n, m - 1) : n * Permutation(n - 1, m - 1); }
        public static long Combination(long n, long m)
        { return n - m > m ? Permutation(n, m) / Factorical(m) : Permutation(n, n - m) / Factorical(n - m); }
        public static long Gcd(long n, long m)
        { return n % m == 0 ? m : Gcd(m, n % m); }
        public static long Lcm(long n, long m)
        { return n * m / Gcd(n, m); }
        public static long Pow(long n, long m)
        { return (m == 1 || m == 0) ? 1L : n * Pow(n, m - 1); }
    }
}