#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define int long long
int lst[3][11];
int nlst[10];

bool check(void) {
    int num[3] = {0};
    for (int i = 0; i < 3; i++) {
        if (nlst[lst[i][0]] == 0) return false;
        for (int j = 0; j < lst[i][10]; j++) {
            num[i] *= 10;
            num[i] += nlst[lst[i][j]];
        }
    }
    return (num[0] + num[1] == num[2]);
}

signed main(void) {
    string s;
    bool b;
    char clst[10];
    int cp = 0;
    for (int i = 0; i < 3; i++) {
        cin >> s;
        for (int j = s.size() - 1; j >= 0; j--) {
            lst[i][10] = s.size();
            b = true;
            // アルファベットを数字に変換
            for (int k = 0; k < cp; k++) {
                if (clst[k] == s[j]) {
                    lst[i][j] = k;
                    b = false;
                    break;
                }
            }
            if (b) {
                if (cp >= 10) {
                    // 11文字以上使われてる
                    cout << "UNSOLVABLE" << endl;
                    return 0;
                }
                clst[cp] = s[j];
                lst[i][j] = cp;
                cp++;
            }
        }
    }

    vector<int> seed = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    sort(seed.begin(), seed.end());
    do {
        for (int i = 0; i < 10; i++) nlst[i] = seed[i];
        b = check();
        if (b) break;
    } while (next_permutation(seed.begin(), seed.end()));

    if (b) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < lst[i][10]; j++) cout << nlst[lst[i][j]];
            cout << endl;
        }
    } else
        cout << "UNSOLVABLE" << endl;
}
#include <bits/stdc++.h>
#define rep3(i, s, n, a) for (long long i = (s); i < (long long)(n); i += a)
#define rep2(i, s, n) rep3(i, s, n, 1)
#define rep(i, n) rep2(i, 0, n)

using namespace std;
using ll = long long;
using ull = unsigned long long;
using P = pair<int, int>;
using Pll = pair<ll, ll>;

int main() { 
    ll n;
    cin >> n;
    vector<vector<ll>> ball(n+1, vector<ll>()), dp(n+1, vector<ll>(2, 0LL));
    rep(i, n){
        ll x, c;
        cin >> x >> c;
        ball[c].push_back(x);
    }
    ll nowl = 0LL, nowr = 0LL;
    rep(i, n){
        ll balllen = ball[i+1].size();
        if(balllen){
            sort(ball[i+1].begin(), ball[i+1].end());
            ll nextl = ball[i+1][0], nextr = ball[i+1][balllen-1];
            ll dis = nextr - nextl;
            dp[i+1][0] = min(dp[i][0] + abs(nowl - nextr), dp[i][1] + abs(nowr - nextr)) + dis;
            dp[i+1][1] = min(dp[i][0] + abs(nowl - nextl), dp[i][1] + abs(nowr - nextl)) + dis;
            nowl = nextl;
            nowr = nextr;
        }else{
            rep(j, 2){
                dp[i+1][j] = dp[i][j];
            }
        }
    }
    cout << min(dp[n][0] + abs(nowl), dp[n][1] + abs(nowr)) << endl;
    return 0; 
}