Problem:
Problem C: Phone Number
Problem
株式会社ウクニキアの電話番、デンさんは毎日とても長い電話番号を電話に入力しています。
ある日余りにも疲れたデンさんは、疲れからか驚くべき考えに至りました。
「電話のボタンの配置を並べ替えたら少しでも楽できるのでは？！」
電話には$3 \times 3$で等間隔に区切られた正方形があり、9個のマスには並べ替えることのできる1から9までのボタンがそれぞれ1つずつついています。
電話番号を打つ際、デンさんは片手だけを使って、次の二つの操作を行うことができます。
人差し指を今触れているボタンに辺で隣接するいずれかのボタンに触れるように移動させる。
人差し指が触れているボタンを押す。
最初、人差し指は1から9までのいずれかのボタンに触れるように置くことができます。
デンさんは、最初のボタンを押してから最後のボタンを押し終わるまでの、人差し指の移動回数を最も小さくできる配置を効率的と考えています。
さて、ここに長さ$N$のお得意先の電話番号があります。
お得意先の電話番号だけ考えた時に、どのような配置が一番効率的でしょうか？
ボタンを並び替えることで、その配置を作ってください。
Input
入力は以下の形式で与えられる。
$N$
$S$
1行目にお得意先の電話番号の長さ$N$が与えられる。
2行目にお得意先の電話番号が1行に与えられる。
Constraints
入力は以下の条件を満たす。
$1 \leq N \leq 10^5 $
$S$は1から9までのいずれかの数字からなる文字列
Output
最も効率的な配置を、3行に空白を入れずに出力せよ。
但し、解答となり得る配置が複数ある場合は、左上の枠から
123
456
789
の順序で数字を並べた際に辞書順で最小となるようなものを出力せよ。
Sample Input 1
10
1236547896
Sample Output 1
123
456
789
Sample Input 2
11
31415926535
Sample Output 2
137
456
892

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pll = pair<ll, ll>;
using vl = vector<ll>;
template <class T> using vec = vector<T>;
template <class T> using vv = vec<vec<T>>;
template <class T> using vvv = vv<vec<T>>;
template <class T> using minpq = priority_queue<T, vector<T>, greater<T>>;
#define all(a) (a).begin(),(a).end()
#define rep(i, n) for (ll i = 0; i < (n); ++i)
#define reps(i, l, r) for(ll i = (l); i < (r); ++i)
#define rrep(i, l, r) for(ll i = (r)-1; i >= (l); --i)
#define sz(x) (ll) (x).size()
template <typename T>
bool chmax(T &a, const T& b) { return a < b ? a = b, true : false; }
template <typename T>
bool chmin(T &a, const T& b) { return a > b ? a = b, true : false; }

#define EPS (1e-10)
#define equals(a, b) (fabs((a) - (b)) < EPS)
class Point {
public:
    ld x;
    ld y;
    Point(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}
    Point operator+(Point p) { return Point(x + p.x, y + p.y); }
    Point operator-(Point p) { return Point(x - p.x, y - p.y); }
    Point operator*(ld a) { return Point(a * x, a * y); }
    Point operator/(ld a) { return Point(x / a, y / a); }

    ld abs() { return sqrt(norm()); }
ld norm() { return x * x + y * y; }

    bool operator<(const Point& p) const {
        return !equals(x, p.x) ? x < p.x : y < p.y;
    }
    bool operator==(const Point& p) const {
        return fabs(x - p.x) < (1e-10) && fabs(y - p.y) < (1e-10);
    }
};
typedef Point Vector;
struct Segment {
    Point A;
    Point B;
};
typedef Segment Line;
class Circle {
public:
    Point C;
    ld r;
    Circle(Point C = Point(), ld r = 0.0) : C(C), r(r) {}
};
typedef vector<Point> Polygon;

struct Edge {
    ll from, to, cost;
    Edge (ll from, ll to, ll cost = 1ll) : from(from), to(to), cost(cost) {}
};
struct Graph {
    vector<vector<Edge>> G;
    Graph() = default;
    explicit Graph(ll N) : G(N) {}
    size_t size() const {
        return G.size();
    }
    void add(ll from, ll to, ll cost = 1ll, bool direct = 0) {
        G[from].emplace_back(from, to, cost);
        if (!direct) G[to].emplace_back(to, from, cost);
    }
    vector<Edge> &operator[](const int &k) {
        return G[k];
    }
};
using Edges = vector<Edge>;

void solve(){
    ll N; cin >> N;
    string S; cin >> S;
    vv<ll> cnt(9, vl(9, 0));
    rep(i, N-1){
        ll u = S[i] - '1', v = S[i+1] - '1';
        if(u == v) continue;
        if(u > v) swap(u, v);
        cnt[u][v]++;
    }
    vl vec(9); iota(all(vec), 0);
    ll ans = 4e18;
    vl V;
    do{
        vl idx(9);
        rep(i, 9){
            idx[vec[i]] = i;
        }
        vv<ll> dist(9, vl(9));
        ll tmp = 0;
        rep(i, 9){
            rep(k, i){
                dist[k][i] = abs(idx[i] / 3 - idx[k]/3) + abs(idx[i] % 3 - idx[k] % 3);
                tmp += dist[k][i] * cnt[k][i];
            }
        }
        if(chmin(ans, tmp)) V = vec;
    }while(next_permutation(all(vec)));
    rep(i, 9){
        V[i]++;
    }
    rep(i, 3){
        cout << V[i*3] << V[i*3+1] << V[i*3+2] << endl;
    }
}

int main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    int t = 1;
    // cin >> t;
    while(t--){
        solve();
    }
}
accuracy: 1
time_ms: 90
memory_kb: 3592
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pll = pair<ll, ll>;
using vl = vector<ll>;
template <class T> using vec = vector<T>;
template <class T> using vv = vec<vec<T>>;
template <class T> using vvv = vv<vec<T>>;
template <class T> using minpq = priority_queue<T, vector<T>, greater<T>>;
#define all(a) (a).begin(),(a).end()
#define rep(i, n) for (ll i = 0; i < (n); ++i)
#define reps(i, l, r) for(ll i = (l); i < (r); ++i)
#define rrep(i, l, r) for(ll i = (r)-1; i >= (l); --i)
#define sz(x) (ll) (x).size()
template <typename T>
bool chmax(T &a, const T& b) { return a < b ? a = b, true : false; }
template <typename T>
bool chmin(T &a, const T& b) { return a > b ? a = b, true : false; }

#define EPS (1e-10)
#define equals(a, b) (fabs((a) - (b)) < EPS)
class Point {
public:
    ld x;
    ld y;
    Point(ld _x = 0, ld _y = 0) : x(_x), y(_y) {}
    Point operator+(Point p) { return Point(x + p.x, y + p.y); }
    Point operator-(Point p) { return Point(x - p.x, y - p.y); }
    Point operator*(ld a) { return Point(a * x, a * y); }
    Point operator/(ld a) { return Point(x / a, y / a); }

    ld abs() { return sqrt(norm()); }
ld norm() { return x * x + y * y; }

    bool operator<(const Point& p) const {
        return !equals(x, p.x) ? x < p.x : y < p.y;
    }
    bool operator==(const Point& p) const {
        return fabs(x - p.x) < (1e-10) && fabs(y - p.y) < (1e-10);
    }
};
typedef Point Vector;
struct Segment {
    Point A;
    Point B;
};
typedef Segment Line;
class Circle {
public:
    Point C;
    ld r;
    Circle(Point C = Point(), ld r = 0.0) : C(C), r(r) {}
};
typedef vector<Point> Polygon;

struct Edge {
    ll from, to, cost;
    Edge (ll from, ll to, ll cost = 1ll) : from(from), to(to), cost(cost) {}
};
struct Graph {
    vector<vector<Edge>> G;
    Graph() = default;
    explicit Graph(ll N) : G(N) {}
    size_t size() const {
        return G.size();
    }
    void add(ll from, ll to, ll cost = 1ll, bool direct = 0) {
        G[from].emplace_back(from, to, cost);
        if (!direct) G[to].emplace_back(to, from, cost);
    }
    vector<Edge> &operator[](const int &k) {
        return G[k];
    }
};
using Edges = vector<Edge>;

void solve(){
    ll N; cin >> N;
    string S; cin >> S;
    vv<ll> cnt(9, vl(9, 0));
    rep(i, N-1){
        ll u = S[i] - '1', v = S[i+1] - '1';
        cnt[min(u, v)][max(u, v)]++;
    }
    vl vec(9); iota(all(vec), 0);
    ll ans = 4e18;
    vl perm;
    do{
        ll tmp = 0;
        rep(i, 9){
            rep(k, i){
                tmp += cnt[k][i] * (abs(vec[i] / 3 - vec[k] / 3) + abs(vec[i] % 3 - vec[k] % 3));
            }
        }
        if(chmin(ans, tmp)) perm = vec;
    }while(next_permutation(all(vec)));
    vl V(9);
    rep(i, 9){
        V[perm[i]] = i+1;
    }
    cout << V[0] << V[1] << V[2] << endl;
    cout << V[3] << V[4] << V[5] << endl;
    cout << V[6] << V[7] << V[8] << endl;
}

int main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    int t = 1;
    // cin >> t;
    while(t--){
        solve();
    }
}
accuracy: 0.08333333333333333
time_ms: 20
memory_kb: 3440
final_rank: 20

code_snippet: #line 2 "/Users/noya2/Desktop/Noya2_library/template/template.hpp"
using namespace std;

#include<bits/stdc++.h>
#line 1 "/Users/noya2/Desktop/Noya2_library/template/inout_old.hpp"
namespace noya2 {

template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &p){
    os << p.first << " " << p.second;
    return os;
}
template <typename T, typename U>
istream &operator>>(istream &is, pair<T, U> &p){
    is >> p.first >> p.second;
    return is;
}

template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v){
    int s = (int)v.size();
    for (int i = 0; i < s; i++) os << (i ? " " : "") << v[i];
    return os;
}
template <typename T>
istream &operator>>(istream &is, vector<T> &v){
    for (auto &x : v) is >> x;
    return is;
}

void in() {}
template <typename T, class... U>
void in(T &t, U &...u){
    cin >> t;
    in(u...);
}

void out() { cout << "\n"; }
template <typename T, class... U, char sep = ' '>
void out(const T &t, const U &...u){
    cout << t;
    if (sizeof...(u)) cout << sep;
    out(u...);
}

template<typename T>
void out(const vector<vector<T>> &vv){
    int s = (int)vv.size();
    for (int i = 0; i < s; i++) out(vv[i]);
}

struct IoSetup {
    IoSetup(){
        cin.tie(nullptr);
        ios::sync_with_stdio(false);
        cout << fixed << setprecision(15);
        cerr << fixed << setprecision(7);
    }
} iosetup_noya2;

} // namespace noya2
#line 1 "/Users/noya2/Desktop/Noya2_library/template/const.hpp"
namespace noya2{

const int iinf = 1'000'000'007;
const long long linf = 2'000'000'000'000'000'000LL;
const long long mod998 =  998244353;
const long long mod107 = 1000000007;
const long double pi = 3.14159265358979323;
const vector<int> dx = {0,1,0,-1,1,1,-1,-1};
const vector<int> dy = {1,0,-1,0,1,-1,-1,1};
const string ALP = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string alp = "abcdefghijklmnopqrstuvwxyz";
const string NUM = "0123456789";

void yes(){ cout << "Yes\n"; }
void no(){ cout << "No\n"; }
void YES(){ cout << "YES\n"; }
void NO(){ cout << "NO\n"; }
void yn(bool t){ t ? yes() : no(); }
void YN(bool t){ t ? YES() : NO(); }

} // namespace noya2
#line 2 "/Users/noya2/Desktop/Noya2_library/template/utils.hpp"

#line 6 "/Users/noya2/Desktop/Noya2_library/template/utils.hpp"

namespace noya2{

unsigned long long inner_binary_gcd(unsigned long long a, unsigned long long b){
    if (a == 0 || b == 0) return a + b;
    int n = __builtin_ctzll(a); a >>= n;
    int m = __builtin_ctzll(b); b >>= m;
    while (a != b) {
        int mm = __builtin_ctzll(a - b);
        bool f = a > b;
        unsigned long long c = f ? a : b;
        b = f ? b : a;
        a = (c - b) >> mm;
    }
    return a << std::min(n, m);
}

template<typename T> T gcd_fast(T a, T b){ return static_cast<T>(inner_binary_gcd(std::abs(a),std::abs(b))); }

long long sqrt_fast(long long n) {
    if (n <= 0) return 0;
    long long x = sqrt(n);
    while ((x + 1) * (x + 1) <= n) x++;
    while (x * x > n) x--;
    return x;
}

template<typename T> T floor_div(const T n, const T d) {
    assert(d != 0);
    return n / d - static_cast<T>((n ^ d) < 0 && n % d != 0);
}

template<typename T> T ceil_div(const T n, const T d) {
    assert(d != 0);
    return n / d + static_cast<T>((n ^ d) >= 0 && n % d != 0);
}

template<typename T> void uniq(std::vector<T> &v){
    std::sort(v.begin(),v.end());
    v.erase(unique(v.begin(),v.end()),v.end());
}

template <typename T, typename U> inline bool chmin(T &x, U y) { return (y < x) ? (x = y, true) : false; }

template <typename T, typename U> inline bool chmax(T &x, U y) { return (x < y) ? (x = y, true) : false; }

template<typename T> inline bool range(T l, T x, T r){ return l <= x && x < r; }

} // namespace noya2
#line 8 "/Users/noya2/Desktop/Noya2_library/template/template.hpp"

#define rep(i,n) for (int i = 0; i < (int)(n); i++)
#define repp(i,m,n) for (int i = (m); i < (int)(n); i++)
#define reb(i,n) for (int i = (int)(n-1); i >= 0; i--)
#define all(v) (v).begin(),(v).end()

using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull = unsigned long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using pil = pair<int,ll>;
using pli = pair<ll,int>;

namespace noya2{

/*　~ (. _________ . /)　*/

}

using namespace noya2;


#line 2 "c.cpp"


void solve(){
    int n; in(n);
    string s; in(s);
    int sz = s.size();
    vector<int> a(sz);
    rep(i,sz){
        a[i] = (int)(s[i] - '0') - 1;
    }
    vector b(9,vector<int>(9));
    rep(i,sz-1){
        b[a[i]][a[i+1]]++;
    }
    vector<int> p(9); iota(all(p),0);
    int mi = iinf;
    vector<int> ans(9,10);
    do {
        vector<int> pos(9);
        rep(i,9){
            pos[p[i]] = i;
        }
        int cur = 0;
        rep(u,9) rep(v,9){
            int ix = pos[u] / 3, iy = pos[u] % 3;
            int jx = pos[v] / 3, jy = pos[v] % 3;
            cur += (abs(ix - jx) + abs(iy - jy)) * b[u][v];
        }
        if (chmin(mi,cur)){
            ans = p;
        }
    }while(next_permutation(all(p)));
    rep(i,3){
        rep(j,3){
            int d = ans[i*3+j]+1;
            cout << d;
        }
        cout << '\n';
    }
}

int main(){
    int t = 1; //in(t);
    while (t--) { solve(); }
}
accuracy: 1
time_ms: 40
memory_kb: 3968
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=long long;
const ll ILL=2167167167167167167;
const int INF=2100000000;
#define rep(i,a,b) for (int i=(int)(a);i<(int)(b);i++)
#define all(p) p.begin(),p.end()
template<class T> using _pq = priority_queue<T, vector<T>, greater<T>>;
template<class T> int LB(vector<T> &v,T a){return lower_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> int UB(vector<T> &v,T a){return upper_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> bool chmin(T &a,T b){if(b<a){a=b;return 1;}else return 0;}
template<class T> bool chmax(T &a,T b){if(a<b){a=b;return 1;}else return 0;}
template<class T> void So(vector<T> &v) {sort(v.begin(),v.end());}
template<class T> void Sore(vector<T> &v) {sort(v.begin(),v.end(),[](T x,T y){return x>y;});}
bool yneos(bool a,bool upp=false){if(a){cout<<(upp?"YES\n":"Yes\n");}else{cout<<(upp?"NO\n":"No\n");}return a;}
template<class T> void vec_out(vector<T> &p,int ty=0){
    if(ty==2){cout<<'{';for(int i=0;i<(int)p.size();i++){if(i){cout<<",";}cout<<'"'<<p[i]<<'"';}cout<<"}\n";}
    else{if(ty==1){cout<<p.size()<<"\n";}for(int i=0;i<(int)(p.size());i++){if(i) cout<<" ";cout<<p[i];}cout<<"\n";}}
template<class T> T vec_min(vector<T> &a){assert(!a.empty());T ans=a[0];for(auto &x:a) chmin(ans,x);return ans;}
template<class T> T vec_max(vector<T> &a){assert(!a.empty());T ans=a[0];for(auto &x:a) chmax(ans,x);return ans;}
template<class T> T vec_sum(vector<T> &a){T ans=T(0);for(auto &x:a) ans+=x;return ans;}
int pop_count(long long a){int res=0;while(a){res+=(a&1),a>>=1;}return res;}
template<class T> T square(T a){return a * a;}


void solve();
// POP'N ROLL MUSIC / TOMOO
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
    // cin >> t;
    rep(i, 0, t) solve();
}

void solve(){
    int N;
    cin >> N;
    const int M = 9;
    vector<int> p(N);
    vector G(M, vector<int>(M));
    rep(i, 0, N){
        char c;
        cin >> c;
        p[i] = c - '1';
        if (i) G[p[i - 1]][p[i]]++;
    }
    vector C(M, vector<int>(M));
    rep(i, 0, M) rep(j, 0, M){
        C[i][j] = abs(i / 3 - j / 3) + abs(i % 3 - j % 3);
    }
    vector<int> order(M);
    rep(i, 0, M) order[i] = i;
    int cost = INF;
    vector<int> ans;
    do{
        vector<int> inv(M);
        rep(i, 0, M) inv[order[i]] = i;
        int tmp = 0;
        rep(i, 0, M) rep(j, 0, M) tmp += C[inv[i]][inv[j]] * G[i][j];
        if (chmin(cost, tmp)) ans = order;
    }while (next_permutation(all(order)));
    rep(i, 0, 3){
        rep(j, 0, 3) cout << ans[i * 3 + j] + 1;
        cout << "\n";
    }
}
accuracy: 1
time_ms: 20
memory_kb: 3496
final_rank: 5

code_snippet: #include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <iomanip>
#include <numeric>
#include <string>
#include <bitset>
#include <assert.h>
#include <functional>

// #define _GLIBCXX_DEBUG
// #define _LIBCPP_DEBUG 0
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define revrep(i, n) for(int i = (int)(n - 1); i >= 0; --i)
#define range(i, s, t) for (int i = (int)(s); i < (int)(t); ++i)
#define revrange(i, s, t) for(int i = (int)(t - 1); i >= (int)(s); --i)
#define srange(i, s, t, step) for(int i = (int)(s); i < (int)(t); i+=int(step))
#define popcnt(x) __builtin_popcountll(x)
#define hayai std::ios::sync_with_stdio(false);std::cin.tie(nullptr)

using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<long long, long long>;
template<class T> inline bool chmax(T& a, T b){ if (a < b){ a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b){ if (a > b){ a = b; return true; } return false; }
inline bool inside(int x, int y, int h, int w) { return (x >= 0 && x < h && y >= 0 && y < w); }
int dx[] = {0, -1, 0, 1};
int dy[] = {-1, 0, 1, 0};

const ll mod = 1e9+7;

int main() {
    int n; 
    cin >> n;
    string s;
    cin >> s;

    map<pii, int> cnt;
    rep(i, n-1) {
        int x = s[i] - '1';
        int y = s[i + 1] - '1';
        cnt[make_pair(x, y)]++;
    }

    int cost = 1e9;
    vector<int> perm(9), answer(9);
    iota(perm.begin(), perm.end(), 0);
    do {
        vector<pii> loc(9);
        rep(i, 9) {
            loc[perm[i]].first = i / 3;
            loc[perm[i]].second = i % 3;
        }
        int now_cost = 0;
        for (auto [p, c]: cnt) {
            now_cost += c * abs(loc[p.first].first - loc[p.second].first);
            now_cost += c * abs(loc[p.first].second - loc[p.second].second);
        }
        if (now_cost < cost) {
            cost = now_cost;
            copy(perm.begin(), perm.end(), answer.begin());
        }
    } while(next_permutation(perm.begin(), perm.end()));

    rep(i, 3) {
        rep(j, 3) {
            cout << answer[i * 3 + j] + 1;
        }
        cout << endl;
    }
}
accuracy: 1
time_ms: 100
memory_kb: 3488
final_rank: 14

code_snippet: #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;

int main(){
    int n; cin >> n;
    string s; cin >> s;

    vector<int> vec, ans;
    int mincost = 1 << 30;
    for(int i = 1; i <= 9; i++){
        vec.emplace_back(i);
        ans.emplace_back(i);
    }

    vector<vector<int>> cnt(10, vector<int>(10, 0));
    for(int i = 1; i < n; i++) cnt[s[i-1]-'0'][s[i]-'0']++;

    do{
        vector<vector<int>> cost(10, vector<int>(10));
        for(int i = 0; i < 9; i++){
            for(int j = 0; j < 9; j++){
                int ix = i/3, iy = i%3;
                int jx = j/3, jy = j%3;
                cost[vec[i]][vec[j]] = abs(ix-jx)+abs(iy-jy);
            }
        }
        int res = 0;
        for(int i = 1; i <= 9; i++){
            for(int j = 1; j <= 9; j++){
                res += cost[i][j]*cnt[i][j];
            }
        }
        if(mincost > res){
            mincost = res;
            ans = vec;
        }
    }while(next_permutation(vec.begin(), vec.end()));

    for(int i = 0; i < 9; i++){
        cout << ans[i];
        if(i%3 == 2) cout << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 3556
final_rank: 15

code_snippet: #include "bits/stdc++.h"

#define REP(i,num) for(ll i=0;i<(num);++i)
#define FOR(i,c,num) for(ll (i)=(c);(i)<(num);++(i))
#define LOOP(i) while(i--)
#define ALL(c) c.begin(),c.end()
#define PRINTALL(c) for(auto pitr=c.begin();pitr!=c.end();++pitr){cout<<*pitr;if(next(pitr,1)!=c.end())cout<<' ';}cout<<endl;
#define PAIRCOMP(c,comp) [](const pair<ll,ll>& lhs,const pair<ll,ll>& rhs){return lhs.c comp rhs.c;}

using namespace std;
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;

constexpr ll atcoder_mod = 1e9+7;

template<typename T=ll>
T in(){ T x; cin >> x; return (x); }
template<typename T=ll,typename C=vector<T>>
C vecin(int N){ C x(N);REP(i,N){ x[i]=in<T>(); }return x; }

void vout(){ cout << endl; }
template<typename Head,typename... Tail>
void vout(Head&& h,Tail&&... t){ cout << ' ' << h;vout(forward<Tail>(t)...); }
void out(){ cout << endl; }
template<typename Head,typename... Tail>
void out(Head&& h,Tail&&... t){ cout << h;vout(forward<Tail>(t)...); }

template<typename T>
bool chmax(T& a,T b){ if(a<b){ a=b;return true; }return false; }
template<typename T>
bool chmin(T& a,T b){ if(a>b){ a=b;return true; }return false; }

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);

	auto N=in();
	string S=in<string>();
	
	vvll C(10,vll(10,0));
	REP(i,N-1){
		ll L=S[i]-'0';
		ll R=S[i+1]-'0';
		C[R][L]++;
	}

	vll P(9),AP;
	iota(ALL(P),1);
	ll A=1ll<<60;
	do{
		vll T(9);
		REP(i,9){
			T[P[i]-1]=i;
		}
		ll sum=0;
		REP(i,9){
			ll v=T[i];
			REP(j,9){
				ll u=T[j];
				ll F=abs((v%3)-(u%3))+abs((v/3)-(u/3));
				sum += C[i+1][j+1]*F;
			}
		}
		if(sum<A){
			A=sum;
			AP=P;
		}
		else if(sum==A){
			if(lexicographical_compare(ALL(P),ALL(AP))){
				AP=P;
			}
		}
	} while(next_permutation(ALL(P)));

	cout << AP[0] << AP[1] << AP[2] << endl;
	cout << AP[3] << AP[4] << AP[5] << endl;
	cout << AP[6] << AP[7] << AP[8] << endl;
	return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 3588
final_rank: 7

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>
//using namespace atcoder;
const double pi = 3.141592653589793238462643383279;
using namespace std;
//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<long long, long long> PLL;
typedef pair<int, PII> TIII;
typedef long long LL;
typedef unsigned long long ULL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;

//container util
//------------------------------------------
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SQ(a) ((a) * (a))
#define EACH(i, c) for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define EXIST(s, e) ((s).find(e) != (s).end())
#define SORT(c) sort((c).begin(), (c).end())

//repetition
//------------------------------------------
#define FOR(i, s, n) for (int i = s; i < (int)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define MOD 1000000007

#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define trav(a, x) for (auto &a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
const double EPS = 1e-7, PI = acos(-1);
//ここから編集


int main()
{
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(6);

  int N; cin >> N;
  string s; cin >> s;
  
  map<string, int> mp;
  for(int i=0; i<s.size()-1; i++){
    string t="";
    t += s[i];
    t += s[i+1];
    mp[t]++;
  }

  vector<pair<int, string>> vp;
  for(int i=1; i<10; i++){
    for(int j=1; j<10; j++){
      string t = "";
      t += (char)('0' + i);
      t += (char)('0' + j);
      mp[t];
    }
  }
  
  vector<int> arr;
  for(int i=1; i<10; i++) arr.push_back(i);
  ll  tmp = INT_MAX;
  vector<int> ans;
  do{
    ll cost = 0;
    vector<vector<int>> dist(10, vector<int>(10));
    for(int i=0; i<9; i++){
      for(int j=0; j<9; j++){
        int ty = i/3, tx = i%3;
        int sy = j/3, sx = j%3;
        dist[arr[i]][arr[j]] = abs(ty-sy) + abs(tx-sx); 
      }
    }
    for(auto e: mp){
      cost += e.second * dist[e.first[0]-'0'][e.first[1]-'0'];
    }
    if(tmp > cost) {
      tmp = cost;
      ans = arr;
    }else if(tmp == cost){
      bool f = true;
      for(int i=0; i<9; i++){
        if(arr[i] > ans[i]){
          f = false;
          break;
        }
        if(arr[i] < ans[i]){
          f = true;
          break;
        }
      }
      if(f){
        ans = arr;
      }
    }
  }while(next_permutation(all(arr)));
  REP(i,9){
    cout << ans[i];
    if(i%3 == 2) cout << endl;
  }
  return 0;
}
accuracy: 1
time_ms: 350
memory_kb: 3528
final_rank: 17

code_snippet: #include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const static int INFTY = (1 << 30);
int nums[10][10];
int xs[10], ys[10];
map<int, pair<int, int> > dist;
char a[100001];

int main()
{
    int N, curr, next;
    int test[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int finalNum[10];
    scanf("%d", &N);
    scanf("%s", a);
    memset(nums, 0, sizeof (nums));
    curr = int(a[0] - '0');
    for (int i = 1; i < N; i++) {
        next = int(a[i] - '0');
        nums[curr][next]++;
        curr = next;
    }
    int global_min = INFTY;
    do {
        curr = 0;
        int idx = 0;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) xs[test[idx]] = i, ys[test[idx++]] = j;
        }

        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= 9; j++) {
                if (nums[i][j]) curr += nums[i][j] * (abs(xs[i] - xs[j]) + abs(ys[i] - ys[j]));
            }
        }
        if (curr < global_min) {
            for (int i = 0; i < 9; i++) finalNum[i] = test[i];
            global_min = curr;
        }

    } while (next_permutation(test, test+9));

    int idx = 0;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) printf("%d", finalNum[idx++]);
        printf("\n");
    }

    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 2852
final_rank: 4

code_snippet: #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=3053"

#include<bits/stdc++.h>
using namespace std;

#define call_from_test
#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
struct FastIO{
  FastIO(){
    cin.tie(0);
    ios::sync_with_stdio(0);
  }
}fastio_beet;
//END CUT HERE
#ifndef call_from_test
signed main(){
  return 0;
}
#endif

#ifndef call_from_test
#include<bits/stdc++.h>
using namespace std;
#endif
//BEGIN CUT HERE
template<typename F>
void all_permutations(int n,F f){
  vector<int> vs(n);
  iota(vs.begin(),vs.end(),0);
  do f(vs); while(next_permutation(vs.begin(),vs.end()));
}
//END CUT HERE
#ifndef call_from_test
//INSERT ABOVE HERE
signed ABC054_C(){
  int n,m;
  cin>>n>>m;
  int es[10][10]={};
  for(int i=0;i<m;i++){
    int a,b;
    cin>>a>>b;
    a--;b--;
    es[a][b]=es[b][a]=1;
  }
  int ans=0;
  auto f=
    [&](const auto &vs){
      if(!es[0][vs[0]+1]) return;
      for(int i=0;i+1<n-1;i++)
        if(!es[vs[i]+1][vs[i+1]+1]) return;
      ans++;
    };
  all_permutations(n-1,f);
  cout<<ans<<endl;
  return 0;
}
/*
  verified on 2019/12/09
  https://atcoder.jp/contests/abc054/tasks/abc054_c
*/

signed main(){
  ABC054_C();
  return 0;
}
#endif

#undef call_from_test

signed main(){
  int n;
  string s;
  cin>>n>>s;

  int c[10][10]={};
  for(int i=0;i+1<n;i++){
    int a=s[i]-'0',b=s[i+1]-'0';
    c[a][b]++;
  }

  int ans=n*100;
  vector<int> us;
  auto f=
    [&](auto vs){
      int x[10],y[10];
      for(int i=0;i<9;i++){
        x[vs[i]+1]=i%3;
        y[vs[i]+1]=i/3;
      }

      int res=0;
      for(int i=1;i<=9;i++)
        for(int j=1;j<=9;j++)
          res+=c[i][j]*(abs(x[i]-x[j])+abs(y[i]-y[j]));

      if(res<ans) ans=res,us=vs;
    };
  all_permutations(9,f);

  for(int i=0;i<9;i++){
    cout<<us[i]+1;
    if(i%3==2) cout<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 3344
final_rank: 6

code_snippet: /*  -*- coding: utf-8 -*-
 *
 * 3053.cc: 
 */

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
 
using namespace std;

/* constant */

const int MAX_N = 100000;
const int M = 9;
const int W = 3;
const int INF = 1 << 30;

/* typedef */

/* global variables */

char s[MAX_N + 4];
int mvs[M][M], ds[M][M], ps[M];

/* subroutines */

inline int ps2i(int ps[]) {
  int sum = 0;
  for (int i = 0; i < M; i++) sum = sum * 10 + ps[i];
  return sum;
}

inline void pos2xy(int pos, int &x, int &y) { x = pos % W, y = pos / W; }
inline int xy2pos(int x, int y) { return y * W + x; }

inline int dist(int pi, int pj) {
  int xi, yi, xj, yj;
  pos2xy(pi, xi, yi), pos2xy(pj, xj, yj);
  return abs(xj - xi) + abs(yj - yi);
}

/* main */

int main() {
  int n;
  scanf("%d%s", &n, s);

  for (int i = 0, j = 1; j < n; i++, j++)
    if (s[i] != s[j]) {
      int di = s[i] - '1', dj = s[j] - '1';
      mvs[di][dj]++;
    }

  for (int i = 0; i < M; i++)
    for (int j = 0; j < M; j++) ds[i][j] = dist(i, j);
  for (int i = 0; i < M; i++) ps[i] = i;

  int mind = INF, minph = 0;

  do {
    //printf("%09d\n", ps2i(ps));
    int d = 0;
    for (int i = 0; i < M; i++)
      for (int j = 0; j < M; j++)
	d += mvs[ps[i]][ps[j]] * ds[i][j];

    if (mind > d)
      mind = d, minph = ps2i(ps);
    else if (mind == d) {
      int ph = ps2i(ps);
      if (minph > ph) minph = ph;
    }
  } while (next_permutation(ps, ps + M));
  //printf("%09d\n", minph);

  for (int y = 0, e = 100000000; y < W; y++) {
    for (int x = 0; x < W; x++, e /= 10)
      putchar('1' + (minph / e) % 10);
    putchar('\n');
  }
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3260
final_rank: 1

code_snippet: #include <bits/stdc++.h>
  
using namespace std;
  
#define rep(i,n) REP(i,0,n)
#define REP(i,s,e) for(int i=(s); i<(int)(e); i++)
#define repr(i, n) REPR(i, n, 0)
#define REPR(i, s, e) for(int i=(int)(s-1); i>=(int)(e); i--)
#define pb push_back
#define all(r) r.begin(),r.end()
#define rall(r) r.rbegin(),r.rend()
#define fi first
#define se second
  
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
 
const int INF = 1e9;
const ll MOD = 1e9 + 7;
double EPS = 1e-8;

int cnt[9][9];
int dist[9][9];

int dx[] = {0, -1, 0, 1};
int dy[] = {-1, 0, 1, 0};

int main(){
    rep(i, 9) rep(j, 9) dist[i][j] = INF;
    rep(i, 9) dist[i][i] = 0;
    rep(y, 3) rep(x, 3) {
        int cur = y * 3 + x;
        rep(i, 4) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if(nx < 0 || nx >= 3 || ny < 0 || ny >= 3) continue;
            int nxt = ny * 3 + nx;
            dist[cur][nxt] = 1;
        }
    }
    rep(k, 9) rep(i, 9) rep(j, 9) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);

    // rep(i, 9) {
    //     rep(j, 9) cout << dist[i][j] << " ";
    //     cout << endl;
    // }

    // cout << endl;
    // rep(i, 9) {
    //     rep(j, 9) cout << cnt[i][j] << " ";
    //     cout << endl;
    // }

    int n;
    string s;
    cin >> n >> s;
    rep(i, n-1) {
        cnt[s[i]-'1'][s[i+1]-'1']++;
    }
    // cout << n << endl << s << endl;


    // cout << endl;
    // rep(i, 9) {
    //     rep(j, 9) cout << cnt[i][j] << " ";
    //     cout << endl;
    // }

    auto calc = [&](const vector<int>& a) {
        int ret = 0;
        rep(i, 9) rep(j, 9) ret += cnt[a[i]][a[j]] * dist[i][j];
        return ret;
    };

    vi a(9);
    rep(i, 9) a[i] = i;

    vi ans;
    int ans_cnt = INF;
    do {
        int tmp = calc(a);
        if(tmp < ans_cnt) {
            ans_cnt = tmp;
            ans = a;
        }
        // for(auto&& x : a) cout << " " << x;
        //     cout << " -> " << tmp << endl;
    }while(next_permutation(all(a)));
    rep(i, 3) {
        rep(j, 3) {
            cout << ans[i*3+j]+1;
        }
        cout << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3340
final_rank: 3

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;

int di[9] = {0, 0, 0, 1, 1, 1, 2, 2, 2};
int dj[9] = {0, 1, 2, 0, 1, 2, 0, 1, 2};

int main(){
    int n;
    cin >> n;
    string s;
    cin >> s;
    int cnt[9][9] = {};
    for(int i = 1; i < s.length(); i++){
        int from = s[i-1]-'1', to = s[i]-'1';
        cnt[from][to]++;
        cnt[to][from]++;
    }
    vector<int> ans(9), arr(9);
    for(int i = 0; i < 9; i++)  arr[i] = i;
    int ma = 1<<30;
    do{
        int rev[9];
        for(int i = 0; i < 9; i++){
            rev[arr[i]] = i;
        }
        int tmp = 0;
        for(int i = 0; i < 9; i++){
            for(int j = i+1; j < 9; j++){
                int dist = abs(di[rev[i]]-di[rev[j]])+abs(dj[rev[i]]-dj[rev[j]]);
                tmp += dist * cnt[i][j];
            }
        }
        if(tmp < ma){
            ma = tmp;
            ans = arr;
        }
    }while(next_permutation(arr.begin(), arr.end()));
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cout << ans[i*3+j]+1;
        }
        cout << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3284
final_rank: 2

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;

int di[9] = {0, 0, 0, 1, 1, 1, 2, 2, 2};
int dj[9] = {0, 1, 2, 0, 1, 2, 0, 1, 2};

int main(){
    int n;
    cin >> n;
    string s;
    cin >> s;
    int cnt[9][9] = {};
    for(int i = 1; i < s.length(); i++){
        int from = s[i-1]-'1', to = s[i]-'1';
        cnt[from][to]++;
        cnt[to][from]++;
    }
    vector<int> ans(9), arr(9);
    for(int i = 0; i < 9; i++)  arr[i] = i;
    int ma = 1<<30;
    do{
        map<int,int> m;
        for(int i = 0; i < 9; i++){
            m[arr[i]] = i;
        }
        int tmp = 0;
        for(int i = 0; i < 9; i++){
            for(int j = i+1; j < 9; j++){
                int dist = abs(di[m[i]]-di[m[j]])+abs(dj[m[i]]-dj[m[j]]);
                tmp += dist * cnt[i][j];
            }
        }
        if(tmp < ma){
            ma = tmp;
            ans = arr;
        }
    }while(next_permutation(arr.begin(), arr.end()));
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cout << ans[i*3+j]+1;
        }
        cout << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 450
memory_kb: 3256
final_rank: 18

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}

//INSERT ABOVE HERE
signed main(){
  int n;
  string s;
  cin>>n>>s;

  int c[10][10]={};
  for(int i=0;i+1<n;i++){
    int a=s[i]-'0',b=s[i+1]-'0';
    c[a][b]++;
  }

  vector<int> v(9);
  iota(v.begin(),v.end(),1);

  int ans=n*100;
  vector<int> u;
  do{
    int x[10],y[10];
    for(int i=0;i<9;i++){
      x[v[i]]=i%3;
      y[v[i]]=i/3;
    }

    int res=0;
    for(int i=1;i<=9;i++)
      for(int j=1;j<=9;j++)
        res+=c[i][j]*(abs(x[i]-x[j])+abs(y[i]-y[j]));

    if(res<ans) ans=res,u=v;
  }while(next_permutation(v.begin(),v.end()));

  for(int i=0;i<9;i++){
    cout<<u[i];
    if(i%3==2) cout<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 80
memory_kb: 3332
final_rank: 10

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define NUM 100005

struct LOC{
	void set(int arg_row,int arg_col){
		row = arg_row;
		col = arg_col;
	}
	int row,col;
};

int LENGTH;
int min_change;

int table_index;
int table[362880][9];
int tmp_array[9],phone[3][3],ans[3][3],adj[10][10];
bool used[10];
char buf[NUM];
LOC loc[10];

void recursive(int index){

	if(index == 9){

		for(int i = 0; i < 9; i++){
			table[table_index][i] = tmp_array[i];
		}
		table_index++;

		return;
	}

	for(int i = 1; i <= 9; i++){

		if(used[i])continue;
		tmp_array[index] = i;
		used[i] = true;
		recursive(index+1);
		used[i] = false;
	}
}

void calc(int num_index){

	int index = 0;

	//電話を作成
	for(int row = 0; row < 3; row++){
		for(int col = 0; col < 3; col++){
			phone[row][col] = table[num_index][index++];
			loc[phone[row][col]].set(row,col);
		}
	}

	int count = 0;
	//指は最初の数字に合わせておく

	for(int i = 1; i <= 9; i++){
		for(int k = 1; k <= 9; k++){
			count += (abs(loc[i].row-loc[k].row)+abs(loc[i].col-loc[k].col))*adj[i][k];
		}
	}

	if(count < min_change){
		for(int row = 0; row < 3; row++){
			for(int col = 0; col < 3; col++){
				ans[row][col] = phone[row][col];
			}
		}
		min_change = count;
	}
}



int main(){

	scanf("%d",&LENGTH);
	scanf("%s",buf);

	for(int i = 1; i <= 9; i++){
		for(int k = 1; k <= 9; k++){
			adj[i][k] = 0;
		}
	}

	//隣接回数を数える
	for(int i = 1; i < LENGTH; i++){

		adj[buf[i]-'0'][buf[i-1]-'0']++;
	}

	table_index = 0;

	for(int i = 1; i <= 9; i++)used[i] = false;

	//9!の数列を作る
	for(int i = 1; i <= 9; i++){

		tmp_array[0] = i;
		used[i] = true;
		recursive(1);

		used[i] = false;
	}

	min_change = BIG_NUM;

	for(int i = 0; i < table_index; i++){

		calc(i);
	}


	for(int row = 0; row < 3; row++){
		for(int col = 0; col < 3; col++){
			printf("%d",ans[row][col]);
		}
		printf("\n");
	}


	return 0;
}
accuracy: 1
time_ms: 50
memory_kb: 16052
final_rank: 19

code_snippet: #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cctype>
#include<math.h>
#include<string>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
#include<utility>
#include<set>
#include<map>
#include<stdlib.h>
#include<iomanip>

using namespace std;

#define ll long long
#define ld long double
#define EPS 0.0000000001
#define INF 1e9
#define LINF (ll)INF*INF
#define MOD 1000000007
#define rep(i,n) for(int i=0;i<(n);i++)
#define loop(i,a,n) for(int i=a;i<(n);i++)
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)

#define int ll //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int,int> pii;
typedef vector<pii> vp;

int gcd(int a, int b){
    if(b==0) return a;
    return gcd(b,a%b);
}
int lcm(int a, int b){
    return a/gcd(a,b)*b;
}


signed main(void) {
    int n;
    cin >> n;
    string s;
    cin >> s;
    int num[10][10] = {};
    rep(i,n-1)num[s[i]-'0'][s[i+1]-'0']++;
    vi v(9);
    rep(i,9)v[i] = i+1;
    vector<vi> ans(3,vi(3));
    int sum = LINF;
    do{
        int t = 0;
        rep(i,9)rep(j,9){
            int xa = i/3, ya = i%3;
            int xb = j/3, yb = j%3;
            t += num[v[i]][v[j]] * (abs(xa-xb) + abs(ya-yb));
        }
        if(t < sum){
            sum = t;
            rep(i,3)rep(j,3)ans[i][j] = v[i*3+j];
        }
    }while(next_permutation(all(v)));
    rep(i,3){
        rep(j,3)cout << ans[i][j];
        cout << endl;
    }
}
accuracy: 1
time_ms: 60
memory_kb: 3304
final_rank: 8

code_snippet: #include <bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
using namespace std;

pair<int,string> v=make_pair(19191919,"1919");
string A="123456789";
char pat[114514];
int n,cnt[10][10];

int cal(string s){
    int a[3][3],x[10],y[10],sum=0;
    r(i,3){
        r(j,3){
            int p=(s[i*3+j]-'0');
            a[i][j]=p;
            x[p]=j;
            y[p]=i;
        }
    }
    r(i,10){
        r(j,10){
            int X=abs(x[i]-x[j]);
            int Y=abs(y[i]-y[j]);
            sum += (X+Y)*cnt[i][j];
        }
    }
    return sum;
}

int main(){
    scanf("%d%s",&n,pat);
    r(i,n-1){
        cnt[pat[i]-'0'][pat[i+1]-'0']++;
    }
    do{
        v=min(v,make_pair(cal(A),A));
    }while(next_permutation(A.begin(),A.end()));

    cout<<v.second.substr(0,3)<<endl;
    cout<<v.second.substr(3,3)<<endl;
    cout<<v.second.substr(6,3)<<endl;
}
accuracy: 1
time_ms: 80
memory_kb: 3340
final_rank: 11

code_snippet: #include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
const int INF=1e9,MOD=1e9+7;
const ll LINF=1e18;
using namespace std;
#define int long long
//template
int d[10][10];
//main
signed main(){
  int N;string s;cin>>N>>s;
  std::vector<int> ans(9);
  memset(d,0,sizeof(d));
  for(int i=1;i<N;i++)d[s[i-1]-'0'][s[i]-'0']++;
  std::vector<int> v(9);
  for(int i=0;i<9;i++)v[i]=i+1;
  int mi=1e9;
  do{
    int res=0;
    for(int i=0;i<9;i++){
      for(int j=0;j<9;j++){
        res+=(abs(i/3-j/3)+abs(i%3-j%3))*d[v[i]][v[j]];
      }
    }
    if(res<mi){
      mi=res;
      for(int i=0;i<9;i++)ans[i]=v[i];
    }
  }while (std::next_permutation(v.begin(), v.end()));
  for(int i=0;i<9;i++){
    cout<<ans[i];
    if(i%3==2)cout<<endl;
  }
  /*
  for(int i=0;i<10;i++){
    for(int j=0;j<10;j++)cout<<d[i][j]<<" ";
    cout<<endl;
  }
  */
}
accuracy: 1
time_ms: 80
memory_kb: 3368
final_rank: 12

code_snippet: #include <bits/stdc++.h>
#define chmin(a, b) ((a)=min((a), (b)))
#define chmax(a, b) ((a)=max((a), (b)))
#define fs first
#define sc second
#define eb emplace_back
using namespace std;

typedef long long ll;
typedef pair<int, int> P;
typedef tuple<int, int, int> T;

const ll MOD=1e9+7;
const ll INF=1e18;
const double pi=acos(-1);
const double eps=1e-10;

int dx[]={1, -1, 0, 0};
int dy[]={0, 0, 1, -1};

int main(){
    int n; cin>>n;
    string s; cin>>s;

    // count i -> j 
    int num[10][10];
    memset(num, 0, sizeof(num));
    for(int i=0; i<n-1; i++){
        num[s[i]-'0'][s[i+1]-'0']++;
    }

    vector<int> v(9);
    iota(v.begin(), v.end(), 1);

    ll costmin=INF;
    vector<int> ans(9);
    do{
        int phone[3][3];
        for(int i=0; i<9; i++){
            phone[i/3][i%3]=v[i];
        }

        int cost[10][10];
        for(int i=0; i<9; i++){
            for(int j=0; j<9; j++){
                cost[phone[i/3][i%3]][phone[j/3][j%3]]=abs(i/3-j/3)+abs(i%3-j%3);
            }
        }

        ll sum=0;
        for(int i=1; i<=9; i++){
            for(int j=1; j<=9; j++){
                sum+=cost[i][j]*num[i][j];
            }
        }

        if(sum<costmin){
            costmin=sum;
            ans=v;
        }

    }while(next_permutation(v.begin(), v.end()));

    for(int i=0; i<9; i++){
        cout << ans[i];
        if((i+1)%3==0) cout << endl;
    }
}
accuracy: 1
time_ms: 130
memory_kb: 3368
final_rank: 16