Problem:
りんごだいぼうけん
square1001君とE869120君は縦 $H$ 行、横 $W$ 列のグリッドの世界に迷い込んでしまいました!
この世界の神は言いました。
「リンゴを $K$ 個集めて二人が出会ったとき、さすれば元の世界に帰れるであろう。」
この言葉を聞いたsquare1001君は、リンゴを $K$ 個以上集めてE869120君がいるマスへ向かうことにしました。
ここで、グリッドの各マスは次のように表されます。
's'：square1001君がいるマスです。
'e'：E869120君がいるマスです。
'a'：リンゴが1つ落ちているマスです。このマスを初めて訪れたときにリンゴを1つ得ることができます。
このグリッド上にこのマスは20個以下しかありません。
'#'：壁です。このマスに訪れることはできません。
'.'：何もないマスです。このマスに訪れることができます。
square1001君は自分がいるマスから上下左右に隣り合うマスへの移動を繰り返すことで、目的を達成しようとします。ただし、グリッドから外に出ることはできません。
square1001君が目的を達成するために必要な移動回数の最小値を求めてください。
ただし、E869120君が動くことはないものとします。また、square1001君はリンゴを $K$ 個以上持ち運ぶ能力があるものとします。
また、目標が達成できないときは「-1」を出力してください。
入力
入力は以下の形式で標準入力から与えられる。
グリッドの上から $i$ マス目、左から $j$ マス目の文字を $A_{i, j}$ とする。
$H$ $W$ $K$
$A_{1,1} A_{1,2} A_{1,3} \cdots A_{1,W}$
$A_{2,1} A_{2,2} A_{2,3} \cdots A_{2,W}$
$A_{3,1} A_{3,2} A_{3,3} \cdots A_{3,W}$
 $\ldots$
$A_{H,1} A_{H,2} A_{H,3} \cdots A_{H,W}$
出力
square1001君が目的を達成するまでに必要な移動回数の最小値を求めてください。ただし、不可能な場合は「-1」を出力してください。
ただし、最後には改行を入れること。
制約
$1 \leq H \leq 1000$
$1 \leq W \leq 1000$
$1 \leq K \leq 20$
$H, W, K$ は整数である。
$A_{i, j}$ は 's'、'e'、'a'、'#'、'.'のいずれかである。
グリッドに 's'、'e'はそれぞれただ 1 つのみ含まれる。
グリッドに含まれる 'a' の数は $K$ 個以上 $20$ 個以下である。
入力例1
5 5 2
s..#a
.#...
a#e.#
...#a
.#...
出力例1
14
入力例2
7 7 3
.......
.s...a.
a##...a
..###..
.a#e#.a
#.###..
a..#..a
出力例2
-1
目的が達成不可能な場合は「-1」を出力してください。
入力例3
12 12 10
.#####......
.##.....#...
....a.a#a..#
.#..#a......
##.....a#s..
#..a###.##.#
.e#.#.#.#a..
..#a#.....#.
#..##a......
.a...a.a..#.
a....#a.aa..
...a.#...#a.
出力例3
30

Submitted solutions:

code_snippet: // AOJ #3136 Apple Adventure
// 2025.3.21

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 1e9;

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int h, w, k;
    cin >> h >> w >> k;
    vector<string> g(h);
    for (int i = 0; i < h; i++) cin >> g[i];

    pair<int,int> s, e;
    vector<pair<int,int>> a;
    for (int i = 0; i < h; i++){
        for (int j = 0; j < w; j++){
            char c = g[i][j];
            if(c=='s') s = {i,j};
            else if(c=='e') e = {i,j};
            else if(c=='a') a.push_back({i,j});
        }
    }
    int n = a.size();
    vector<pair<int,int>> p;
    p.push_back(s);
    for(auto &pp: a) p.push_back(pp);
    p.push_back(e);
    int m = p.size();

    vector<vector<int>> d(m, vector<int>(m, INF));

    int di[4] = {1, -1, 0, 0};
    int dj[4] = {0, 0, 1, -1};

    for (int i = 0; i < m; i++){
        vector<vector<int>> dist(h, vector<int>(w, -1));
        queue<pair<int,int>> qu;
        auto [si, sj] = p[i];
        dist[si][sj] = 0;
        qu.push({si, sj});
        while(!qu.empty()){
            auto [ci, cj] = qu.front();
            qu.pop();
            for (int d_ = 0; d_ < 4; d_++){
                int ni = ci + di[d_], nj = cj + dj[d_];
                if(ni < 0 || ni >= h || nj < 0 || nj >= w) continue;
                if(g[ni][nj]=='#') continue;
                if(dist[ni][nj] != -1) continue;
                dist[ni][nj] = dist[ci][cj] + 1;
                qu.push({ni, nj});
            }
        }
        for (int j = 0; j < m; j++){
            auto [ti, tj] = p[j];
            if(dist[ti][tj] != -1) d[i][j] = dist[ti][tj];
        }
    }

    int sz = 1 << n;
    vector<vector<int>> dp(sz, vector<int>(n+1, INF));
    dp[0][0] = 0;
    for (int mask = 0; mask < sz; mask++){
        for (int i = 0; i <= n; i++){
            if(dp[mask][i]==INF) continue;
            for (int j = 1; j <= n; j++){
                if(mask & (1 << (j-1))) continue;
                if(d[i][j]==INF) continue;
                int nmask = mask | (1 << (j-1));
                dp[nmask][j] = min(dp[nmask][j], dp[mask][i] + d[i][j]);
            }
        }
    }

    int ans = INF;
    for (int mask = 0; mask < sz; mask++){
        if(__builtin_popcount(mask) < k) continue;
        for (int i = 0; i <= n; i++){
            if(dp[mask][i]==INF || d[i][m-1]==INF) continue;
            ans = min(ans, dp[mask][i] + d[i][m-1]);
        }
    }
    cout << (ans==INF ? -1 : ans) << endl;
    return 0;
}
accuracy: 1
time_ms: 970
memory_kb: 127008
final_rank: 6

code_snippet: /* -*- coding: utf-8 -*-
 *
 * 3136.cc: Apple Adventure
 */

#include<cstdio>
#include<queue>
#include<algorithm>
#include<utility>
 
using namespace std;

/* constant */

const int MAX_H = 1000;
const int MAX_W = 1000;
const int MAX_HW = MAX_H * MAX_W;
const int MAX_M = 20;
const int MBITS = 1 << MAX_M;
const int MAX_GN = MAX_M + 2;
const int MAX_K = 20;
const int INF = 1 << 30;

const int dys[] = { 0, 1, 0, -1 }, dxs[] = { 1, 0, -1, 0 };

/* typedef */

typedef queue<int> qi;
typedef pair<int,int> pii;

/* global variables */

char fs[MAX_H][MAX_W + 4];
int aps[MAX_GN], ads[MAX_GN][MAX_GN], ds[MAX_HW];
int bnums[MBITS], dp[MBITS][MAX_M];

/* subroutines */

void bfs(int h, int w, int s) {
  int hw = h * w;
  fill(ds, ds + hw, INF);
  ds[s] = 0;

  qi q;
  q.push(s);

  while (! q.empty()) {
    int u = q.front(); q.pop();
    int uy = u / w, ux = u % w;

    for (int di = 0; di < 4; di++) {
      int vy = uy + dys[di], vx = ux + dxs[di], v = vy * w + vx;
      if (vy >= 0 && vy < h && vx >= 0 && vx < w &&
	  fs[vy][vx] != '#' && ds[v] >= INF) {
	ds[v] = ds[u] + 1;
	q.push(v);
      }
    }
  }
}

inline void setmin(int &a, int b) { if (a > b) a = b; }

/* main */

int main() {
  int h, w, k;
  scanf("%d%d%d", &h, &w, &k);

  int m = 0, stp = -1, glp = -1;
  for (int y = 0, p = 0; y < h; y++) {
    scanf("%s", fs[y]);
    for (int x = 0; x < w; x++, p++)
      switch (fs[y][x]) {
      case 's': stp = p; break;
      case 'e': glp = p; break;
      case 'a': aps[m++] = p; break;
      }
  }
  
  int gn = m + 2, st = m, gl = m + 1;
  aps[st] = stp, aps[gl] = glp;

  for (int i = 0; i < gn; i++) {
    bfs(h, w, aps[i]);
    for (int j = 0; j < gn; j++) {
      ads[i][j] = ds[aps[j]];
      //printf("%d ", (ads[i][j] < INF) ? ads[i][j] : -1);
    }
    //putchar('\n');
  }

  int mbits = 1 << m, mmsk = mbits - 1;

  bnums[0] = 0;
  for (int bits = 1, msb = 1; bits < mbits; bits++) {
    if ((msb << 1) <= bits) msb <<= 1;
    bnums[bits] = bnums[bits ^ msb] + 1;
  }

  for (int bits = 0; bits < mbits; bits++)
    fill(dp[bits], dp[bits] + m, INF);
  for (int i = 0, bi = 1; i < m; i++, bi <<= 1)
    if (ads[st][i] < INF) dp[bi][i] = ads[st][i];

  int mind = INF;
  for (int bits = 0; bits < mbits; bits++)
    for (int i = 0; i < m; i++)
      if (dp[bits][i] < INF) {
	if (bnums[bits] >= k && ads[i][gl] < INF)
	  setmin(mind, dp[bits][i] + ads[i][gl]);

	for (int j = 0, bj = 1; j < m; j++, bj <<= 1)
	  if (! (bits & bj) && ads[i][j] < INF)
	    setmin(dp[bits | bj][j], dp[bits][i] + ads[i][j]);
      }

  printf("%d\n", (mind < INF) ? mind : -1);

  return 0;
}
accuracy: 1
time_ms: 880
memory_kb: 93840
final_rank: 1

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline ll time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

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

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int h,w,K; cin >> h >> w >> K;
    vector<string> s(h);
    vector<pair<int,int>> v(2);
    for(int i=0;i<h;i++){
        cin >> s[i];
        for(int j=0;j<w;j++){
            if(s[i][j] == 'a'){
                v.push_back({i,j});
                s[i][j] = '.';
            }
            else if(s[i][j] == 's'){
                v[0] = {i,j};
                s[i][j] = '.';
            }
            else if(s[i][j] == 'e'){
                v[1] = {i,j};
                s[i][j] = '.';
            }
        }
    }
    int n = v.size();
    const int inf = 1e9;
    vector<vector<int>> dist(n,vector<int>(n,inf));
    for(int i=0;i<n;i++){
        vector<vector<int>> d(h,vector<int>(w,inf));
        d[v[i].first][v[i].second] = 0;
        queue<pair<int,int>> q;
        q.push(v[i]);
        while(q.size()){
            auto p = q.front(); q.pop();
            int x = p.first, y = p.second;
            for(int j=0;j<4;j++){
                int nx = x + dx[j];
                int ny = y + dy[j];
                if(0 <= nx and nx < h and 0 <= ny and ny < w and s[nx][ny] == '.' and d[nx][ny] == inf){
                    d[nx][ny] = d[x][y] + 1;
                    q.push({nx,ny});
                }
            }
        }
        for(int j=0;j<n;j++){
            dist[i][j] = d[v[j].first][v[j].second];
        }
    }
    vector<vector<int>> dp(1<<(n-2), vector<int>(n, inf));
    dp[0][0] = 0;
    for(int i=0;i<(1<<(n-2));i++){
        for(int j=0;j<n;j++){
            if(dp[i][j] == inf)continue;
            for(int k=2;k<n;k++){
                if((1<<(k-2))&i)continue;
                int nx = i|(1<<(k-2));
                dp[nx][k] = min(dp[nx][k], dp[i][j]+dist[j][k]);
            }
        }
    }
    int res = inf;
    for(int i=0;i<(1<<(n-2));i++){
        for(int j=0;j<n;j++){
            if(dp[i][j] == inf)continue;
            if(__builtin_popcount(i) >= K){
                res = min(res, dp[i][j]+dist[j][1]);
            }
        }
    }
    if(res == inf) res = -1;
    cout << res << endl;
}
accuracy: 1
time_ms: 1000
memory_kb: 126920
final_rank: 7

code_snippet: #include <cstdio>
#include <utility>
#include <queue>
#include <vector>

const int SIZE=1000;
const int APPLE_NUM=20;

using namespace std;

typedef pair<int,int> coordinate;

// 迷宮自体
int H,W,K;
char maze[SIZE][SIZE+1];

// 各ラウンドでアクセスしたか
char maze_visited[SIZE][SIZE][APPLE_NUM+2];

// 林檎と人の位置
int total_a_num,S_index,E_index;
vector<coordinate> key_points;
coordinate S,E;

// 各林檎の間の距離、人を含む
int dist_vec[22][22];



void init_dist(){
    for (int i=0;i<22;i++)
        for (int j=0;j<22;j++)
            dist_vec[i][j]=-1;
}

char get_maze_item(const coordinate& pos){
    return maze[pos.second][pos.first];
}

bool in_maze(const coordinate& pos){
    return pos.first>=0&&pos.first<W&&pos.second>=0&&pos.second<H;
}

bool pos_visited(const coordinate& pos,int i){

    return maze_visited[pos.second][pos.first][i];
}

void explore_pos(const coordinate& pos,int i,queue<coordinate>& Q,queue<int>& dist_Q,int cur_dist){
    if (in_maze(pos) && !pos_visited(pos, i) && get_maze_item(pos)!= '#')
        Q.push(pos),
        maze_visited[pos.second][pos.first][i] = 1, 
        dist_Q.push(cur_dist + 1);
    ;
    ;
}

int find_index(const coordinate& pos){
    for (int i=0;i<key_points.size();i++)
        if (key_points[i]==pos) return i;
}

void BFS(int vert){
    coordinate ini;

    ini=key_points[vert];
    
    queue<coordinate> Q;
    queue<int> dist_Q;
    explore_pos(ini, vert, Q, dist_Q, -1);
    // dist_Q.push(0);
    
    // printf("vert=%d,pos=(%d,%d)\n", vert,ini.second,ini.first);

    while (!Q.empty()){
        //
        const coordinate cur=Q.front();
        const int cur_dist=dist_Q.front();
        Q.pop();
        dist_Q.pop();

        // printf("(%d,%d),dist=%d\n",cur.second,cur.first,cur_dist);

        //todo
        char maze_item=get_maze_item(cur);
        if (maze_item=='a'||maze_item=='e'||maze_item=='s'){
            int index=find_index(cur);
            dist_vec[vert][index]=cur_dist;
            dist_vec[index][vert] = cur_dist;
        }
        

        coordinate left(cur.first-1,cur.second)
        ,right(cur.first+1,cur.second)
        ,up(cur.first,cur.second-1)
        ,down(cur.first,cur.second+1);

        // 左のポジションを探索
        explore_pos(left,vert,Q,dist_Q,cur_dist);
        

        // 左のポジションを探索
        explore_pos(right, vert, Q, dist_Q, cur_dist);

        // 左のポジションを探索
        explore_pos(up, vert, Q,dist_Q, cur_dist);

        // 左のポジションを探索
        explore_pos(down, vert, Q, dist_Q, cur_dist);
    }

}

bool is_possible(){
    if (dist_vec[S_index][E_index]==-1)
        return false;

    int count=0;
    for (int i=0;i<total_a_num;i++)
        if (dist_vec[S_index][i]!=-1) count++;

    return count>=K;
}


int dp[20][1<<20];

int bit_count(int state){
    int c=0;
    for(int l=0;l<total_a_num;l++)
        if (state&(1<<l)) c++;

    return c;
}

int solve(){
    int POW[25]={1};
    int ans=0;
    for (int i=1;i<25;i++) POW[i]=POW[i-1]*2;

    for (int i=0;i<total_a_num;i++) dp[i][POW[i]]=dist_vec[S_index][i];

    for (int state=1;state<POW[total_a_num];state++){
        for (int apple=0;apple<total_a_num;apple++){
            if (dp[apple][state]==0)
                continue;

            if (bit_count(state)==K){
                if (ans==0)
                    ans=dp[apple][state]+dist_vec[apple][E_index];
                else
                    ans = min(dp[apple][state] + dist_vec[apple][E_index],ans);
            }

            for (int loop = 0; loop < total_a_num; loop++)
            {
                if (state & (1 << loop))
                {

                    //Do nothing
                }
                else
                {
                    if (dist_vec[apple][loop]==-1)
                        continue;
                    int next_state = state | POW[loop];
                    int next_dist = dp[apple][state] + dist_vec[apple][loop];

                    if (dp[loop][next_state]==0)
                        dp[loop][next_state] = next_dist;
                    else
                        dp[loop][next_state] = min(dp[loop][next_state], next_dist);
                }
            }
        }
    }

    return ans;
}

int main(){
    //迷宮を初期化
    scanf("%d%d%d\n",&H,&W,&K);
    for (int i=0;i<H;i++) {
        for (int j=0;j<W;j++){
            maze[i][j]=getchar();

            // 座標をX,Yに並ぶ
            coordinate cur_pos = coordinate(j, i);
            if (maze[i][j] == 's')
                S = cur_pos ;

            if (maze[i][j] == 'e')
                E = cur_pos;

            if (maze[i][j] == 'a')
                key_points.push_back(cur_pos);
        }
        getchar();
    }

    init_dist();

    total_a_num=key_points.size();
    S_index=total_a_num;
    E_index=total_a_num+1;
    key_points.push_back(S);
    key_points.push_back(E);

    // for (auto a:key_points)
    //     printf("(%d,%d)\n",a.first,a.second);

    BFS(S_index);

    // for (int i=0;i<total_a_num+2;i++)
    //     printf("%d ",dist_vec[S_index][i]);
    // putchar('\n');

    // for (int i = 0; i < total_a_num + 2; i++)
    //     printf("%d ", dist_vec[i][S_index]);
    // putchar('\n');

    if (!is_possible()){
        puts("-1");
        return 0;
    }

    for (int i=0;i<total_a_num+2;i++)
        if (i!=S_index&&dist_vec[S_index][i]!=-1)
            BFS(i);

    // for (int i=0;i<total_a_num+2;i++){
    //     for(int j=0;j<total_a_num+2;j++)
    //         printf("%d ",dist_vec[i][j]);

    //     putchar('\n');
    // }

    printf("%d\n",solve());

    // 初期化異常無し
    // for (int i = 0; i < H; i++)
    // {
    //     for (int j = 0; j < W; j++)
    //         putchar(maze[i][j]);
    //     putchar('\n');
    // }

    return 0;
}
accuracy: 1
time_ms: 1690
memory_kb: 90672
final_rank: 12

code_snippet: #include <iostream>
#include <stdio.h>
#include <vector>
#include <queue>
#include <utility>
#include <map>
#include <algorithm>

#define dbg(x) cout << #x << " = " << x << endl
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define fs first
#define sn second
#define pb push_back
#define mp make_pair

using namespace std;
using ll = long long;
using pi = pair<int, int>;
using vi = vector<int>;
using vs = vector<string>;

const int INF = 100100100;
const double ESP = 1e-9;

int H, W, K,
dfs[1000][1000],
dist[20][20],
dx[] = { 1,0,-1,0 }, dy[] = { 0,-1,0,1 },
dp[1 << 20][20],
dS[20],
dG[20];
string Map[1002];
vector<pi> ap;
pi	s, g;


int  bit_count (int bits) {
	bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555);
	bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333);
	bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f);
	bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff);
	return (bits & 0x0000ffff) + (bits >> 16 & 0x0000ffff);
}


int main()
{
	auto check = [&](int x, int y) {return 0 <= x && x < H && 0 <= y && y < W && Map[x][y] != '#'; };


	cin >> H >> W >> K;

	rep(i, H) {
		cin >> Map[i];
		rep(j, W) {
			if (Map[i][j] == 'a') ap.pb(mp(i, j));
			if (Map[i][j] == 's') s = mp(i, j);
			if (Map[i][j] == 'e') g = mp(i, j);
		}
	}

	int size = ap.size();

	rep(i, size) {
		rep(i, H) rep(j, W) dfs[i][j] = INF;

		dfs[ap[i].fs][ap[i].sn] = 0;

		queue<pi> q;
		q.push(ap[i]);

		while (q.size()) {
			auto pos = q.front();
			q.pop();

			int x = pos.fs, y = pos.sn;

			rep(t, 4) {
				int nx = x + dx[t], ny = y + dy[t];
				if (check(nx, ny) && dfs[nx][ny] == INF) {
					dfs[nx][ny] = dfs[x][y] + 1;
					q.emplace(nx, ny);
				}
			}
		}
		dS[i] = dfs[s.fs][s.sn];
		dG[i] = dfs[g.fs][g.sn];
		rep(j, size) dist[i][j] = dfs[ap[j].fs][ap[j].sn];
	}

	int M = 1 << size;
	rep(i, M) rep(j, size) dp[i][j] = INF;
	rep(i, size) dp[1 << i][i] = dS[i];
	rep(i, M) {
		rep(j, size) {
			rep(k, size) {
				if (!(i & 1 << k)) {
					dp[i | (1 << k)][k] = min(dp[i | (1 << k)][k], dp[i][j] + dist[j][k]);				
				}
			}
		}
	}

	int ans = INF;
	rep(i, M) {
		if (bit_count(i) >= K) {
			rep(j, size) {
				ans = min(ans, dp[i][j] + dG[j]);
			}
		}
	}
	if (ans >= INF) ans = -1;

	cout << ans << endl;

	return 0;
}
accuracy: 1
time_ms: 920
memory_kb: 89980
final_rank: 2

code_snippet: #include <cstdio>
#include <utility>
#include <queue>
#include <vector>

const int SIZE=1000;
const int APPLE_NUM=20;

using namespace std;

typedef pair<int,int> coordinate;

// 迷宮自体
int H,W,K;
char maze[SIZE][SIZE+1];

// 各ラウンドでアクセスしたか
char maze_visited[SIZE][SIZE][APPLE_NUM+2];

// 林檎と人の位置
int total_a_num,S_index,E_index;
vector<coordinate> key_points;
coordinate S,E;

// 各林檎の間の距離、人を含む
int dist_vec[22][22];



void init_dist(){
    for (int i=0;i<22;i++)
        for (int j=0;j<22;j++)
            dist_vec[i][j]=-1;
}

char get_maze_item(const coordinate& pos){
    return maze[pos.second][pos.first];
}

bool in_maze(const coordinate& pos){
    return pos.first>=0&&pos.first<W&&pos.second>=0&&pos.second<H;
}

bool pos_visited(const coordinate& pos,int i){

    return maze_visited[pos.second][pos.first][i];
}

void explore_pos(const coordinate& pos,int i,queue<coordinate>& Q,queue<int>& dist_Q,int cur_dist){
    if (in_maze(pos) && !pos_visited(pos, i) && get_maze_item(pos)!= '#')
        Q.push(pos),
        maze_visited[pos.second][pos.first][i] = 1, 
        dist_Q.push(cur_dist + 1);
    ;
    ;
}

int find_index(const coordinate& pos){
    for (int i=0;i<key_points.size();i++)
        if (key_points[i]==pos) return i;
}

void BFS(int vert){
    coordinate ini;

    ini=key_points[vert];
    
    queue<coordinate> Q;
    queue<int> dist_Q;
    explore_pos(ini, vert, Q, dist_Q, -1);
    // dist_Q.push(0);
    
    // printf("vert=%d,pos=(%d,%d)\n", vert,ini.second,ini.first);

    while (!Q.empty()){
        //
        const coordinate cur=Q.front();
        const int cur_dist=dist_Q.front();
        Q.pop();
        dist_Q.pop();

        // printf("(%d,%d),dist=%d\n",cur.second,cur.first,cur_dist);

        //todo
        char maze_item=get_maze_item(cur);
        if (maze_item=='a'||maze_item=='e'||maze_item=='s'){
            int index=find_index(cur);
            dist_vec[vert][index]=cur_dist;
            dist_vec[index][vert] = cur_dist;
        }
        

        coordinate left(cur.first-1,cur.second)
        ,right(cur.first+1,cur.second)
        ,up(cur.first,cur.second-1)
        ,down(cur.first,cur.second+1);

        // 左のポジションを探索
        explore_pos(left,vert,Q,dist_Q,cur_dist);
        

        // 左のポジションを探索
        explore_pos(right, vert, Q, dist_Q, cur_dist);

        // 左のポジションを探索
        explore_pos(up, vert, Q,dist_Q, cur_dist);

        // 左のポジションを探索
        explore_pos(down, vert, Q, dist_Q, cur_dist);
    }

}

bool is_possible(){
    if (dist_vec[S_index][E_index]==-1)
        return false;

    int count=0;
    for (int i=0;i<total_a_num;i++)
        if (dist_vec[S_index][i]!=-1) count++;

    return count>=K;
}


int dp[20][1<<20];

int bit_count(int state){
    int c=0;
    for(int l=0;l<total_a_num;l++)
        if (state&(1<<l)) c++;

    return c;
}

int solve(){
    int POW[25]={1};
    int ans=0;
    for (int i=1;i<25;i++) POW[i]=POW[i-1]*2;

    for (int i=0;i<total_a_num;i++) dp[i][POW[i]]=dist_vec[S_index][i];

    for (int state=1;state<POW[total_a_num];state++){
        for (int apple=0;apple<total_a_num;apple++){
            if (dp[apple][state]==0)
                continue;

            if (bit_count(state)==K){
                if (ans==0)
                    ans=dp[apple][state]+dist_vec[apple][E_index];
                else
                    ans = min(dp[apple][state] + dist_vec[apple][E_index],ans);
            }

            for (int loop = 0; loop < total_a_num; loop++)
            {
                if (state & (1 << loop))
                {

                    //Do nothing
                }
                else
                {
                    int next_state = state | POW[loop];
                    int next_dist = dp[apple][state] + dist_vec[apple][loop];

                    if (dp[loop][next_state]==0)
                        dp[loop][next_state] = next_dist;
                    else
                        dp[loop][next_state] = min(dp[loop][next_state], next_dist);
                }
            }
        }
    }

    return ans;
}

int main(){
    //迷宮を初期化
    scanf("%d%d%d\n",&H,&W,&K);
    for (int i=0;i<H;i++) {
        for (int j=0;j<W;j++){
            maze[i][j]=getchar();

            // 座標をX,Yに並ぶ
            coordinate cur_pos = coordinate(j, i);
            if (maze[i][j] == 's')
                S = cur_pos ;

            if (maze[i][j] == 'e')
                E = cur_pos;

            if (maze[i][j] == 'a')
                key_points.push_back(cur_pos);
        }
        getchar();
    }

    init_dist();

    total_a_num=key_points.size();
    S_index=total_a_num;
    E_index=total_a_num+1;
    key_points.push_back(S);
    key_points.push_back(E);

    // for (auto a:key_points)
    //     printf("(%d,%d)\n",a.first,a.second);

    BFS(S_index);

    // for (int i=0;i<total_a_num+2;i++)
    //     printf("%d ",dist_vec[S_index][i]);
    // putchar('\n');

    // for (int i = 0; i < total_a_num + 2; i++)
    //     printf("%d ", dist_vec[i][S_index]);
    // putchar('\n');

    if (!is_possible()){
        puts("-1");
        return 0;
    }

    for (int i=0;i<total_a_num+2;i++)
        if (i!=S_index&&dist_vec[S_index][i]!=-1)
            BFS(i);

    // for (int i=0;i<total_a_num+2;i++){
    //     for(int j=0;j<total_a_num+2;j++)
    //         printf("%d ",dist_vec[i][j]);

    //     putchar('\n');
    // }

    printf("%d\n",solve());

    // 初期化異常無し
    // for (int i = 0; i < H; i++)
    // {
    //     for (int j = 0; j < W; j++)
    //         putchar(maze[i][j]);
    //     putchar('\n');
    // }

    return 0;
}
accuracy: 0.2
time_ms: 150
memory_kb: 18688
final_rank: 20

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 SIZE 1005

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

struct Info{
	Info(int arg_row,int arg_col,int arg_sum_dist){
		row = arg_row;
		col = arg_col;
		sum_dist = arg_sum_dist;
	}
	int row,col,sum_dist;
};

int H,W,K;
int start = 0,goal = 1;
int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0};
int work[SIZE][SIZE];
int min_dist[25][25],POW[25];
int dp[20][1 << 20];
char table[SIZE][SIZE];
LOC loc[25];


bool rangeCheck(int row,int col){

	return row >= 0 && row <= H-1 && col >= 0 && col <= W-1;
}


int main(){

	POW[0] = 1;
	for(int i = 1; i < 25; i++){

		POW[i] = POW[i-1]*2;
	}

	scanf("%d %d %d",&H,&W,&K);

	int index = 2;

	for(int row = 0; row < H; row++){

		scanf("%s",table[row]);
		for(int col = 0; col < W; col++){
			switch(table[row][col]){
			case 's':
				loc[start].set(row,col);
				break;

			case 'e':
				loc[goal].set(row,col);
				break;

			case 'a':
				loc[index].set(row,col);
				index++;
				break;

			default:
				//Do nothing
				break;
			}
		}
	}

	queue<Info> Q;

	for(int start = 0; start < index; start++){

		for(int row = 0; row < H; row++){
			for(int col = 0; col < W; col++){
				work[row][col] = BIG_NUM;
			}
		}

		work[loc[start].row][loc[start].col] = 0;
		Q.push(Info(loc[start].row,loc[start].col,0));

		while(!Q.empty()){

			if(Q.front().sum_dist > work[Q.front().row][Q.front().col]){

				Q.pop();

			}else{

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

					int adj_row = Q.front().row+diff_row[i];
					int adj_col = Q.front().col+diff_col[i];
					int next_dist = Q.front().sum_dist+1;

					if(rangeCheck(adj_row,adj_col) == false || table[adj_row][adj_col] == '#' ||
							work[adj_row][adj_col] <= next_dist)continue;

					work[adj_row][adj_col] = next_dist;
					Q.push(Info(adj_row,adj_col,next_dist));
				}

				Q.pop();
			}
		}

		for(int next = 0; next < index; next++){

			min_dist[start][next] = work[loc[next].row][loc[next].col];
		}
	}

	int ans = BIG_NUM;
	int num_apple = index-2,offset=2;

	for(int i = 0; i < num_apple; i++){
		for(int state = 0; state < POW[num_apple]; state++){
			dp[i][state] = BIG_NUM; //dp[最後のリンゴ][状態] = 最小コスト
		}
	}

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

		dp[i][POW[i]] = min_dist[start][i+offset];
	}

	int tmp;

	for(int state = 1; state < POW[num_apple]; state++){
		for(int i = 0; i < num_apple; i++){
			if(dp[i][state] == BIG_NUM)continue;

			tmp = 0;
			for(int loop = 0; loop < num_apple; loop++){
				if(state & (1 << loop))tmp++;
			}

			if(tmp == K){

				ans = min(ans,dp[i][state]+min_dist[i+offset][goal]);
				continue; //寄り道するのは無駄なので以後遷移は不要
			}

			for(int loop = 0; loop < num_apple; loop++){
				if(state & (1 << loop)){

					//Do nothing

				}else{
					int next_state = state+POW[loop];
					int next_dist = dp[i][state]+min_dist[i+offset][loop+offset];

					dp[loop][next_state] = min(dp[loop][next_state],next_dist);
				}
			}
		}
	}


	if(ans == BIG_NUM){

		printf("-1\n");
	}else{

		printf("%d\n",ans);
	}

	return 0;
}
accuracy: 1
time_ms: 1120
memory_kb: 90116
final_rank: 5

code_snippet: #include <iostream>
#include <vector>
#include <array>
#include <list>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <memory>
#include <cmath>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <numeric>
#include <climits>
#include <cfloat>
#include <cassert>
#include <random>

struct Coordinate {
	int x, y;
	std::vector<Coordinate> neighbors() const {
		return std::vector<Coordinate>{ Coordinate{x + 1, y}, Coordinate{x - 1, y}, Coordinate{x, y + 1}, Coordinate{x, y - 1} };
	}
};
std::vector<std::vector<int>> min_step(const Coordinate start, const std::vector<std::string>& state) {
	auto comparator = [](const std::pair<Coordinate, int>& a, const std::pair<Coordinate, int>& b) {return a.second > b.second; };
	std::priority_queue<std::pair<Coordinate, int>, std::vector<std::pair<Coordinate, int>>, decltype(comparator)> queue(comparator);
	std::vector<std::vector<int>> result(state.size(), std::vector<int>(state.front().size(), INT_MAX));
	queue.emplace(start, 0);
	result[start.y][start.x] = 0;
	while (!queue.empty()) {
		const auto top = queue.top(); queue.pop();
		if (result[top.first.y][top.first.x] == top.second) {
			for (const auto next : top.first.neighbors()) if (0 <= next.y && next.y < result.size() && 0 <= next.x && next.x < result[next.y].size()) {
				if (state[next.y][next.x] != '#' && result[next.y][next.x] > top.second + 1) {
					result[next.y][next.x] = top.second + 1;
					queue.emplace(next, top.second + 1);
				}
			}
		}
	}
	return result;
}
int bit_count(int x) {
	int res = 0;
	while (x > 0) {
		res += x % 2;
		x >>= 1;
	}
	return res;
}
int main() {
	int height, width, k; std::cin >> height >> width >> k;
	std::vector<std::string> state(height); for (auto& line : state) std::cin >> line;
	std::vector<Coordinate> apples; 
	Coordinate e, s;
	for (auto i = 0; i < height; ++i) for (auto j = 0; j < width; ++j) {
		if (state[i][j] == 'e') {
			e = Coordinate{ j, i };
		}
		else if (state[i][j] == 's') {
			s = Coordinate{ j, i };
		}
		else if (state[i][j] == 'a') {
			apples.push_back(Coordinate{ j, i });
		}
	}
	const auto from_start = min_step(e, state);
	const auto to_goal = min_step(s, state);
	apples.erase(std::remove_if(apples.begin(), apples.end(), [&from_start, &to_goal](const Coordinate& c) {return from_start[c.y][c.x] == INT_MAX || to_goal[c.y][c.x] == INT_MAX; }), apples.end());
	std::vector<std::vector<std::vector<int>>> min_steps; std::transform(apples.begin(), apples.end(), std::back_inserter(min_steps), [&state](const Coordinate from) {return min_step(from, state); });
	std::vector<std::vector<int>> min_distance(1 << apples.size(), std::vector<int>(apples.size(), INT_MAX));
	for (auto i = 0; i < apples.size(); ++i) {
		min_distance[1 << i][i] = from_start[apples[i].y][apples[i].x];
	}
	int min = INT_MAX;
	for (auto i = 0; i < min_distance.size(); ++i) {
		if (bit_count(i) >= k) {
			int m = INT_MAX;
			for (auto j = 0; j < apples.size(); ++j) if (min_distance[i][j] != INT_MAX) m = std::min(m, min_distance[i][j] + to_goal[apples[j].y][apples[j].x]);
			min = std::min(min, m);
			continue;
		}
		for (auto j = 0; j < apples.size(); ++j) if (min_distance[i][j] != INT_MAX) {
			for (auto k = 0; k < apples.size(); ++k) if ((i & (1 << k)) == 0 && min_steps[j][apples[k].y][apples[k].x] != INT_MAX) {
				if (min_distance[i | (1 << k)][k] > min_distance[i][j] + min_steps[j][apples[k].y][apples[k].x]) {
					min_distance[i | (1 << k)][k] = min_distance[i][j] + min_steps[j][apples[k].y][apples[k].x];
				}
			}
		}
	}
	std::cout << (min == INT_MAX ? -1 : min) << std::endl;
}
accuracy: 1
time_ms: 2340
memory_kb: 213600
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int i=0;i<(int)(n);++i)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}

using pi = pair<int,int>;

const int INF = 19191919;
const int dx[4]={1,-1,0,0};
const int dy[4]={0,0,1,-1};

int main(){
    int h,w,k;
    cin >>h >>w >>k;
    vector<string> f(h);
    rep(i,h) cin >>f[i];

    vector<pi> a;
    pi start,goal;
    rep(i,h)rep(j,w){
        if(f[i][j]=='a') a.pb({i,j});
        if(f[i][j]=='s') start = {i,j};
        if(f[i][j]=='e') goal = {i,j};
    }
    int A = a.size();

    auto IN = [&](int y, int x){
        return 0<=y && y<h && 0<=x && x<w;
    };

    auto BFS = [&](pi s){
        vector<vector<int>> d(h,vector<int>(w,INF));
        d[s.fi][s.se] = 0;
        queue<pi> que({s});
        while(!que.empty()){
            pi now = que.front();
            que.pop();
            rep(i,4){
                int ny = now.fi+dy[i], nx = now.se+dx[i];
                if(IN(ny,nx) && f[ny][nx]!='#' && d[ny][nx] > d[now.fi][now.se]+1){
                    d[ny][nx] = d[now.fi][now.se]+1;
                    que.push({ny,nx});
                }
            }
        }
        return d;
    };

    vector<vector<int>> ds = BFS(start), dg = BFS(goal);

    vector<vector<int>> da(A, vector<int>(A,INF));
    rep(i,A){
        vector<vector<int>> d = BFS(a[i]);
        rep(j,A) da[i][j] = d[a[j].fi][a[j].se];
    }

    vector<vector<int>> dp(1<<A,vector<int>(A,INF));
    rep(i,A) dp[1<<i][i] = ds[a[i].fi][a[i].se];

    rep(mask,1<<A)rep(i,A)if(mask>>i&1){
        rep(j,A)if(!(mask>>j&1)){
            int nx = mask|(1<<j);
            dp[nx][j] = min(dp[nx][j], dp[mask][i]+da[i][j]);
        }
    }

    int ans = INF;
    rep(mask,1<<A)rep(i,A)if((mask>>i&1) && __builtin_popcount(mask)>=k){
        int t = dp[mask][i];
        t += dg[a[i].fi][a[i].se];
        ans = min(ans, t);
    }

    if(ans == INF) ans = -1;
    cout << ans << "\n";
    return 0;
}
accuracy: 1
time_ms: 1180
memory_kb: 134764
final_rank: 9

code_snippet: #include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <utility>
#include <queue>
#define inf 1e9

using namespace std;
typedef pair<int, int> P;

int h, w, k;
char c[1005][1005];
int px[25], py[25];
int d[1005][1005];
int dist[25][25];
int dp[1<<20][20];
int pop[1<<20];
const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};

void bfs(int sx, int sy)
{
	for(int y = 1; y <= h; y++){
		for(int x = 1; x <= w; x++){
			d[x][y] = inf;
		}
	}
	d[sx][sy] = 0;
	
	queue<P> Q;
	Q.push(P(sx, sy));
	
	while(Q.size()){
		int x = Q.front().first, y = Q.front().second;
		Q.pop();
		for(int i = 0; i < 4; i++){
			int nx = x + dx[i], ny = y + dy[i];
			if(nx < 1 || nx > w || ny < 1 || ny > h) continue;
			if(d[nx][ny] < inf) continue;
			if(c[nx][ny] == '#') continue;
			d[nx][ny] = d[x][y] + 1;
			Q.push(P(nx, ny));
		}
	}
}

int main(void)
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	cin >> h >> w >> k;
	int m = 0;
	for(int y = 1; y <= h; y++){
		for(int x = 1; x <= w; x++){
			cin >> c[x][y];
			if(c[x][y] == 'a') px[m] = x, py[m] = y, m++;
		}
	}
	for(int y = 1; y <= h; y++){
		for(int x = 1; x <= w; x++){
			if(c[x][y] == 's') px[m] = x, py[m] = y;
			if(c[x][y] == 'e') px[m+1] = x, py[m+1] = y;
		}
	}
	
	for(int i = 0; i <= m+1; i++){
		bfs(px[i], py[i]);
		for(int j = 0; j <= m+1; j++) dist[i][j] = d[px[j]][py[j]];
	}
	
	int M = 1<<m;
	for(int i = 0; i < M; i++){
		for(int j = 0; j < m; j++){
			dp[i][j] = inf;
		}
	}
	for(int i = 0; i < m; i++) dp[1<<i][i] = dist[m][i];
	for(int i = 0; i < M; i++){
		for(int j = 0; j < m; j++){
			for(int k = 0; k < m; k++){
				if(i & (1<<k)) continue;
				dp[i|(1<<k)][k] = min(dp[i|(1<<k)][k], dp[i][j] + dist[j][k]);
			}
		}
	}
	
	for(int i = 1; i < M; i++) pop[i] = pop[i&(i-1)] + 1;
	int ans = inf;
	for(int i = 0; i < M; i++){
		if(pop[i] < k) continue;
		for(int j = 0; j < m; j++){
			ans = min(ans, dp[i][j] + dist[j][m+1]);
		}
	}
	if(ans > inf/2) cout << -1 << endl;
	else cout << ans << endl;
	
	return 0;
}
accuracy: 1
time_ms: 1020
memory_kb: 94088
final_rank: 3

code_snippet: #include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include <utility>
#include <queue>
#define inf 1e9

using namespace std;
typedef pair<int, int> P;

int h, w, k;
char c[1005][1005];
int px[25], py[25];
int d[1005][1005];
int dist[25][25];
int dp[1<<20][20];
int pop[1<<20];
const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};

void bfs(int sx, int sy)
{
	for(int y = 1; y <= h; y++){
		for(int x = 1; x <= w; x++){
			d[x][y] = inf;
		}
	}
	d[sx][sy] = 0;
	
	queue<P> Q;
	Q.push(P(sx, sy));
	
	while(Q.size()){
		int x = Q.front().first, y = Q.front().second;
		Q.pop();
		for(int i = 0; i < 4; i++){
			int nx = x + dx[i], ny = y + dy[i];
			if(nx < 1 || nx > w || ny < 1 || ny > h) continue;
			if(d[nx][ny] < inf) continue;
			if(c[nx][ny] == '#') continue;
			d[nx][ny] = d[x][y] + 1;
			Q.push(P(nx, ny));
		}
	}
}

int main(void)
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	cin >> h >> w >> k;
	int m = 0;
	for(int y = 1; y <= h; y++){
		for(int x = 1; x <= w; x++){
			cin >> c[x][y];
			if(c[x][y] == 'a') px[m] = x, py[m] = y, m++;
		}
	}
	for(int y = 1; y <= h; y++){
		for(int x = 1; x <= w; x++){
			if(c[x][y] == 's') px[m] = x, py[m] = y;
			if(c[x][y] == 'e') px[m+1] = x, py[m+1] = y;
		}
	}
	
	for(int i = 0; i <= m+1; i++){
		bfs(px[i], py[i]);
		for(int j = 0; j <= m+1; j++) dist[i][j] = d[px[j]][py[j]];
	}
	
	int M = 1<<m;
	for(int i = 0; i < M; i++){
		for(int j = 0; j < m; j++){
			dp[i][j] = inf;
		}
	}
	for(int i = 0; i < m; i++) dp[1<<i][i] = dist[m][i];
	for(int i = 0; i < M; i++){
		for(int j = 0; j < m; j++){
			for(int k = 0; k < m; k++){
				if(j & (1<<k)) continue;
				dp[i|(1<<k)][k] = min(dp[i|(1<<k)][k], dp[i][j] + dist[j][k]);
			}
		}
	}
	
	for(int i = 1; i < M; i++) pop[i] = pop[i&(i-1)] + 1;
	int ans = inf;
	for(int i = 0; i < M; i++){
		if(pop[i] < k) continue;
		for(int j = 0; j < m; j++){
			ans = min(ans, dp[i][j] + dist[j][m+1]);
		}
	}
	if(ans > inf/2) cout << -1 << endl;
	else cout << ans << endl;
	
	return 0;
}
accuracy: 0.26666666666666666
time_ms: 680
memory_kb: 91508
final_rank: 19

code_snippet: //
// Created by yamunaku on 2019/12/29.
//

#include <bits/stdc++.h>

using namespace std;

#define rep(i, n) for(int i = 0; i < (n); i++)
#define repl(i, l, r) for(int i = (l); i < (r); i++)
#define per(i, n) for(int i = ((n)-1); i >= 0; i--)
#define perl(i, l, r) for(int i = ((r)-1); i >= (l); i--)
#define all(x) (x).begin(),(x).end()
#define MOD9 998244353
#define MOD1 1000000007
#define IINF 1000000000
#define LINF 1000000000000000000
#define SP <<" "<<
#define CYES cout<<"Yes"<<endl
#define CNO cout<<"No"<<endl
#define CFS cin.tie(0);ios::sync_with_stdio(false)
#define CST(x) cout<<fixed<<setprecision(x)

using ll = long long;
using ld = long double;
using vi = vector<int>;
using mti = vector<vector<int>>;
using vl = vector<ll>;
using mtl = vector<vector<ll>>;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
template<typename T>
using heap = priority_queue<T, vector<T>, function<bool(const T, const T)>>;

struct pos{
    int x;
    int y;
};

struct sta{
    int f;
    int l;
    int d;
};

int main(){
    // CFS;
    int h, w, K;
    cin >> h >> w >> K;
    vector<string> f(h);
    rep(i, h) cin >> f[i];
    vector<pos> app;
    rep(i, h){
        rep(j, w){
            if(f[i][j] == 'a'){
                app.push_back({i, j});
                f[i][j] = '.';
            }

        }
    }
    rep(i, h){
        rep(j, w){
            if(f[i][j] == 's' || f[i][j] == 'e'){
                app.push_back({i, j});
                f[i][j] = '.';
            }
        }
    }

    int sz = app.size();
    mti dist(sz, vi(sz, IINF));
    vi vx = {0, 1, 0, -1};
    vi vy = {1, 0, -1, 0};
    rep(i, sz){
        queue<pos> q;
        mti dis(h, vi(w, IINF));
        q.push({app[i].x, app[i].y});
        dis[app[i].x][app[i].y] = 0;
        while(!q.empty()){
            auto now = q.front();
            q.pop();
            rep(t, 4){
                int nx = now.x + vx[t];
                int ny = now.y + vy[t];
                if(nx < 0 || h <= nx || ny < 0 || w <= ny) continue;
                if(f[nx][ny] == '#') continue;
                if(dis[nx][ny] != IINF) continue;
                dis[nx][ny] = dis[now.x][now.y] + 1;
                q.push({nx, ny});
            }
        }
        rep(j, sz){
            dist[i][j] = dis[app[j].x][app[j].y];
        }
    }

//    rep(i, sz){
//        rep(j, sz){
//            cout << dist[i][j] << " ";
//        }
//        cout << endl;
//    }
    int ans = IINF;

    mti d(1 << sz, vi(sz, IINF));
    d[1 << (sz - 2)][sz - 2] = 0;
    rep(i, 1 << sz){
        rep(j, sz){
            if(d[i][j] == IINF) continue;
            rep(k, sz){
                if(dist[j][k] != IINF && (i&(1<<k))==0)
                    d[i | (1 << k)][k] = min(d[i | (1 << k)][k], d[i][j] + dist[j][k]);
            }
        }
        int c = 0;
        rep(k, sz){
            if(i & (1 << k)) c++;
        }
        if(c >= K + 2){
            ans = min(ans, d[i][sz - 1]);
        }
    }
    if(ans == IINF) cout << -1 << endl;
    else cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 2070
memory_kb: 495472
final_rank: 17

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

int nth_bit(int64_t num, int n){
    return (num >> n) & 1;
}

int pop_count(int bits){
    bits = (bits & 0x55555555) + (bits >> 1 & 0x55555555);
    bits = (bits & 0x33333333) + (bits >> 2 & 0x33333333);
    bits = (bits & 0x0f0f0f0f) + (bits >> 4 & 0x0f0f0f0f);
    bits = (bits & 0x00ff00ff) + (bits >> 8 & 0x00ff00ff);
    return (bits & 0x0000ffff) + (bits >>16 & 0x0000ffff);
}

void chmin(int64_t& a, int64_t b){
    a = min(a, b);
}

int main(){
    int H, W, K;
    cin >> H >> W >> K;
    string S[1000];
    vector<pair<int, int>> pos;
    pair<int, int> ps, pg;
    for(int i=0; i<H; i++){
        cin >> S[i];
        for(int j=0; j<W; j++){
            if(S[i][j] == 's') ps = {i, j};
            if(S[i][j] == 'e') pg = {i, j};
            if(S[i][j] == 'a') pos.emplace_back(i, j);
        }
    }
    int KK = pos.size();

    const int64_t INF = 1e15;
    int64_t dist[20][20], grid_dist[1000][1000], toS[20], toG[20];
    const int dx[] = {-1, 1, 0, 0};
    const int dy[] = {0, 0, -1, 1};
    auto inside = [&](int i, int j){ return 0<=i && i<H && 0<=j && j<W && S[i][j] != '#'; };

    for(int k=0; k<KK; k++){
        for(int i=0; i<H; i++) for(int j=0; j<W; j++) grid_dist[i][j] = INF;
        queue<pair<int, int>> que;
        grid_dist[pos[k].first][pos[k].second] = 0;
        que.push(pos[k]);
        while(que.size()){
            auto p = que.front(); que.pop();
            int i = p.first, j = p.second;
            for(int t=0; t<4; t++){
                int x = i + dx[t], y = j + dy[t];
                if(inside(x, y) && grid_dist[x][y] == INF){
                    grid_dist[x][y] = grid_dist[i][j] + 1;
                    que.emplace(x, y);
                }
            }
        }
        toS[k] = grid_dist[ps.first][ps.second];
        toG[k] = grid_dist[pg.first][pg.second];
        for(int l=0; l<KK; l++) dist[k][l] = grid_dist[pos[l].first][pos[l].second];
    }

    static int64_t dp[1<<20][20];
    for(int i=0; i<(1<<KK); i++) for(int k=0; k<KK; k++) dp[i][k] = INF;
    for(int k=0; k<KK; k++) dp[1<<k][k] = toS[k];
    for(int i=0; i<(1<<KK); i++) for(int k=0; k<KK; k++) for(int t=0; t<KK; t++) if(!nth_bit(i, t)){
        chmin(dp[i+(1<<t)][t], dp[i][k] + dist[k][t]);
    }

    int64_t ans = INF;
    for(int i=0; i<(1<<KK); i++) if(pop_count(i) >= K) for(int k=0; k<KK; k++) chmin(ans, dp[i][k] + toG[k]);
    if(ans >= INF) ans = -1;
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 1050
memory_kb: 175748
final_rank: 11

code_snippet: #include<iostream>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;

#define inRange(x,a,b) (a <= x && x < b)
int di[8] = {0,0,1,-1,1,1,-1,-1};
int dj[8] = {1,-1,0,0,1,-1,1,-1};

int dist[22][22];
int dp[22][1<<22];
int bfs[1000][1000];
int cnt = 0;

int dec(char c){
    if(c == 's')    return 0;
    if(c == 'e')    return cnt+1;
    return c-'A'+1;
}

int main(){
    memset(dist, 0x3f, sizeof(dist));
    memset(dp, 0x3f, sizeof(dp));
    int h, w, k;
    cin >> h >> w >> k;
    char mat[h][w];
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            cin >> mat[i][j];
            if(mat[i][j] == 'a'){
                mat[i][j] = (char)('A' + cnt++);
            }
        }
    }
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            if(mat[i][j] == '#' || mat[i][j] == '.')    continue;
            int ind = dec(mat[i][j]);
            memset(bfs, 0x3f, sizeof(bfs));
            bfs[i][j] = 0;
            queue<int> q;
            q.push(i*w+j);
            while(!q.empty()){
                int x = q.front();  q.pop();
                int i = x/w, j = x%w;
                if(mat[i][j] != '.'){
                    dist[ind][dec(mat[i][j])] = bfs[i][j];
                }
                for(int k = 0; k < 4; k++){
                    int ni = i+di[k], nj = j+dj[k];
                    if(inRange(ni,0,h)&&inRange(nj,0,w)&&bfs[ni][nj]>bfs[i][j]+1&&mat[ni][nj]!='#'){
                        bfs[ni][nj] = bfs[i][j]+1;
                        q.push(ni*w+nj);
                    }
                }
            }
        }
    }
    dp[0][1] = 0;
    for(int s = 1; s < 1<<(cnt+1); s++){
        for(int i = 0; i < cnt+1; i++){
            if(((s>>i)&1) == 0) continue;
            if(dp[i][s] > 1e9)  continue;
            for(int j = 0; j < cnt+1; j++){
                if((s>>j)&1)   continue;
                if(dist[i][j] > 1e9)    continue;
                dp[j][s|(1<<j)] = min(dp[j][s|(1<<j)], dp[i][s]+dist[i][j]);
            }
        }
    }
    int ret = 2e9;
    for(int s = 1; s < 1<<(cnt+1); s++){
        int pop = -1;
        for(int j = 0; j < cnt+1; j++)  pop += (s>>j)&1;
        if(pop < k) continue;
        for(int j = 1; j <= cnt; j++){
            if(dist[j][cnt+1] < 1e9 && dp[j][s] < 1e9)  ret = min(ret, dp[j][s]+dist[j][cnt+1]);
        }
    }
    cout << (ret >= 2e9 ? -1 : ret) << endl;
    return 0;
}
accuracy: 1
time_ms: 1250
memory_kb: 368484
final_rank: 15

code_snippet: #include<iostream>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;

#define inRange(x,a,b) (a <= x && x < b)
int di[8] = {0,0,1,-1,1,1,-1,-1};
int dj[8] = {1,-1,0,0,1,-1,1,-1};

int dist[22][22];
int dp[22][1<<22];
int bfs[1000][1000];
int cnt = 0;

int dec(char c){
    if(c == 's')    return 0;
    if(c == 'e')    return cnt+1;
    return c-'A'+1;
}

int main(){
    memset(dist, 0x3f, sizeof(dist));
    memset(dp, 0x3f, sizeof(dp));
    int h, w, k;
    cin >> h >> w >> k;
    char mat[h][w];
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            cin >> mat[i][j];
            if(mat[i][j] == 'a'){
                mat[i][j] = (char)('A' + cnt++);
            }
        }
    }
    for(int i = 0; i < h; i++){
        for(int j = 0; j < w; j++){
            if(mat[i][j] == '#' || mat[i][j] == '.')    continue;
            int ind = dec(mat[i][j]);
            memset(bfs, 0x3f, sizeof(bfs));
            bfs[i][j] = 0;
            queue<int> q;
            q.push(i*w+j);
            while(!q.empty()){
                int x = q.front();  q.pop();
                int i = x/w, j = x%w;
                if(mat[i][j] != '.'){
                    dist[ind][dec(mat[i][j])] = bfs[i][j];
                }
                for(int k = 0; k < 4; k++){
                    int ni = i+di[k], nj = j+dj[k];
                    if(inRange(ni,0,h)&&inRange(nj,0,w)&&bfs[ni][nj]>bfs[i][j]+1&&mat[ni][nj]!='#'){
                        bfs[ni][nj] = bfs[i][j]+1;
                        q.push(ni*w+nj);
                    }
                }
            }
        }
    }
    dp[0][1] = 0;
    for(int s = 1; s < 1<<(cnt+1); s++){
        for(int i = 0; i < cnt+1; i++){
            if(((s>>i)&1) == 0) continue;
            if(dp[i][s] > 1e9)  continue;
            for(int j = 0; j < cnt+1; j++){
                if((s>>j)&1)   continue;
                if(dist[i][j] > 1e9)    continue;
                dp[j][s|(1<<j)] = min(dp[j][s|(1<<j)], dp[i][s]+dist[i][j]);
            }
        }
    }
    int ret = 2e9;
    for(int s = 1; s < 1<<(cnt+1); s++){
        int pop = -1;
        for(int j = 0; j < cnt+1; j++)  pop += (s>>j)&1;
        if(pop < k) continue;
        for(int j = 1; j <= cnt; j++){
            if(dist[j][cnt+1] < 1e9)    ret = min(ret, dp[j][s]+dist[j][cnt+1]);
        }
    }
    cout << (ret >= 2e9 ? -1 : ret) << endl;
    return 0;
}
accuracy: 0.3333333333333333
time_ms: 530
memory_kb: 368404
final_rank: 18

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
int H,W,K;
string s[1000];
int X[22],Y[22];
long dis[22][22];
int D[5]={0,1,0,-1,0};
long dp[1<<20][20];
main()
{
	cin>>H>>W>>K;
	int id=2;
	for(int i=0;i<H;i++)
	{
		cin>>s[i];
		for(int j=0;j<W;j++)
		{
			if(s[i][j]=='s')
			{
				X[0]=i;
				Y[0]=j;
			}
			else if(s[i][j]=='e')
			{
				X[1]=i;
				Y[1]=j;
			}
			else if(s[i][j]=='a')
			{
				X[id]=i;
				Y[id++]=j;
			}
		}
	}
	for(int i=0;i<id;i++)
	{
		vector<vector<int> >d(H,vector<int>(W,1e9));
		d[X[i]][Y[i]]=0;
		queue<pair<int,int> >P;
		P.push(make_pair(X[i],Y[i]));
		while(!P.empty())
		{
			int x=P.front().first,y=P.front().second;
			P.pop();
			for(int r=0;r<4;r++)
			{
				int tx=x+D[r],ty=y+D[r+1];
				if(0<=tx&&tx<H&&0<=ty&&ty<W&&s[tx][ty]!='#'&&d[tx][ty]>d[x][y]+1)
				{
					d[tx][ty]=d[x][y]+1;
					P.push(make_pair(tx,ty));
				}
			}
		}
		for(int j=0;j<id;j++)
		{
			dis[i][j]=d[X[j]][Y[j]];
		}
	}
	int sz=id-2;
	for(int i=0;i<1<<sz;i++)for(int j=0;j<sz;j++)dp[i][j]=1e18;
	for(int i=2;i<id;i++)
	{
		dp[1<<i-2][i-2]=dis[0][i];
	}
	for(int i=1;i<1<<sz;i++)
	{
		for(int j=0;j<sz;j++)
		{
			if(dp[i][j]>1e17)continue;
			for(int k=0;k<sz;k++)
			{
				if(i>>k&1)continue;
				dp[i|1<<k][k]=min(dp[i|1<<k][k],dp[i][j]+dis[j+2][k+2]);
			}
		}
	}
	long ans=1e18;
	for(int i=0;i<1<<sz;i++)
	{
		if(__builtin_popcount(i)<K)continue;
		for(int j=0;j<sz;j++)ans=min(ans,dp[i][j]+dis[j+2][1]);
	}
	cout<<(ans>1e9?-1:ans)<<endl;
}
accuracy: 1
time_ms: 1030
memory_kb: 168048
final_rank: 10

code_snippet: #include <bits/stdc++.h>
 
//    #include <boost/multiprecision/cpp_int.hpp>
// #define int long long
 #define inf  1000000007
 #define pa pair<int,int>
 #define ll long long
 #define pal pair<double,double>
 #define ppap pair<pa,int>
  #define PI 3.14159265358979323846
  #define paa pair<int,char>
  #define  mp make_pair
  #define  pb push_back
  #define EPS (1e-8)
                                          
    int dx[8]={0,1,0,-1,1,1,-1,-1};
    int dy[8]={1,0,-1,0,-1,1,1,-1};
                                            using namespace std;
                                   			class pa3{
                                            	public:
                                            	int x;
                                   				int y,z;
                                            	pa3(int x=0,int y=0,int z=0):x(x),y(y),z(z) {}
                                            	bool operator < (const pa3 &p) const{
                                            		if(x!=p.x) return x<p.x;
                                            		if(y!=p.y) return y<p.y;
                                            		 return z<p.z;
                                            		//return x != p.x ? x<p.x: y<p.y;
                                            	}
                                   				bool operator > (const pa3 &p) const{
                                            		if(x!=p.x) return x>p.x;
                                            		if(y!=p.y) return y>p.y;
                                            		 return z>p.z;
                                            		//return x != p.x ? x<p.x: y<p.y;
                                            	}
                                            	bool operator == (const pa3 &p) const{
                                            		return x==p.x && y==p.y && z==p.z;
                                            	}
                                            		bool operator != (const pa3 &p) const{
                                            			return !( x==p.x && y==p.y && z==p.z);
                                            	}
                                            
                                            };
                                            
                                            class pa4{
                                            	public:
                                            	int x;
                                            	int y,z,w;
                                            	pa4(int x=0,int y=0,int z=0,int w=0):x(x),y(y),z(z),w(w) {}
                                            	bool operator < (const pa4 &p) const{
                                            		if(x!=p.x) return x<p.x;
                                            		if(y!=p.y) return y<p.y;
                                            		if(z!=p.z)return z<p.z;
                                            		return w<p.w;
                                            		//return x != p.x ? x<p.x: y<p.y;
                                            	}
                                            	bool operator > (const pa4 &p) const{
                                            		if(x!=p.x) return x>p.x;
                                            		if(y!=p.y) return y>p.y;
                                            		if(z!=p.z)return z>p.z;
                                            		return w>p.w;
                                            		//return x != p.x ? x<p.x: y<p.y;
                                            	}
                                            	bool operator == (const pa4 &p) const{
                                            		return x==p.x && y==p.y && z==p.z &&w==p.w;
                                            	}
                                            		
                                            
                                            };
                                            class pa2{
                                            	public:
                                            	int x,y;
                                            	pa2(int x=0,int y=0):x(x),y(y) {}
                                            	pa2 operator + (pa2 p) {return pa2(x+p.x,y+p.y);}
                                            	pa2 operator - (pa2 p) {return pa2(x-p.x,y-p.y);}
                                            	bool operator < (const pa2 &p) const{
                                            		return y != p.y ? y<p.y: x<p.x;
                                            	}
                                            	bool operator > (const pa2 &p) const{
                                            		return x != p.x ? x<p.x: y<p.y;
                                            	}
                                            	bool operator == (const pa2 &p) const{
                                            		return abs(x-p.x)==0 && abs(y-p.y)==0;
                                            	}
                                            	bool operator != (const pa2 &p) const{
                                            		return !(abs(x-p.x)==0 && abs(y-p.y)==0);
                                            	}
                                            		
                                            
                                            };
                                            
 
                      
                                string itos( int i ) {
                                ostringstream s ;
                                s << i ;
                                return s.str() ;
                                }
                                 
                                int gcd(int v,int b){
                                	if(v==0) return b;
                                	if(b==0) return v;
                                	if(v>b) return gcd(b,v);
                                	if(v==b) return b;
                                	if(b%v==0) return v;
                                	return gcd(v,b%v);
                                }
                 
                            
                                int mod;
int extgcd(int a, int b, int &x, int &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    int d = extgcd(b, a%b, y, x);
    y -= a/b * x;
    return d;
}
pa operator+(const pa & l,const pa & r) {   
    return {l.first+r.first,l.second+r.second};                                    
}    
pa operator-(const pa & l,const pa & r) {   
    return {l.first-r.first,l.second-r.second};                                    
}  
                                
                int pr[10000100];
                int inv[10000010];
                
                int beki(int wa,int rr,int warukazu){
                	if(rr==0) return 1%warukazu;
                	if(rr==1) return wa%warukazu;
                	wa%=warukazu;
                	if(rr%2==1) return ((ll)beki(wa,rr-1,warukazu)*(ll)wa)%warukazu;
                	ll zx=beki(wa,rr/2,warukazu);
                	return (zx*zx)%warukazu;
                }
 
                
    			int comb(int nn,int rr){
    				if(rr<0 || rr>nn || nn<0) return 0;
    				int r=pr[nn]*inv[rr];
    				r%=mod;
    				r*=inv[nn-rr];
    				r%=mod;
    				return r;
    			}
               
                void gya(int ert){
                	pr[0]=1;
                	for(int i=1;i<=ert;i++){
                		pr[i]=((ll)pr[i-1]*i)%mod;
                	}
                		inv[ert]=beki(pr[ert],mod-2,mod);
                	for(int i=ert-1;i>=0;i--){
                		inv[i]=(ll)inv[i+1]*(i+1)%mod;
                	}
                }
                
              //   cin.tie(0);
    		//	ios::sync_with_stdio(false);
    			//priority_queue<pa3,vector<pa3>,greater<pa3>> pq;            
                 //sort(ve.begin(),ve.end(),greater<int>());
 //   mt19937(clock_per_sec);
  //  mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()) ;


string s[1020];
map<pa,int> ma;

int dis[22][22]={};
bool vis[1020][1020];
bool sumi[22][1<<22]={};
int dp[1<<20][20];
signed main(){
	
	
cin.tie(0);
ios::sync_with_stdio(false);

	int h,w,k;
	cin>>h>>w>>k;
	int n=0,sx,sy,ex,ey;
	vector<pa> ve;
	for(int i=0;i<h;i++){
		cin>>s[i];
		for(int j=0;j<w;j++){
			char c=s[i][j];
			n+=c=='a';
			if(c=='a'){
				ve.pb(mp(i,j));
			}
			if(c=='s'){
				sx=i,sy=j;
			}
			if(c=='e'){
				ex=i,ey=j;
			}
		}
	}
	ve.pb(mp(sx,sy));
	ve.pb(mp(ex,ey));
	for(int i=0;i<n+2;i++)ma[ve[i]]=i;
	for(int i=0;i<n+2;i++)for(int j=0;j<n+2;j++)dis[i][j]=inf;
	for(int i=0;i<n+2;i++){
		queue<pa3> qu;
		qu.push(pa3(ve[i].first,ve[i].second,0));
		for(int i=0;i<h;i++)for(int j=0;j<w;j++)vis[i][j]=0;
		while(qu.size()){
			pa3 z=qu.front();
			qu.pop();
			if(vis[z.x][z.y])continue;
			vis[z.x][z.y]=1;
			if(s[z.x][z.y]!='.'){
				dis[i][ma[mp(z.x,z.y)]]=z.z;
		//		cout<<i<<" "<<ma[mp(z.x,z.y)]<<"  "<<z.z<<endl;
			}
			for(int r=0;r<4;r++){
				int x=z.x+dx[r];
				int y=z.y+dy[r];
				if(x<0||y<0 || x>=h || y>=w)continue;
				if(s[x][y]=='#')continue;
					if(!vis[x][y])qu.push((pa3){x,y,z.z+1});
			}
		}
	}
	int ans=inf;
	for(int i=1;i<(1<<n);i++){
		
		for(int j=0;j<n;j++)if(i&(1<<j)){
		if(i==(i&(-i))){
			dp[i][j]=dis[j][n];
		//	continue;
		}
		else{
				dp[i][j]=inf;
				for(int h=0;h<n;h++)if(i&(1<<h))if(h!=j)if(dis[j][h]<inf){
					dp[i][j]=min(dp[i][j],dp[i^(1<<j)][h]+dis[j][h]);
				}
			}
		
		if(__builtin_popcount(i)>=k && dis[j][n+1]<inf)ans=min(ans,dis[j][n+1]+dp[i][j]);
	}}
	
	if(ans==inf)cout<<-1<<endl;
else	cout<<ans<<endl;
	
	/*
	priority_queue<pa3,vector<pa3>,greater<pa3>> pq;     
	pq.push(pa3(0,n,0));
	
	while(pq.size()){
		pa3 z=pq.top();
		pq.pop();
		if(sumi[z.y][z.z])continue;
		sumi[z.y][z.z]=1;
	//	cout<<z.y<<" "<<z.z<<" "<<z.x<<endl;
		if(z.y==n+1){
			if(__builtin_popcount(z.z)>=k){
				cout<<z.x<<endl;
				return 0;
			}
		}
		for(int i=0;i<n;i++)if(dis[z.y][i]<inf){
			if(0==(z.z&(1<<i)))	pq.push((pa3){z.x+dis[z.y][i],i,(z.z|(1<<i))&((1<<n)-1)});
		}
		
		for(int i=n+1;i<n+2;i++)if(dis[z.y][i]<inf)if(__builtin_popcount(z.z)>=k){
			pq.push((pa3){z.x+dis[z.y][i],i,z.z});
		}

	}
cout<<-1<<endl;
	*/
	return 0; 
 }
accuracy: 1
time_ms: 1070
memory_kb: 87092
final_rank: 4

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

using namespace std;

using i64 = long long;

const i64 MOD = 1e9+7;

const i64 INF = 1e18+7;


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

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


signed main(){

    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(20);

    int h, w, k;
    cin >> h >> w >> k;
    vector<string> s(h);
    for(auto& x : s)
        cin >> x;

    int sx, sy, ex, ey;
    int cnt = 0;
    vector<int> x, y;
    for(int i = 0; i < h; ++i)
        for(int j = 0; j < w; ++j){
            if(s[i][j] == 's'){
                sx = i;
                sy = j;
            }
            if(s[i][j] == 'e'){
                ex = i;
                ey = j;
            }
            if(s[i][j] == 'a'){
                ++cnt;
                x.emplace_back(i);
                y.emplace_back(j);
            }
        }

    x.emplace_back(sx);
    x.emplace_back(ex);
    y.emplace_back(sy);
    y.emplace_back(ey);

    vector<int> dx{1, 0, -1, 0};
    vector<int> dy{0, 1, 0, -1};

    vector<vector<int>> graph(cnt + 2, vector<int>(cnt + 2, MOD));
    for(int i = 0; i < cnt + 2; ++i){
        queue<pair<int,int>> que;
        vector<vector<int>> range(h, vector<int>(w, MOD));
        range[x[i]][y[i]] = 0;
        que.emplace(x[i], y[i]);
        while(!que.empty()){
            int x, y;
            tie(x, y) = que.front();
            que.pop();
            for(int d = 0; d < 4; ++d){
                int nx = x + dx[d];
                int ny = y + dy[d];
                if(nx < 0 || ny < 0 || nx >= h || ny >= w || s[nx][ny] == '#')
                    continue;
                if(chmin(range[nx][ny], range[x][y] + 1))
                    que.emplace(nx, ny);
            }
        }
        for(int j = 0; j < cnt + 2; ++j)
            graph[i][j] = range[x[j]][y[j]];
    }

    vector<vector<i64>> dp(1 << cnt, vector<i64>(cnt, INF));
    for(int i = 0; i < cnt; ++i)
        dp[(1 << i)][i] = graph[cnt][i];

    for(int i = 0; i < (1 << cnt); ++i){
        for(int j = 0; j < cnt; ++j){
            for(int k = 0; k < cnt; ++k){
                chmin(dp[i | (1 << k)][k], dp[i][j] + graph[j][k]);
            }
        }
    }

    i64 ans = INF;
    for(int i = 0; i < (1 << cnt); ++i){
        int cn = __builtin_popcount(i);
        if(cn >= k){
            for(int j = 0; j < cnt; ++j){
                chmin(ans, dp[i][j] + graph[j][cnt + 1]);
            }
        }
    }
    if(ans >= 1e7){
        cout << -1 << endl;
        return 0;
    }
    cout << ans << endl;
}
accuracy: 1
time_ms: 1320
memory_kb: 208740
final_rank: 13

code_snippet: #include <bits/stdc++.h>
#define FOR(i,a,n) for(ll i=(ll)a;i<(ll)n;i++)
#define rep(i,n) FOR(i,0,n)
using namespace std;
typedef long long ll;
const int X[]={0,1,0,-1},Y[]={1,0,-1,0};

int H,W,K,eh,ew,apple,d[30][30],bfs[1001][1001],dp[1<<20][30];
char A[1000][1000];
vector<int>x(1),y(1);

int bitdp(int app,int last){
    if(dp[app][last])return dp[app][last];
    int num=0;
    rep(i,apple)if((app>>i)&1)num++;
    if(num==K)return dp[app][last]=d[last][x.size()-1];
    dp[app][last]=1e7;
    rep(i,apple)if(!((app>>i)&1)){
        dp[app][last]=min(dp[app][last],bitdp(app+(1<<i),i+1)+d[last][i+1]);
    }
    return dp[app][last];
}

int main(){
    cin>>H>>W>>K;
    rep(i,H)rep(j,W){
        cin>>A[i][j];
        if(A[i][j]=='e')eh=i,ew=j;
        if(A[i][j]=='s')x[0]=i,y[0]=j;
        if(A[i][j]=='a'){
            x.push_back(i);
            y.push_back(j);
            apple++;
        }
    }
    x.push_back(eh);
    y.push_back(ew);

    queue<pair<int,int> > que;
    rep(i,x.size()){
        fill(bfs[0],bfs[1001],1e7);
        que.push({x[i],y[i]});
        bfs[x[i]][y[i]]=0;
        while(!que.empty()){
            int nx=que.front().first,ny=que.front().second;
            que.pop();
            rep(j,4){
                int NX=nx+X[j],NY=ny+Y[j];
                if(NX<0||H<=NX||NY<0||W<=NY||A[NX][NY]=='#'||bfs[NX][NY]!=1e7)continue;
                bfs[NX][NY]=bfs[nx][ny]+1;
                que.push({NX,NY});
            }
        }
        rep(j,x.size())d[i][j]=bfs[x[j]][y[j]];
    }

    cout<<(bitdp(0,0)>=1e7?-1:dp[0][0])<<endl;
}
accuracy: 1
time_ms: 1860
memory_kb: 130928
final_rank: 14

code_snippet: #include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#define _USE_MATH_DEFINES
#include <cmath>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;

#define FOR(i,m,n) for(int i=(m);i<(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()

const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-8;
const int MOD = 1000000007;
// const int MOD = 998244353;
const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1};
// const int dy[] = {1, 1, 0, -1, -1, -1, 0, 1},
//           dx[] = {0, -1, -1, -1, 0, 1, 1, 1};

struct IOSetup {
  IOSetup() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    cerr << fixed << setprecision(10);
  }
} iosetup;
/*-------------------------------------------------*/
int main() {
  int h, w, k; cin >> h >> w >> k;
  vector<string> a(h); REP(i, h) cin >> a[i];
  int sy, sx, ey, ex;
  vector<int> y, x;
  REP(i, h) REP(j, w) {
    if (a[i][j] == 's') {
      sy = i;
      sx = j;
    } else if (a[i][j] == 'e') {
      ey = i;
      ex = j;
    } else if (a[i][j] == 'a') {
      y.emplace_back(i);
      x.emplace_back(j);
    }
  }
  int n = y.size();
  vector<vector<int> > dist(h, vector<int>(w, INF)), dp(1 << n, vector<int>(n, INF));
  dist[sy][sx] = 0;
  queue<pair<int, int> > que;
  que.emplace(sy, sx);
  while (!que.empty()) {
    int i = que.front().first, j = que.front().second; que.pop();
    REP(k, 4) {
      int r = i + dy[k], c = j + dx[k];
      if (0 <= r && r < h && 0 <= c && c < w && dist[r][c] == INF && a[r][c] != '#') {
        dist[r][c] = dist[i][j] + 1;
        que.emplace(r, c);
      }
    }
  }
  REP(i, n) dp[1 << i][i] = dist[y[i]][x[i]];
  vector<vector<int> > graph(n, vector<int>(n, INF));
  REP(s, n) {
    dist.assign(h, vector<int>(w, INF));
    dist[y[s]][x[s]] = 0;
    que.emplace(y[s], x[s]);
    while (!que.empty()) {
      int i = que.front().first, j = que.front().second; que.pop();
      REP(k, 4) {
        int r = i + dy[k], c = j + dx[k];
        if (0 <= r && r < h && 0 <= c && c < w && dist[r][c] == INF && a[r][c] != '#') {
          dist[r][c] = dist[i][j] + 1;
          que.emplace(r, c);
        }
      }
    }
    REP(t, n) graph[s][t] = dist[y[t]][x[t]];
  }
  FOR(i, 1, 1 << n) REP(j, n) {
    if (dp[i][j] == INF) continue;
    REP(k, n) if (!(i >> k & 1)) {
      if (graph[j][k] == INF) continue;
      dp[i | (1 << k)][k] = min(dp[i | (1 << k)][k], dp[i][j] + graph[j][k]);
    }
  }
  dist.assign(h, vector<int>(w, INF));
  dist[ey][ex] = 0;
  que.emplace(ey, ex);
  while (!que.empty()) {
    int i = que.front().first, j = que.front().second; que.pop();
    REP(k, 4) {
      int r = i + dy[k], c = j + dx[k];
      if (0 <= r && r < h && 0 <= c && c < w && dist[r][c] == INF && a[r][c] != '#') {
        dist[r][c] = dist[i][j] + 1;
        que.emplace(r, c);
      }
    }
  }
  int ans = INF;
  REP(i, 1 << n) REP(j, n) {
    if (__builtin_popcount(i) == k) ans = min(ans, dp[i][j] + dist[y[j]][x[j]]);
  }
  cout << (ans == INF ? -1 : ans) << '\n';
  return 0;
}
accuracy: 1
time_ms: 1120
memory_kb: 130948
final_rank: 8