Problem:
A Light Road
There is an evil creature in a square on N-by-M grid (
2 \leq N, M \leq 100
),
and you want to kill it using a laser generator located in a different square.
Since the location and direction of the laser generator are fixed,
you may need to use several mirrors to reflect laser beams.
There are some obstacles on the grid and you have a limited  number of mirrors.
Please find out whether it is possible to kill the creature,
and if possible, find the minimum number of mirrors.
There are two types of single-sided mirrors;
type P mirrors can be placed at the angle of 45 or 225 degrees from east-west direction,
and type Q mirrors can be placed with at the angle of 135 or 315 degrees.
For example, four mirrors are located properly, laser go through like the following.
Note that mirrors are single-sided,
and thus back side (the side with cross in the above picture) is not reflective.
You have
A
type P mirrors, and also
A
type Q mirrors (
0 \leq A \leq 10
).
Although you cannot put mirrors onto the squares with the creature or the laser generator,
laser beam can pass through the square.
Evil creature is killed if the laser reaches the square  it is  in.
Input
Each test case consists of several lines.
The first line contains three integers,
N
,
M
, and
A
.
Each of the following
N
lines contains
M
characters,
and represents the grid information.
'#', '.', 'S', 'G' indicates obstacle, empty square,
the location of the laser generator, and the location of the evil creature, respectively.
The first line shows the information in northernmost squares
and the last line shows the information in southernmost squares.
 You can assume that there is exactly one laser generator and exactly one creature,
and the laser generator emits laser beam always toward the south.
Output
Output the minimum number of mirrors used if you can kill creature, or -1 otherwise.
Sample Input 1
3 3 2
S#.
...
.#G
Output for the Sample Input 1
2
Sample Input 2
3 3 1
S#.
...
.#G
Output for the Sample Input 2
-1
Sample Input 3
3 3 1
S#G
...
.#.
Output for the Sample Input 3
2
Sample Input 4
4 3 2
S..
...
..#
.#G
Output for the Sample Input 4
-1

Submitted solutions:

code_snippet: /*###############################################################################################################
##                                Author : Minseong Gwak (astilate, minsung05)                                 ##
###############################################################################################################*/

#include<bits/stdc++.h>
 
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
 
#define getint(n) int n; scanf("%d%*c", &n)
#define getll(n)  ll n; scanf("%lld%*c", &n)
#define getchar(n) char n; scanf("%c%*c", &n)
#define inta int a; scanf("%d%*c", &a)
#define intab int a,b; scanf("%d%*c%d%*c", &a,&b)
 
#define forr(i, n) for(int i=1; i <= (n); i++)
#define fors(i, s, e) for(int i = (s); i<=(e); i++)
#define fore(i, e, s) for(int i = (e); i >= (s); i--)
 
#define pb push_back
#define fi first
#define se second
 
using namespace std;
 
using ll = long long; using lll = __int128_t;
using pii = pair<int, int>; using pll = pair<ll, ll>;
using vi = vector<int>; using vii=vector<pii>;
using vl = vector<ll>; using vll=vector<pll>;

#define prev _prev
#define next _next

const int N = 105, A = 15;
char s[N][N];
int D[N][N][A][A][5];
int di[5] = {0, 1, 0, -1, 0};
int dj[5] = {0, 0, 1, 0, -1};
int P[5] = {0, 4, 3, 2, 1};
int Q[5] = {0, 2, 1, 4, 3};

using st = tuple<int, int, int, int, int>;

int main()
{
    getint(n); getint(m); getint(a);
    for(int i=1;i<=n;i++) scanf("%s%*c", s[i]+1);
    pii S, G; bool ss = 0, gg = 0;
    forr(i, n) forr(j, m)
    {
        if(s[i][j] == 'S') S = {i, j}, ss = 1;
        else if(s[i][j] == 'G') G = {i, j}, gg = 1;
    }

    if(!ss || !gg || S.fi == n || s[S.fi+1][S.se] == '#')
    {
        printf("-1\n");
        return 0;
    }

    queue<st> q;
    q.push({S.fi+1, S.se, 0, 0, 1});
    D[S.fi+1][S.se][0][0][1] = true;

    while(!q.empty())
    {
        auto [i, j, x, y, k] = q.front(); q.pop();
        
        if(s[i][j] == '.')
        {
            // type P : 1 <-> 4, 2 <-> 3
            {
                int ii = i+di[P[k]], jj = j+dj[P[k]];
                if(ii<1||ii>n||jj<1||jj>m);
                else if(x+1 > a);
                else if(D[ii][jj][x+1][y][P[k]] || s[ii][jj] == '#' || (s[ii][jj] == 'S' && P[k]%2 == 1));
                else
                {
                    D[ii][jj][x+1][y][P[k]] = true;
                    q.push({ii, jj, x+1, y, P[k]});
                }
            }
            // type Q : 1 <-> 2, 3 <-> 4
            {
                int ii = i+di[Q[k]], jj = j+dj[Q[k]];
                if(ii<1||ii>n||jj<1||jj>m);
                else if(y+1 > a);
                else if(D[ii][jj][x][y+1][Q[k]] || s[ii][jj] == '#' || (s[ii][jj] == 'S' && Q[k]%2 == 1));
                else
                {
                    D[ii][jj][x][y+1][Q[k]] = true;
                    q.push({ii, jj, x, y+1, Q[k]});
                }
            }
        }

        {
            int ii = i+di[k], jj = j+dj[k];
            if(ii<1||ii>n||jj<1||jj>m);
            else if(D[ii][jj][x][y][k] || s[ii][jj] == '#' || (s[ii][jj] == 'S' && k%2 == 1));
            else
            {
                D[ii][jj][x][y][k] = true;
                q.push({ii, jj, x, y, k});
            }
        }
    }

    int ans = 100;
    fors(x, 0, a) fors(y, 0, a) forr(k, 4) if(D[G.fi][G.se][x][y][k]) ans = min(ans, x+y);

    printf("%d\n", ans==100?-1:ans);
}
accuracy: 1
time_ms: 10
memory_kb: 48892
final_rank: 13

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

struct Data {
	int px, py, dir, c1, c2;
};

const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
int H, W, A, sx, sy, gx, gy;
bool dp[109][109][4][11][11];
char C[109][109];
queue<Data> Q;

int main() {
	// Step 1. Input
	cin >> H >> W >> A;
	for (int i = 1; i <= H; i++) {
		for (int j = 1; j <= W; j++) {
			cin >> C[i][j];
			if (C[i][j] == 'S') { C[i][j] = '.'; sx = i; sy = j; }
			if (C[i][j] == 'G') { C[i][j] = '.'; gx = i; gy = j; }
		}
	}

	// Step 2. BFS Init
	dp[sx][sy][1][0][0] = true;
	Q.push(Data{sx, sy, 1, 0, 0});

	// Step 3. BFS Main
	while (!Q.empty()) {
		Data pos = Q.front(); Q.pop();
		if (true) {
			int nx = pos.px + dx[pos.dir];
			int ny = pos.py + dy[pos.dir];
			if (nx == sx && ny == sy && pos.dir == 3) continue;
			if (nx >= 1 && ny >= 1 && nx <= H && ny <= W && C[nx][ny] != '#' && dp[nx][ny][pos.dir][pos.c1][pos.c2] == false) {
				dp[nx][ny][pos.dir][pos.c1][pos.c2] = true;
				Data nex = {nx, ny, pos.dir, pos.c1, pos.c2};
				Q.push(nex);
			}
		}

		// Rotate
		bool flag = true;
		if (sx == pos.px && sy == pos.py) flag = false;
		if (gx == pos.px && gy == pos.py) flag = false;

		// Actually Rotate
		if (flag == true) {
			for (int i = 0; i < 4; i++) {
				if ((i + 0) % 4 == pos.dir) continue;
				if ((i + 2) % 4 == pos.dir) continue;
				int nx = pos.px + dx[i];
				int ny = pos.py + dy[i];
				int c1 = pos.c1 + ((i + pos.dir) % 4 == 1 ? 1 : 0);
				int c2 = pos.c2 + ((i + pos.dir) % 4 == 3 ? 1 : 0);
				if (nx == sx && ny == sy && i == 3) continue;
				if (nx >= 1 && ny >= 1 && nx <= H && ny <= W && c1 <= A && c2 <= A && C[nx][ny] != '#' && dp[nx][ny][i][c1][c2] == false) {
					dp[nx][ny][i][c1][c2] = true;
					Data nex = {nx, ny, i, c1, c2};
					Q.push(nex);
				}
			}
		}
	}

	// Step 4. Get Answer
	int Answer = (1 << 30);
	for (int i = 0; i <= A; i++) {
		for (int j = 0; j <= A; j++) {
			for (int k = 0; k < 4; k++) {
				if (dp[gx][gy][k][i][j] == true) Answer = min(Answer, i + j);
			}
		}
	}
	cout << (Answer == (1 << 30) ? -1 : Answer) << endl;
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 7396
final_rank: 5

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
int dd[3] = {0,1,3}, du[3] = {0,0,1}, dv[3] = {0,1,0};

int main() {
    int N, M, A;
    cin >> N >> M >> A;
    vector<vector<bool>> G(N,vector<bool>(M,true));
    int SX, SY, GX, GY;
    rep(i,0,N) {
        rep(j,0,M) {
            char c;
            cin >> c;
            if (c == '#') G[i][j] = false;
            if (c == 'S') SX = i, SY = j;
            if (c == 'G') GX = i, GY = j;
        }
    }
    auto encode = [&](int x, int y, int dir, int a, int b) -> int {
        return x*M*4*(A+1)*(A+1) + y*4*(A+1)*(A+1) + dir*(A+1)*(A+1) + a*(A+1) + b;
    };
    auto decode = [&](int e) -> tuple<int,int,int,int,int> {
        int x, y, dir, a, b;
        b = e % (A+1), e /= (A+1);
        a = e % (A+1), e /= (A+1);
        dir = e % 4, e /= 4;
        y = e % M, e /= M;
        x = e;
        return {x,y,dir,a,b};
    };
    auto canmove = [&](int x, int y, int dir, int u, int v) -> bool {
        return 0<=x && x<N && 0<=y && y<M && G[x][y] && u<=A && v<=A && (x != SX || y != SY || dir != 2);
    };
    vector<bool> DP(N*M*4*(A+1)*(A+1),false);
    queue<int> Q;
    DP[encode(SX,SY,0,0,0)] = true;
    Q.push(encode(SX,SY,0,0,0));
    while(!Q.empty()) {
        int P = Q.front();
        Q.pop();
        auto [X,Y,dir,U,V] = decode(P);
        rep(i,0,3) {
            int NX = X + dx[dir], NY = Y + dy[dir];
            int Ndir = dir ^ dd[i];
            int NU = U + du[i], NV = V + dv[i];
            int E = encode(NX,NY,Ndir,NU,NV);
            if (canmove(NX,NY,Ndir,NU,NV) && !DP[E]) {
                DP[E] = true;
                Q.push(E);
            }
        }
    }
    int ANS = inf;
    rep(i,0,4) {
        rep(j,0,A+1) {
            rep(k,0,A+1) {
                if (DP[encode(GX,GY,i,j,k)]) chmin(ANS,j+k);
            }
        }
    }
    cout << (ANS == inf ? -1 : ANS) << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 3508
final_rank: 1

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

struct Data {
	int px, py, dir, c1, c2;
};

const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
int H, W, A, sx, sy, gx, gy;
bool dp[109][109][4][11][11];
char C[109][109];
queue<Data> Q;

int main() {
	// Step 1. Input
	cin >> H >> W >> A;
	for (int i = 1; i <= H; i++) {
		for (int j = 1; j <= W; j++) {
			cin >> C[i][j];
			if (C[i][j] == 'S') { C[i][j] = '.'; sx = i; sy = j; }
			if (C[i][j] == 'G') { C[i][j] = '.'; gx = i; gy = j; }
		}
	}

	// Step 2. BFS Init
	dp[sx][sy][1][0][0] = true;
	Q.push(Data{sx, sy, 1, 0, 0});

	// Step 3. BFS Main
	while (!Q.empty()) {
		Data pos = Q.front(); Q.pop();
		if (true) {
			int nx = pos.px + dx[pos.dir];
			int ny = pos.py + dy[pos.dir];
			if (nx == sx && ny == sy && pos.dir == 3) continue;
			if (nx >= 1 && ny >= 1 && nx <= H && ny <= W && C[nx][ny] != '#' && dp[nx][ny][pos.dir][pos.c1][pos.c2] == false) {
				dp[nx][ny][pos.dir][pos.c1][pos.c2] = true;
				Data nex = {nx, ny, pos.dir, pos.c1, pos.c2};
				Q.push(nex);
			}
		}

		// Rotate
		bool flag = true;
		if (sx == pos.px && sy == pos.py) flag = false;
		if (gx == pos.px && gy == pos.py) flag = false;

		// Actually Rotate
		if (flag == true) {
			for (int i = 0; i < 4; i++) {
				if ((i + 0) % 4 == pos.dir) continue;
				if ((i + 2) % 4 == pos.dir) continue;
				int nx = pos.px + dx[i];
				int ny = pos.py + dy[i];
				int c1 = pos.c1 + ((i + pos.dir) % 4 == 1 ? 1 : 0);
				int c2 = pos.c2 + ((i + pos.dir) % 4 == 3 ? 1 : 0);
				if (nx == sx && ny == sy && i == 3) continue;
				if (nx >= 1 && ny >= 1 && nx <= H && ny <= W && c1 <= A && c2 <= A && C[nx][ny] != '#' && dp[nx][ny][i][c1][c2] == false) {
					dp[nx][ny][i][c1][c2] = true;
					Data nex = {nx, ny, i, c1, c2};
					Q.push(nex);
				}
			}
		}
	}

	// Step 4. Get Answer
	int Answer = (1 << 30);
	for (int i = 0; i <= A; i++) {
		for (int j = 0; j <= A; j++) {
			for (int k = 0; k < 4; k++) {
				if (dp[gx][gy][k][i][j] == true) Answer = min(Answer, i + j);
			}
		}
	}
	cout << (Answer == (1 << 30) ? -1 : Answer) << endl;
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 7180
final_rank: 4

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

typedef pair<int,int> pii;

bool memo[100][100][4][11][11];
struct p {
    int y, x, d, r, l;
};

int main() {
    int N, M, A;
    cin >> N >> M >> A;
    vector<string> b(N);
    for(int i = 0; i < N; i++) {
        cin >> b[i];
    }
    queue<p> q;
    pii goal, start;
    for(int i = 0; i < N; i++) {
        for(int j = 0; j < M; j++) {
            if(b[i][j]=='S') {
                memo[i][j][0][0][0] = true;
                q.push((p){i,j,0,0,0});
                start=pii(i,j);
            }
            if(b[i][j]=='G') {
                goal=pii(i,j);
            }
        }
    }
    while(q.size()) {
        int dxy[] = {1,0,-1,0,1};
        p t = q.front(); q.pop();
        //cout << t.y << " " << t.x << " " << t.d << endl;
        for(int i = 0; i < 4; i++) {
            int nx, ny;
            ny = t.y + dxy[i];
            nx = t.x + dxy[i+1];
            if(ny < 0 || N <= ny || nx < 0 || M <= nx) continue;
            if(b[ny][nx] == '#') continue;

            if(ny==start.second && nx==start.first && i==2) continue;

            if(i==(t.d+2)%4) {
                continue; // turn
            }
            else if(i==t.d) {
                // go straight
                if(memo[ny][nx][i][t.r][t.l]) continue;
                memo[ny][nx][i][t.r][t.l] = true;
                q.push((p){ny,nx,i,t.r,t.l});
            }
            else if(b[t.y][t.x] == '.') {
                if(i+t.d==3){
                    // type P
                    if(t.r+1 > A) continue;
                    if(memo[ny][nx][i][t.r+1][t.l]) continue;
                    memo[ny][nx][i][t.r+1][t.l] = true;
                    q.push((p){ny,nx,i,t.r+1,t.l});
                }
                else {
                    // type Q
                    if(t.l+1 > A) continue;
                    if(memo[ny][nx][i][t.r][t.l+1]) continue;
                    memo[ny][nx][i][t.r][t.l+1] = true;
                    q.push((p){ny,nx,i,t.r,t.l+1});
                }
            }
        }
    }
    int res = -1;
    for(int i = 0; i <= A; i++) {
        for(int j = 0; j <= A; j++) {
            for(int k = 0; k < 4; k++) {
                if(memo[goal.first][goal.second][k][i][j]) {
                    if(res+1) res = min(res, i+j);
                    else res = i+j;
                }
            }
        }
    }
    cout << res << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 6416
final_rank: 2

code_snippet: #include <bits/stdc++.h>
using namespace std;
vector<int> dy = {1, 0, -1, 0};
vector<int> dx = {0, 1, 0, -1};
vector<int> p = {1, 0, 3, 2};
vector<int> q = {3, 2, 1, 0};
int main(){
  int N, M, A;
  cin >> N >> M >> A;
  vector<vector<char>> c(N + 2, vector<char>(M + 2, '#'));
  for (int i = 1; i <= N; i++){
    for (int j = 1; j <= M; j++){
      cin >> c[i][j];
    }
  }
  int sy, sx;
  for (int i = 1; i <= N; i++){
    for (int j = 1; j <= M; j++){
      if (c[i][j] == 'S'){
        sy = i;
        sx = j;
      }
    }
  }
  set<tuple<int, int, int, int, int>> st;
  deque<tuple<int, int, int, int, int>> dq;
  dq.push_back(make_tuple(0, 0, sy, sx, 0));
  int ans = -1;
  while (!dq.empty()){
    tuple<int, int, int, int, int> T = dq.front();
    dq.pop_front();
    if (!st.count(T)){
      st.insert(T);
      int cnt1 = get<0>(T);
      int cnt2 = get<1>(T);
      int y = get<2>(T);
      int x = get<3>(T);
      int d = get<4>(T);
      if (c[y][x] == 'G'){
        ans = cnt1 + cnt2;
        break;
      }
      if (c[y][x] != 'S'){
        if (cnt1 < A){
          int d2 = p[d];
          int y2 = y + dy[d2];
          int x2 = x + dx[d2];
          if (c[y2][x2] != '#' && !(c[y2][x2] == 'S' && d2 == 2)){
            tuple<int, int, int, int, int> T2 = make_tuple(cnt1 + 1, cnt2, y2, x2, d2);
            if (!st.count(T2)){
              dq.push_back(T2);
            }
          }
        }
        if (cnt2 < A){
          int d2 = q[d];
          int y2 = y + dy[d2];
          int x2 = x + dx[d2];
          if (c[y2][x2] != '#' && !(c[y2][x2] == 'S' && d2 == 2)){
            tuple<int, int, int, int, int> T2 = make_tuple(cnt1, cnt2 + 1, y2, x2, d2);
            if (!st.count(T2)){
              dq.push_back(T2);
            }
          }
        }
      }
      int y2 = y + dy[d];
      int x2 = x + dx[d];
      if (c[y2][x2] != '#' && !(c[y2][x2] == 'S' && d == 2)){
        tuple<int, int, int, int, int> T2 = make_tuple(cnt1, cnt2, y2, x2, d);
        if (!st.count(T2)){
          dq.push_front(T2);
        }
      }
    }
  }
  cout << ans << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 8308
final_rank: 7

code_snippet: #line 2 "/home/nok0/documents/programming/library/template/header.hpp"
#include <bits/stdc++.h>
#line 3 "/home/nok0/documents/programming/library/template/def_const.hpp"

const int inf = 1000000000;
const long long INF = 1000000000000000000ll;
#line 4 "/home/nok0/documents/programming/library/template/debug.hpp"

namespace viewer {
void view(const long long &e) {
	if(e == INF)
		std::cerr << "INF";
	else if(e == -INF)
		std::cerr << "-INF";
	else
		std::cerr << e;
}

void view(const int &e) {
	if(e == inf)
		std::cerr << "inf";
	else if(e == -inf)
		std::cerr << "-inf";
	else
		std::cerr << e;
}

template <typename T>
void view(const T &e) {
	std::cerr << e;
}

template <typename T, typename U>
void view(const std::pair<T, U> &p) {
	std::cerr << "(";
	view(p.first);
	std::cerr << ", ";
	view(p.second);
	std::cerr << ")";
}

template <class T0, class T1, class T2>
void view(const std::tuple<T0, T1, T2> &p) {
	std::cerr << "(";
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ")";
}

template <class T0, class T1, class T2, class T3>
void view(const std::tuple<T0, T1, T2, T3> &p) {
	std::cerr << "(";
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ", ";
	view(std::get<3>(p));
	std::cerr << ")";
}

template <typename T>
void view(const std::set<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::unordered_set<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::multiset<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::unordered_multiset<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::vector<T> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(const auto &e : v) {
		view(e);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T, std::size_t ary_size>
void view(const std::array<T, ary_size> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(const auto &e : v) {
		view(e);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::vector<std::vector<T>> &vv) {
	std::cerr << "{\n";
	for(const auto &v : vv) {
		std::cerr << "\t";
		view(v);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::vector<std::pair<T, U>> &v) {
	std::cerr << "{\n";
	for(const auto &c : v) {
		std::cerr << "\t(";
		view(c.first);
		std::cerr << ", ";
		view(c.second);
		std::cerr << ")\n";
	}
	std::cerr << "}";
}

template <class T0, class T1, class T2>
void view(const std::vector<std::tuple<T0, T1, T2>> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << '{';
	for(const auto &t : v) {
		std::cerr << "\n\t";
		view(t);
		std::cerr << ",";
	}
	std::cerr << "\n}";
}

template <class T0, class T1, class T2, class T3>
void view(const std::vector<std::tuple<T0, T1, T2, T3>> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << '{';
	for(const auto &t : v) {
		std::cerr << "\n\t";
		view(t);
		std::cerr << ",";
	}
	std::cerr << "\n}";
}

template <typename T, typename U>
void view(const std::map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &t : m) {
		std::cerr << "\t[";
		view(t.first);
		std::cerr << "] : ";
		view(t.second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::unordered_map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &t : m) {
		std::cerr << "\t[";
		view(t.first);
		std::cerr << "] : ";
		view(t.second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}
}  // namespace viewer

// when compiling : g++ foo.cpp -DLOCAL
#ifdef LOCAL
void debug_out() {}
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
	viewer::view(H);
	std::cerr << ", ";
	debug_out(T...);
}
#define debug(...)                                                \
	do {                                                          \
		std::cerr << __LINE__ << " [" << #__VA_ARGS__ << "] : ["; \
		debug_out(__VA_ARGS__);                                   \
		std::cerr << "\b\b]\n";                                   \
	} while(0)
#define dump(x)                                      \
	do {                                             \
		std::cerr << __LINE__ << " " << #x << " : "; \
		viewer::view(x);                             \
		std::cerr << '\n';                           \
	} while(0)

#else
#define debug(...) (void(0))
#define dump(x)    (void(0))
#endif
#line 3 "/home/nok0/documents/programming/library/template/def_name.hpp"

#define pb        push_back
#define eb        emplace_back
#define SZ(x)     ((int)(x).size())
#define all(x)    (x).begin(), (x).end()
#define rall(x)   (x).rbegin(), (x).rend()
#define popcnt(x) __builtin_popcountll(x)
template<class T = int>
using V = std::vector<T>;
template<class T = int>
using VV = std::vector<std::vector<T>>;
template<class T>
using pqup = std::priority_queue<T, std::vector<T>, std::greater<T>>;
using ll = long long;
using ld = long double;
using int128 = __int128_t;
using pii = std::pair<int, int>;
using pll = std::pair<long long, long long>;
#line 3 "/home/nok0/documents/programming/library/template/fast_io.hpp"

struct fast_io {
	fast_io() {
		std::ios::sync_with_stdio(false);
		std::cin.tie(nullptr);
		std::cout << std::fixed << std::setprecision(15);
	}
} fast_io_;
#line 3 "/home/nok0/documents/programming/library/template/input.hpp"

template<class T, class U>
std::istream &operator>>(std::istream &is, std::pair<T, U> &p) {
    is >> p.first >> p.second;
    return is;
}
template<class T>
std::istream &operator>>(std::istream &is, std::vector<T> &v) {
    for (T &i : v) is >> i;
    return is;
}
std::istream &operator>>(std::istream &is, __int128_t &a) {
    std::string s;
    is >> s;
    __int128_t ret = 0;
    for (int i = 0; i < (int)s.length(); i++)
        if ('0' <= s[i] and s[i] <= '9')
            ret = 10 * ret + s[i] - '0';
    a = ret * (s[0] == '-' ? -1 : 1);
    return is;
}
namespace scanner {
void scan(int &a) { std::cin >> a; }
void scan(long long &a) { std::cin >> a; }
void scan(std::string &a) { std::cin >> a; }
void scan(char &a) { std::cin >> a; }
void scan(char a[]) { std::scanf("%s", a); }
void scan(double &a) { std::cin >> a; }
void scan(long double &a) { std::cin >> a; }
template<class T, class U>
void scan(std::pair<T, U> &p) { std::cin >> p; }
template<class T>
void scan(std::vector<T> &a) { std::cin >> a; }
void INPUT() {}
template<class Head, class... Tail>
void INPUT(Head &head, Tail &...tail) {
    scan(head);
    INPUT(tail...);
}
}  // namespace scanner
#define VEC(type, name, size)     \
    std::vector<type> name(size); \
    scanner::INPUT(name)
#define VVEC(type, name, h, w)                                    \
    std::vector<std::vector<type>> name(h, std::vector<type>(w)); \
    scanner::INPUT(name)
#define INT(...)     \
    int __VA_ARGS__; \
    scanner::INPUT(__VA_ARGS__)
#define LL(...)            \
    long long __VA_ARGS__; \
    scanner::INPUT(__VA_ARGS__)
#define STR(...)             \
    std::string __VA_ARGS__; \
    scanner::INPUT(__VA_ARGS__)
#define CHAR(...)     \
    char __VA_ARGS__; \
    scanner::INPUT(__VA_ARGS__)
#define DOUBLE(...)     \
    double __VA_ARGS__; \
    scanner::INPUT(__VA_ARGS__)
#define LD(...)              \
    long double __VA_ARGS__; \
    scanner::INPUT(__VA_ARGS__)
#line 3 "/home/nok0/documents/programming/library/template/math.hpp"

template <class T, class U>
inline bool chmin(T &a, const U &b) { return a > b ? a = b, true : false; }
template <class T, class U>
inline bool chmax(T &a, const U &b) { return a < b ? a = b, true : false; }
template <class T>
T divup(T x, T y) { return (x + y - 1) / y; }
template <class T>
T POW(T a, long long n) {
	T ret = 1;
	while(n) {
		if(n & 1) ret *= a;
		a *= a;
		n >>= 1;
	}
	return ret;
}
long long POW(long long a, long long n, const int mod) {
	long long ret = 1;
	a = (a % mod + mod) % mod;
	while(n) {
		if(n & 1) (ret *= a) %= mod;
		(a *= a) %= mod;
		n >>= 1;
	}
	return ret;
}
template <class T, class F>
T bin_search(T ok, T ng, const F &f) {
	while(abs(ok - ng) > 1) {
		T mid = (ok + ng) >> 1;
		(f(mid) ? ok : ng) = mid;
	}
	return ok;
}
template <class T, class F>
T bin_search(T ok, T ng, const F &f, int loop) {
	for(int i = 0; i < loop; i++) {
		T mid = (ok + ng) / 2;
		(f(mid) ? ok : ng) = mid;
	}
	return ok;
}
#line 3 "/home/nok0/documents/programming/library/template/output.hpp"


template<class T, class U>
std::ostream &operator<<(std::ostream &os, const std::pair<T, U> &p) {
    os << p.first << " " << p.second;
    return os;
}
template<class T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &a) {
    for (int i = 0; i < int(a.size()); ++i) {
        if (i) os << " ";
        os << a[i];
    }
    return os;
}
std::ostream &operator<<(std::ostream &dest, __int128_t &value) {
    std::ostream::sentry s(dest);
    if (s) {
        __uint128_t tmp = value < 0 ? -value : value;
        char buffer[128];
        char *d = std::end(buffer);
        do {
            --d;
            *d = "0123456789"[tmp % 10];
            tmp /= 10;
        } while (tmp != 0);
        if (value < 0) {
            --d;
            *d = '-';
        }
        int len = std::end(buffer) - d;
        if (dest.rdbuf()->sputn(d, len) != len) {
            dest.setstate(std::ios_base::badbit);
        }
    }
    return dest;
}
template<class T>
void print(const T a) { std::cout << a << '\n'; }
template<class Head, class... Tail>
void print(Head H, Tail... T) {
    std::cout << H << ' ';
    print(T...);
}
template<class T>
void printel(const T a) { std::cout << a << '\n'; }
template<class T>
void printel(const std::vector<T> &a) {
    for (const auto &v : a)
        std::cout << v << '\n';
}
template<class Head, class... Tail>
void printel(Head H, Tail... T) {
    std::cout << H << '\n';
    printel(T...);
}
void Yes(const bool b = true) { std::cout << (b ? "Yes\n" : "No\n"); }
void No() { std::cout << "No\n"; }
void YES(const bool b = true) { std::cout << (b ? "YES\n" : "NO\n"); }
void NO() { std::cout << "NO\n"; }
#line 2 "/home/nok0/documents/programming/library/template/rep.hpp"

#define foa(v, a)                   for (auto &v : a)
#define repname(a, b, c, d, e, ...) e
#define rep(...)                    repname(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)
#define rep0(x)                     for (int rep_counter = 0; rep_counter < (x); ++rep_counter)
#define rep1(i, x)                  for (int i = 0; i < (x); ++i)
#define rep2(i, l, r)               for (int i = (l); i < (r); ++i)
#define rep3(i, l, r, c)            for (int i = (l); i < (r); i += (c))

#define repsname(a, b, c, ...) c
#define reps(...)              repsname(__VA_ARGS__, reps1, reps0)(__VA_ARGS__)
#define reps0(x)               for (int reps_counter = 1; reps_counter <= (x); ++reps_counter)
#define reps1(i, x)            for (int i = 1; i <= (x); ++i)

#define rrepname(a, b, c, ...) c
#define rrep(...)              rrepname(__VA_ARGS__, rrep1, rrep0)(__VA_ARGS__)
#define rrep0(x)               for (int rrep_counter = (x)-1; rrep_counter >= 0; --rrep_counter)
#define rrep1(i, x)            for (int i = (x)-1; i >= 0; --i)
#line 3 "/home/nok0/documents/programming/library/template/vector.hpp"

template <class T>
int lb(const std::vector<T> &a, const T x) { return std::distance((a).begin(), std::lower_bound((a).begin(), (a).end(), (x))); }
template <class T>
int ub(const std::vector<T> &a, const T x) { return std::distance((a).begin(), std::upper_bound((a).begin(), (a).end(), (x))); }
template <class T>
void UNIQUE(std::vector<T> &a) {
	std::sort(a.begin(), a.end());
	a.erase(std::unique(a.begin(), a.end()), a.end());
}
template <class T>
std::vector<T> press(std::vector<T> &a) {
	auto res = a;
	UNIQUE(res);
	for(auto &v : a)
		v = lb(res, v);
	return res;
}
#define SORTname(a, b, c, ...) c
#define SORT(...)              SORTname(__VA_ARGS__, SORT1, SORT0, ...)(__VA_ARGS__)
#define SORT0(a)               std::sort((a).begin(), (a).end())
#define SORT1(a, c)            std::sort((a).begin(), (a).end(), [](const auto x, const auto y) { return x c y; })
template <class T>
void ADD(std::vector<T> &a, const T x = 1) {
	for(auto &v : a) v += x;
}
template <class T>
void SUB(std::vector<T> &a, const T x = 1) {
	for(auto &v : a) v -= x;
}
template <class T>
struct cum_vector {
   public:
	cum_vector() = default;
	template <class U>
	cum_vector(const std::vector<U> &vec) : cum((int)vec.size() + 1) {
		for(int i = 0; i < (int)vec.size(); i++)
			cum[i + 1] = cum[i] + vec[i];
	}
	T prod(int l, int r) {
		return cum[r] - cum[l];
	}

   private:
	std::vector<T> cum;
};
std::vector<std::pair<char, int>> rle(const std::string &s) {
	const int n = s.size();
	std::vector<std::pair<char, int>> ret;
	for(int l = 0; l < n;) {
		int r = l + 1;
		for(; r < n and s[l] == s[r]; r++) {}
		ret.emplace_back(s[l], r - l);
		l = r;
	}
	return ret;
}
template <class T>
std::vector<std::pair<T, int>> rle(const std::vector<T> &v) {
	int n = v.size();
	std::vector<std::pair<T, int>> ret;
	for(int l = 0; l < n;) {
		int r = l + 1;
		for(; r < n and v[l] == v[r]; r++) {}
		ret.emplace_back(v[l], r - l);
		l = r;
	}
	return ret;
}
std::vector<int> iota(int n) {
	std::vector<int> p(n);
	std::iota(p.begin(), p.end(), 0);
	return p;
}
#line 11 "/home/nok0/documents/programming/library/template/all"
using namespace std;
#line 2 "d.cpp"

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

int main() {
	INT(n, m, a);
	VEC(string, s, n);
	auto valid = [&](int x, int y) {
		return x >= 0 and x < n and y >= 0 and y < m and s[x][y] != '#';
	};
	using T = tuple<int, int, int, int, int>;
	deque<T> deq;
	int sx, sy, gx, gy;
	rep(i, n) {
		rep(j, m) {
			if(s[i][j] == 'S') sx = i, sy = j;
			if(s[i][j] == 'G') gx = i, gy = j;
		}
	}
	//現在地 前回の方向 使った個数 2つ
	auto decode = [&](int x, int y, int od, int up, int uq) {
		auto ret = x;
		ret *= m;
		ret += y;
		ret *= 4;
		ret += od;
		ret *= 11;
		ret += up;
		ret *= 11;
		ret += uq;
		return ret;
	};
	auto mx = decode(n, 0, 0, 0, 0);
	vector<int> dist(mx, inf);

	auto x = decode(sx, sy, 0, 0, 0);
	dist[x] = 0;
	deq.push_back(T(sx, sy, 0, 0, 0));


	while(SZ(deq)) {
		auto [x, y, od, up, uq] = deq.front();
		debug(x, y, od, up, uq);
		deq.pop_front();
		rep(k, 4) {
			if(abs(od - k) == 2) continue;
			auto nx = x + dx[k], ny = y + dy[k];
			if(!valid(nx, ny) or (nx == sx and ny == sy and k == 2)) continue;
			auto nup = up, nuq = uq;
			int cost = 0;
			if(od != k) {
				cost = 1;
				if(x == sx and y == sy) continue;
				if(od == 0 and k == 1)
					nup++;
				else if(od == 3 and k == 2)
					nup++;
				else if(od == 1 and k == 0)
					nup++;
				else if(od == 2 and k == 3)
					nup++;
				else
					nuq++;
			}
			if(nup <= a and nuq <= a) {
				auto nxt = decode(nx, ny, k, nup, nuq);
				if(dist[nxt] <= dist[decode(x, y, od, up, uq)] + cost) continue;
				dist[nxt] = dist[decode(x, y, od, up, uq)] + cost;
				auto nxT = T(nx, ny, k, nup, nuq);
				if(!cost) {
					deq.push_front(nxT);
				} else {
					deq.push_back(nxT);
				}
			}
		}
	}
	int res = inf;
	rep(k, 4) {
		rep(p, a + 1) {
			rep(q, a + 1) {
				chmin(res, dist[decode(gx, gy, k, p, q)]);
			}
		}
	}
	print(res != inf ? res : -1);
}
accuracy: 1
time_ms: 10
memory_kb: 18440
final_rank: 6

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

int main(){
	cin.tie(0);
	ios::sync_with_stdio(0);
	
	int H,W,A; cin >> H >> W >> A;
	vector<string> s(H);
	rep(i,H) cin >> s[i];
	int si,sj,gi,gj;
	rep(i,H)rep(j,W) {
		if(s[i][j] == 'S') si = i, sj = j;
		if(s[i][j] == 'G') gi = i, gj = j; 
	}

	using T = tuple<int,int,int,int,int>; // i, j, p, q, d
	set<T> se;
	deque<T> dq; dq.push_back({si, sj, 0, 0, 0});
	int ans = -1;
	int di[] = {1,  0, -1,  0};
	int dj[] = {0,  1,  0, -1};
	int np[] = {1,  0,  3,  2};
	int nq[] = {3,  2,  1,  0};
	auto ok = [&](int i, int j){ return 0 <= i && i < H && 0 <= j && j < W; };

	while(!dq.empty()) {
		T v = dq.front(); dq.pop_front();
		if(!se.count(v)) {
			se.insert(v);
			int i,j,p,q,d; tie(i,j,p,q,d) = v;
			
			if(s[i][j] == 'G') {
				ans = p + q; break;
			}

			if(s[i][j] != 'S' && p < A) {
				int nd = np[d], ni = i + di[nd], nj = j + dj[nd];
				if(ok(ni, nj) && s[ni][nj] != '#' && !(s[ni][nj] == 'S' && nd == 2)) {
					T to = {ni, nj, p + 1, q, nd};
					if(!se.count(to)) dq.push_back(to);
				}
			}

			if(s[i][j] != 'S' && q < A) {
				int nd = nq[d], ni = i + di[nd], nj = j + dj[nd];
				if(ok(ni, nj) && s[ni][nj] != '#' && !(s[ni][nj] == 'S' && nd == 2)) {
					T to = {ni, nj, p, q + 1, nd};
					if(!se.count(to)) dq.push_back(to);
				}
			}

			int ni = i + di[d], nj = j + dj[d];
			if(ok(ni, nj) && s[ni][nj] != '#' && !(s[ni][nj] == 'S' && d == 2)) {
				T to = {ni, nj, p, q, d};
				dq.push_front(to);
			}
		}
	}

	cout << ans << '\n';
}
accuracy: 1
time_ms: 30
memory_kb: 8360
final_rank: 12

code_snippet: #pragma GCC tag("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define DEBUG
#ifdef DEBUG
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for(int i = 0; i < (int)v.size(); i++) {
        if(i) { os << ','; }
        os << v[i];
    }
    os << '}';
    return os;
}
void debugg() { cerr << endl; }
template <class T, class... Args>
void debugg(const T &x, const Args &... args) {
    cerr << " " << x;
    debugg(args...);
}
#define debug(...)                                                             \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debugg(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef pair<int,int> pii;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(int i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
	if(a>b){
		a = b; return true;
	}
	else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
	if(a<b){
		a = b; return true;
	}
	else return false;
}
template<typename T> inline void print(T &a){
    int sz = a.size();
    for(auto itr = a.begin(); itr != a.end(); itr++){
		cout << *itr;
        sz--;
        if(sz) cout << " ";
	}
    cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){
	cout << a << " " << b << "\n";
}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
	cout << a << " " << b << " " << c << "\n";
}
void mark() {cout << "#" << "\n";}
ll pcount(ll x) {return __builtin_popcountll(x);}
//#include <atcoder/maxflow>
//using namespace atcoder;
const int inf = (1<<30)-1;
const ll linf = 1LL<<61;
const int MAX = 5050000;
int dy[8] = {0,1,0,-1,1,-1,-1,1};
int dx[8] = {-1,0,1,0,1,-1,1,-1};
const double pi = acos(-1);
const double eps = 1e-9;
const int mod = 1e9 + 7;
//const int mod = 998244353;

bool in(ll y, ll x, ll h, ll w){
    return 0 <= y && y < h && 0 <= x && x < w;
}

struct state{
    int c,y,x,p,q,dir;
};

int d[101][101][11][11][4];

int main(){
    int n,m,a; cin >> n >> m >> a;
    vs s(n); rep(i,n) cin >> s[i];
    rep(i,n) rep(j,m) rep(k,a+1) rep(l,a+1) rep(o,4) d[i][j][k][l][o] = inf;
    int gy,gx;
    queue<state> q;
    rep(i,n) rep(j,m){
        if(s[i][j] == 'S'){
            d[i][j][0][0][1] = 0;
            q.push(state{0,i,j,0,0,1});
        }
        if(s[i][j] == 'G'){
            gy = i, gx = j;
        }
    }
    while(!q.empty()){
        state t = q.front(); q.pop();
        rep(i,4){
            if((i+2)%4 == t.dir) continue;
            if(s[t.y][t.x] == 'S' && i != t.dir) continue;
            int ny = t.y + dy[i];
            int nx = t.x + dx[i];
            if(!in(ny,nx,n,m) || s[ny][nx] == '#') continue;
            int np = t.p + (i!=t.dir && dy[i]*dx[t.dir] + dx[i]*dy[t.dir] > 0);
            int nq = t.q + (i!=t.dir && dy[i]*dx[t.dir] + dx[i]*dy[t.dir] < 0);
            state nxt = {t.c+(i!=t.dir),ny,nx,np,nq,i};
            if(s[nxt.y][nxt.x] == 'S' && i == 3) continue;
            if(nxt.p > a || nxt.q > a) continue;
            if(chmin(d[nxt.y][nxt.x][nxt.p][nxt.q][nxt.dir], nxt.c)){
                q.push(nxt);
            }
        }
    }
    int ans = inf;
    rep(i,a+1) rep(j,a+1) rep(k,4) chmin(ans, d[gy][gx][i][j][k]);
    if(ans == inf) ans = -1;
    cout << ans << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 21600
final_rank: 8

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

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

struct P{
  int y,x,di,p,q,F;
};
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
bool used[100][100][4][100];
struct PP{
  int y,x,di,p,q;
};
//PP AA[30];

int main(){
  /*
  AA[0]={1,0,0,9,9};
  AA[1]={1,1,1,8,9};
  AA[2]={2,1,0,7,9};
  AA[3]={3,1,0,7,9};
  AA[4]={3,0,3,7,8};
  AA[5]={4,0,0,7,7};
  AA[6]={5,0,0,7,7};
  AA[7]={5,1,1,6,7};
  AA[8]={5,2,1,6,7};
  AA[9]={5,3,1,6,7};
  AA[10]={4,3,2,6,6};
  AA[11]={3,3,2,6,6};
  AA[12]={3,4,1,6,5};
  AA[13]={3,5,1,6,5};
  AA[14]={2,5,2,6,4};
  AA[15]={1,5,2,6,4};
  AA[16]={1,6,1,6,3};
  AA[17]={1,7,1,6,3};
  AA[18]={1,8,1,6,3};
  AA[19]={2,8,0,5,3};
  AA[20]={3,8,0,5,3};
  AA[21]={4,8,0,5,3};
  AA[22]={5,8,0,5,3};
  AA[23]={6,8,0,5,3};
  AA[24]={7,8,0,5,3};
  AA[25]={8,8,0,5,3};
  AA[26]={8,7,3,4,3};
  AA[27]={8,6,3,4,3};
  AA[28]={8,5,3,4,3};
  AA[29]={8,4,3,4,3};*/

  int n,m,a;cin>>n>>m>>a;
  vector<string> s(n);
  REP(i,n)cin>>s[i];
  deque<P> que;
  int sy,sx;
  REP(i,n)REP(j,m)if(s[i][j]=='S')que.push_front({i+1,j,0,a,a,-1}),sy=i,sx=j;
  if(sy==n-1||s[sy+1][sx]=='#'){
    cout<<-1<<endl;return 0;
  }
  int ans=1e9;
  while(que.size()){
    P p=que.front();que.pop_front();
    if(p.p<0||p.q<0)continue;
    if(p.x==sx&&p.y>=sy-1&&p.y<=p.F&&p.di==2)continue;
    if(s[p.y][p.x]=='G')ans=min(ans,a-p.p+a-p.q);
    //REP(ii,30)if(AA[ii].y==p.y&&AA[ii].x==p.x&&AA[ii].di==p.di&&AA[ii].p==p.p&&AA[ii].q==p.q)cout<<p.y<<" "<<p.x<<" "<<p.di<<" "<<p.p<<" "<<p.q<<endl;
    //if(p.y==6&&p.x==4&&p.di==2)cout<<p.y<<" "<<p.x<<" "<<p.di<<" "<<p.p<<" "<<p.q<<endl;
    //if(p.y==6&&p.x==5&&p.di==1)cout<<p.y<<" "<<p.x<<" "<<p.di<<endl;
    REP(k,4){
      int Y=p.y+dy[k],X=p.x+dx[k];
      if(Y<0||Y>=n||X<0||X>=m||s[Y][X]=='#')continue;
      //if(p.y==3&&p.x==5&&p.di==1&&k==2)cout<<"OK"<<endl;
      if(p.di==k){
        que.push_front({Y,X,k,p.p,p.q,p.F});
        used[Y][X][k][p.F+1]=true;
        continue;
      }
      if(abs(p.di-k)==2)continue;
      if(((p.di*k)==0&&(p.di+k)==1)||((p.di*k)==6&&(p.di+k)==5)){
        if(!p.p)continue;
        //bool out=false;
        //for(int pp=p.p-1;pp<=a;pp++)for(int qq=p.q;qq<=a;qq++)if(used[Y][X][k][pp][qq][p.F+1])out=true;
        //if(out)continue;
        if(used[Y][X][k][(~p.F?p.F:Y)+1])continue;
        que.push_back({Y,X,k,p.p-1,p.q,(~p.F?p.F:Y)});
        used[Y][X][k][(~p.F?p.F:Y)+1]=true;
      }
      else{
        //if(p.y==3&&p.x==5&&p.di==1&&k==2)cout<<"OK"<<p.p<<" "<<p.q<<endl;
        if(!p.q)continue;
        //bool out=false;
        //for(int pp=p.p;pp<=a;pp++)for(int qq=p.q-1;qq<=a;qq++)if(used[Y][X][k][pp][qq][p.F+1])out=true;
        //if(out)continue;
        //if(p.y==3&&p.x==5&&p.di==1&&k==2)cout<<"YEAH"<<endl;
        if(used[Y][X][k][(~p.F?p.F:Y)+1])continue;
        que.push_back({Y,X,k,p.p,p.q-1,(~p.F?p.F:Y)});
        used[Y][X][k][(~p.F?p.F:Y)+1]=true;
      }
      //used[Y][X][k]=true;
    }
  }/*
  REP(k,4){
    REP(i,n){
      REP(j,m){
        bool tmp=0;
        REP(aa,11)REP(bb,11)REP(tt,105)tmp|=used[i][j][k][aa][bb][tt];
        cout<<tmp;
      }
      cout<<endl;
    }
    cout<<endl;
  }*/
  if(ans>1e8)cout<<-1<<endl;
  else cout<<ans<<endl;
}
accuracy: 0.9340659340659341
time_ms: 20
memory_kb: 6392
final_rank: 19

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

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

struct P{
  int y,x,di,p,q,F;
};
int dx[4]={0,1,0,-1},dy[4]={1,0,-1,0};
bool used[100][100][4][11][11][100];

signed main(){
  int n,m,a;cin>>n>>m>>a;
  vector<string> s(n);
  REP(i,n)cin>>s[i];
  queue<P> que;
  int sy,sx;
  REP(i,n)REP(j,m)if(s[i][j]=='S')que.push({i+1,j,0,a,a,-1}),sy=i,sx=j;
  int ans=1e9;
  while(que.size()){
    P p=que.front();que.pop();
    if(p.p<0||p.q<0)continue;
    if(p.x==sx&&p.y>=sy-1&&p.y<=p.F&&p.di==2)continue;
    if(s[p.y][p.x]=='G')ans=min(ans,a-p.p+a-p.q);
    REP(k,4){
      int Y=p.y+dy[k],X=p.x+dx[k];
      if(Y<0||Y>=n||X<0||X>=m||s[Y][X]=='#')continue;
      if(p.di==k)que.push({Y,X,k,p.p,p.q,p.F});
      if(abs(p.di-k)==2)continue;
      if((p.di*k==0&&p.di+k==1)||(p.di*k==6&&p.di+k==5)){
        if(!p.p)continue;
        bool out=false;
        REP(pp,p.p)REP(qq,p.q+1)if(used[Y][X][k][pp][qq][p.F+1])out=true;
        if(out)continue;
        que.push({Y,X,k,p.p-1,p.q,(~p.F?p.F:Y)});
        used[Y][X][k][p.p-1][p.q][(~p.F?p.F:Y)+1]=true;
      }
      else{
        if(!p.q)continue;
        bool out=false;
        REP(pp,p.p+1)REP(qq,p.q)if(used[Y][X][k][pp][qq][p.F+1])out=true;
        if(out)continue;
        que.push({Y,X,k,p.p,p.q-1,(~p.F?p.F:Y)});
        used[Y][X][k][p.p][p.q-1][(~p.F?p.F:Y)+1]=true;
      }
      //used[Y][X][k]=true;
    }
  }
  if(ans>1e8)cout<<-1<<endl;
  else cout<<ans<<endl;
}
accuracy: 0.0989010989010989
time_ms: 10
memory_kb: 24500
final_rank: 20

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

int main() {
    int N, M, A;
    cin >> N >> M >> A;
    vector<string> G(N);
    int gx, gy, sx, sy;
    for (int i = 0; i < N; i++) {
        cin >> G[i];
        for (int j = 0; j < M; j++) {
            if (G[i][j] == 'S')
                sx = i, sy = j;
            if (G[i][j] == 'G')
                gx = i, gy = j;
        }
    }

    vector memo(N, vector(M, vector(4, vector(A + 1, vector(A + 1, false)))));
    vector seen(N, vector(M, vector(4, vector(A + 1, vector(A + 1, false)))));
    int dx[4] = {1, 0, -1, 0}, dy[4] = {0, -1, 0, 1};
    auto check = [&](int x, int y, int dir) {
        if (x < 0 || x >= N || y < 0 || y >= M || G[x][y] == '#')
            return false;
        if (G[x][y] == 'S' && dir == 2)
            return false;
        return true;
    };
    struct T {
        int x, y, dir, P, Q;
    };
    auto check_T = [&](T t) {
        return check(t.x, t.y, t.dir) && t.P >= 0 && t.Q >= 0;
    };
    deque<T> que;
    que.push_front({sx, sy, 0, A, A});
    seen[sx][sy][0][A][A] = 1;
    while (!que.empty()) {
        auto now = que.front();
        que.pop_front();
        int &x = now.x, &y = now.y, &dir = now.dir, &P = now.P, &Q = now.Q;
        int nxt_x = x + dx[dir], nxt_y = y + dy[dir];
        if (check(nxt_x, nxt_y, dir)) {
            if (!seen[nxt_x][nxt_y][dir][P][Q]) {
                seen[nxt_x][nxt_y][dir][P][Q] = true;
                que.push_front({nxt_x, nxt_y, dir, P, Q});
            }
            if (G[nxt_x][nxt_y] == 'S')
                continue;
            for (int i = 1; i <= 3; i += 2) {
                int nxt_dir = (dir + i) % 4;
                T nxt{nxt_x, nxt_y, nxt_dir, P, Q};
                if (dir + nxt_dir == 3)
                    nxt.P--;
                else
                    nxt.Q--;
                if (check_T(nxt)) {
                    if (!seen[nxt.x][nxt.y][nxt.dir][nxt.P][nxt.Q]) {
                        seen[nxt.x][nxt.y][nxt.dir][nxt.P][nxt.Q] = true;
                        que.push_back(nxt);
                    }
                }
            }
        }
    }

    int ans = 100;
    for (int dir = 0; dir < 4; dir++) {
        for (int i = 0; i <= A; i++) {
            for (int j = 0; j <= A; j++) {
                if (seen[gx][gy][dir][i][j])
                    ans = min(ans, A * 2 - i - j);
            }
        }
    }
    cout << (ans == 100 ? -1 : ans) << endl;
}
accuracy: 1
time_ms: 40
memory_kb: 40172
final_rank: 14

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

using ll = long long;
using PII = pair<ll, ll>;

#define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(x) x.begin(), x.end()
#define POPCOUNT(x) __builtin_popcount(x)
template <typename T> void chmin(T &a, const T &b) { a = min(a, b); }
template <typename T> void chmax(T &a, const T &b) { a = max(a, b); }

const ll INF = 1LL << 60;

struct FastIO {
    FastIO() {
        cin.tie(0);
        ios::sync_with_stdio(0);
    }
} fastiofastio;

using State = tuple<int, int, int, int, int>;

char maze[100][101];
int dist[100][100][4][11][11];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};

int main() {
    int N, M, A;
    cin >> N >> M >> A;
    int sx, sy;
    int gx, gy;
    for (int i = 0; i < N; i++) {
        cin >> maze[i];
        for (int j = 0; j < M; j++) {
            if (maze[i][j] == 'S')
                sx = j, sy = i;
            if (maze[i][j] == 'G')
                gx = j, gy = i;
        }
    }
    fill((int *)dist, (int *)(dist + M), 1 << 30);
    dist[sx][sy][1][0][0] = 0;
    deque<State> que;
    que.emplace_back(sx, sy, 1, 0, 0);
    while (!que.empty()) {
        State now = que.front();
        que.pop_front();
        int x = get<0>(now);
        int y = get<1>(now);
        int dir = get<2>(now);
        int p = get<3>(now);
        int q = get<4>(now);
        int nx = x + dx[dir];
        int ny = y + dy[dir];
        if (0 > nx || nx >= M || 0 > ny || ny >= N || maze[ny][nx] == '#')
            continue;
        if (x == sx && y == sy && dir == 3)
            continue;
        if (dist[nx][ny][dir][p][q] > dist[x][y][dir][p][q]) {
            dist[nx][ny][dir][p][q] = dist[x][y][dir][p][q];
            que.emplace_front(nx, ny, dir, p, q);
        }
        int ndir;
        // Pを置く
        if (dir <= 1)
            ndir = 1 - dir;
        else
            ndir = 5 - dir;
        if (p + 1 <= A &&
            dist[nx][ny][ndir][p + 1][q] > dist[x][y][dir][p][q] + 1) {
            dist[nx][ny][ndir][p + 1][q] = dist[x][y][dir][p][q] + 1;
            que.emplace_back(nx, ny, ndir, p + 1, q);
        }
        // Qを置く
        ndir = 3 - dir;
        if (q + 1 <= A &&
            dist[nx][ny][ndir][p][q + 1] > dist[x][y][dir][p][q] + 1) {
            dist[nx][ny][ndir][p][q + 1] = dist[x][y][dir][p][q] + 1;
            que.emplace_back(nx, ny, ndir, p, q + 1);
        }
    }
    int ans = 1 << 30;
    for (int i = 0; i < 4; i++)
        for (int j = 0; j <= A; j++)
            for (int k = 0; k <= A; k++)
                ans = min(ans, dist[gx][gy][i][j][k]);
    if (ans == 1 << 30)
        cout << -1 << endl;
    else
        cout << ans << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 22564
final_rank: 9

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-8, PI = acos(-1);
//ここから編集    
typedef string::const_iterator State;
int H, W, A;
vector<string> f(110);
bool can_pass(int y, int x){
    return (y>=0 && y < H && x >= 0 && x < W && f[y][x] != '#');
}
ll dp[110][110][5][15][15];
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(6);

    
    cin >> H >> W >> A;

    
    int sy, sx;
    int gy, gx;
    REP(i,H) {
        cin >> f[i];
        REP(j, f[i].size()){
            if(f[i][j] == 'S'){
                sy = i, sx = j;
            }
            if(f[i][j] == 'G'){
                gy = i, gx = j;
            }
        }
    }
    REP(i,H) REP(j,W) REP(k,A+1) REP(l,A+1) REP(m,5) dp[i][j][m][k][l] = INT_MAX;

    dp[sy][sx][2][0][0] = 0;
    queue<pair<int, pair<int, pair<int, int>>>> q;
    q.push(make_pair(sy*W+sx, make_pair(2, make_pair(0, 0))));

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

        int y = p.first/W, x = p.first%W;
        int dir = p.second.first;
        int a,b;
        tie(a, b) = p.second.second;

        if(dir == 0){
            int ny = y-1, nx = x;
            
            if(can_pass(ny, nx) && f[ny][nx] != 'S' && dp[ny][nx][0][a][b] > dp[y][x][dir][a][b]){
                
                dp[ny][nx][0][a][b] = dp[y][x][dir][a][b];
                q.push(make_pair(ny*W+nx, make_pair(0, make_pair(a, b))));
            }
            ny = y, nx = x+1;
            if(can_pass(ny, nx) && f[y][x] != 'S' && b+1 <= A && dp[ny][nx][1][a][b+1] > dp[y][x][dir][a][b] + 1){
                dp[ny][nx][1][a][b+1] = dp[y][x][dir][a][b] + 1;
                q.push(make_pair(ny*W+nx, make_pair(1, make_pair(a, b+1))));
            }
            ny = y, nx = x-1;
            if(can_pass(ny, nx) && f[y][x] != 'S' && a+1 <= A && dp[ny][nx][3][a+1][b] > dp[y][x][dir][a][b] + 1){
                dp[ny][nx][3][a+1][b] = dp[y][x][dir][a][b] + 1;
                q.push(make_pair(ny*W+nx, make_pair(3, make_pair(a+1, b))));
            }
        }else if(dir == 1){
            int ny = y-1, nx = x;
            if(can_pass(ny, nx) && f[ny][nx] != 'S' && b+1<=A && dp[ny][nx][0][a][b+1] > dp[y][x][dir][a][b] + 1){
                dp[ny][nx][0][a][b+1] = dp[y][x][dir][a][b] + 1;
                q.push(make_pair(ny*W+nx, make_pair(0, make_pair(a, b+1))));
            }
            ny = y, nx = x+1;
            if(can_pass(ny, nx) && dp[ny][nx][1][a][b] > dp[y][x][dir][a][b]){
                dp[ny][nx][1][a][b] = dp[y][x][dir][a][b];
                q.push(make_pair(ny*W+nx, make_pair(1, make_pair(a, b))));
            }
            ny = y+1, nx = x;
            if(can_pass(ny, nx) && f[y][x] != 'S' && a+1 <= A && dp[ny][nx][2][a+1][b] > dp[y][x][dir][a][b] + 1){
                dp[ny][nx][2][a+1][b] = dp[y][x][dir][a][b] + 1;
                q.push(make_pair(ny*W+nx, make_pair(2, make_pair(a+1, b))));
            }
        }else if(dir == 2){
            int ny = y+1, nx = x;
            if(can_pass(ny, nx) && dp[ny][nx][2][a][b] > dp[y][x][dir][a][b]){
                dp[ny][nx][2][a][b] = dp[y][x][dir][a][b];
                q.push(make_pair(ny*W+nx, make_pair(2, make_pair(a, b))));
            }

            ny = y, nx = x+1;
            if(can_pass(ny, nx) && f[y][x] != 'S' && a+1 <= A && dp[ny][nx][1][a+1][b] > dp[y][x][dir][a][b] + 1){
                dp[ny][nx][1][a+1][b] = dp[y][x][dir][a][b] + 1;
                q.push(make_pair(ny*W+nx, make_pair(1, make_pair(a+1, b))));
            }
            ny = y, nx = x-1;
            if(can_pass(ny, nx) && f[y][x] != 'S' && b+1 <= A && dp[ny][nx][3][a][b+1] > dp[y][x][dir][a][b] + 1){
                dp[ny][nx][3][a][b+1] = dp[y][x][dir][a][b] + 1;
                q.push(make_pair(ny*W+nx, make_pair(3, make_pair(a, b+1))));
            }
        }else{
            int ny = y-1, nx = x;
            if(can_pass(ny, nx) && f[y][x] != 'S' && f[ny][nx] != 'S' && a+1<=A && dp[ny][nx][0][a+1][b] > dp[y][x][dir][a][b]){
                dp[ny][nx][0][a+1][b] = dp[y][x][dir][a][b] + 1;
                q.push(make_pair(ny*W+nx, make_pair(0, make_pair(a+1, b))));
            }
            ny = y+1, nx = x;
            if(can_pass(ny, nx) && f[y][x] != 'S' && b+1 <= A && dp[ny][nx][2][a][b+1] > dp[y][x][dir][a][b] + 1){
                dp[ny][nx][2][a][b+1] = dp[y][x][dir][a][b] + 1;
                q.push(make_pair(ny*W+nx, make_pair(2, make_pair(a, b+1))));
            }
            ny = y, nx = x-1;
            if(can_pass(ny, nx)  && dp[ny][nx][3][a][b] > dp[y][x][dir][a][b]){
                dp[ny][nx][3][a][b] = dp[y][x][dir][a][b];
                q.push(make_pair(ny*W+nx, make_pair(3, make_pair(a, b))));
            }
        }
    }

    ll ans = INT_MAX;
    for(int i=0; i<4; i++){
        for(int j=0; j<=A; j++){
            for(int k=0; k<=A; k++){
                ans = min(ans, dp[gy][gx][i][j][k]);
            }
        }
    }
    if(ans == INT_MAX) ans = -1;
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 74572
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
vector<int> dy = {1, 0, -1, 0};
vector<int> dx = {0, 1, 0, -1};
vector<int> p = {1, 0, 3, 2};
vector<int> q = {3, 2, 1, 0};
int main(){
  int N, M, A;
  cin >> N >> M >> A;
  vector<vector<char>> c(N + 2, vector<char>(M + 2, '#'));
  for (int i = 1; i <= N; i++){
    for (int j = 1; j <= M; j++){
      cin >> c[i][j];
    }
  }
  int sy, sx;
  for (int i = 1; i <= N; i++){
    for (int j = 1; j <= M; j++){
      if (c[i][j] == 'S'){
        sy = i;
        sx = j;
      }
    }
  }
  set<tuple<int, int, int, int, int>> st;
  deque<tuple<int, int, int, int, int>> dq;
  dq.push_back(make_tuple(0, 0, sy, sx, 0));
  int ans = -1;
  while (!dq.empty()){
    tuple<int, int, int, int, int> T = dq.front();
    dq.pop_front();
    if (!st.count(T)){
      st.insert(T);
      int cnt1 = get<0>(T);
      int cnt2 = get<1>(T);
      int y = get<2>(T);
      int x = get<3>(T);
      int d = get<4>(T);
      if (c[y][x] == 'G'){
        ans = cnt1 + cnt2;
        break;
      }
      if (c[y][x] != 'S'){
        if (cnt1 < A){
          int d2 = p[d];
          int y2 = y + dy[d2];
          int x2 = x + dx[d2];
          if (c[y2][x2] != '#' && !(c[y2][x2] == 'S' && d2 == 2)){
            tuple<int, int, int, int, int> T2 = make_tuple(cnt1 + 1, cnt2, y2, x2, d2);
            if (!st.count(T2)){
              dq.push_back(T2);
            }
          }
        }
        if (cnt2 < A){
          int d2 = q[d];
          int y2 = y + dy[d2];
          int x2 = x + dx[d2];
          if (c[y2][x2] != '#' && !(c[y2][x2] == 'S' && d2 == 2)){
            tuple<int, int, int, int, int> T2 = make_tuple(cnt1, cnt2 + 1, y2, x2, d2);
            if (!st.count(T2)){
              dq.push_back(T2);
            }
          }
        }
      }
      int y2 = y + dy[d];
      int x2 = x + dx[d];
      if (c[y2][x2] != '#' && !(c[y2][x2] == 'S' && d == 2)){
        tuple<int, int, int, int, int> T2 = make_tuple(cnt1, cnt2, y2, x2, d);
        if (!st.count(T2)){
          dq.push_front(T2);
        }
      }
    }
  }
  cout << ans << endl;
}
accuracy: 1
time_ms: 30
memory_kb: 8060
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=1000000007,MAX=105,INF=1<<30;
int H,W,K,sh,sw,gh,gw;
char S[MAX][MAX];
short can[MAX][MAX][MAX][11][4];

vector<int> dh={0,1,0,-1},dw={1,0,-1,0};

struct dat{
    int h;
    int w;
    int x;
    int b;
    int dir;
};

void BFS(){
    deque<dat> deq;
    can[sh][sw][H+1][0][1]=0;
    deq.push_front({sh,sw,H+1,0,1});
    
    while(!deq.empty()){
        auto u=deq.front();deq.pop_front();
        int h=u.h,w=u.w,x=u.x,b=u.b,dir=u.dir;
        if(h<0||h>=H||w<0||w>=W) continue;
        short a=can[h][w][x][b][dir];
        if(a>K||b>K) continue;
        if(S[h][w]=='#') continue;
        if((a||b)&&x==H+1) continue;
        if(w==sw&&x!=H+1&&sh<=h&&h<=x&&dir==3) continue;
        
        if(h+dh[dir]>=0&&w+dw[dir]>=0&&chmin(can[h+dh[dir]][w+dw[dir]][x][b][dir],a)) deq.push_front({h+dh[dir],w+dw[dir],x,b,dir});
        
        if(h==sh&&w==sw) continue;
        if(h==gh&&w==gw) continue;
        
        for(int k=0;k<4;k++){
            if((k&1)==(dir&1)) continue;
            
            if(dir/2==k/2){
                if(x==H+1&&w==sw){
                    if(chmin(can[h][w][h][b][k],short(a+1))){
                        deq.push_back({h,w,h,b,k});
                    }
                }else{
                    if(chmin(can[h][w][x][b][k],short(a+1))){
                        deq.push_back({h,w,x,b,k});
                    }
                }
            }
            else{
                if(x==H+1&&w==sw){
                    if(chmin(can[h][w][h][b+1][k],short(a))){
                        deq.push_front({h,w,h,b+1,k});
                    }
                }else{
                    if(chmin(can[h][w][x][b+1][k],short(a))){
                        deq.push_front({h,w,x,b+1,k});
                    }
                }
            }
        }
    }
}

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    cin>>H>>W>>K;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            cin>>S[i][j];
            if(S[i][j]=='S'){
                sh=i;
                sw=j;
            }
            if(S[i][j]=='G'){
                gh=i;
                gw=j;
            }
        }
    }
    
    for(int i=0;i<=H;i++){
        for(int j=0;j<=W;j++){
            for(int k=0;k<=H+1;k++){
                for(int b=0;b<11;b++){
                    for(int l=0;l<4;l++){
                        can[i][j][k][b][l]=100;
                    }
                }
            }
        }
    }
    
    BFS();
    
    int ans=INF;
    
    for(int k=0;k<=H+1;k++){
        for(int b=0;b<=K;b++){
            for(int l=0;l<4;l++){
                if(can[gh][gw][k][b][l]<=K){
                    chmin(ans,b+can[gh][gw][k][b][l]);
                }
            }
        }
    }
    
    if(ans>2*K) ans=-1;
    
    cout<<ans<<endl;
}
accuracy: 1
time_ms: 20
memory_kb: 78216
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=1000000007,MAX=105,INF=1<<30;
int H,W,K,sh,sw,gh,gw;
char S[MAX][MAX];
short can[MAX][MAX][MAX][11][4];

vector<int> dh={0,1,0,-1},dw={1,0,-1,0};

struct dat{
    int h;
    int w;
    int x;
    int b;
    int dir;
};

void BFS(){
    deque<dat> deq;
    can[sh][sw][H+1][0][1]=0;
    deq.push_front({sh,sw,H+1,0,1});
    
    while(!deq.empty()){
        auto u=deq.front();deq.pop_front();
        int h=u.h,w=u.w,x=u.x,b=u.b,dir=u.dir;
        if(h<0||h>=H||w<0||w>=W) continue;
        short a=can[h][w][x][b][dir];
        if(a>K||b>K) continue;
        if(S[h][w]=='#') continue;
        if((a||b)&&x==H+1) continue;
        if(w==sw&&x!=H+1&&sh<=h&&h<=x&&dir==3) continue;
        
        if(h+dh[dir]>=0&&w+dw[dir]>=0&&chmin(can[h+dh[dir]][w+dw[dir]][x][b][dir],a)) deq.push_front({h+dh[dir],w+dw[dir],x,b,dir});
        
        if(h==sh&&w==sw) continue;
        if(h==gh&&w==gw) continue;
        
        for(int k=0;k<4;k++){
            if((k&1)==(dir&1)) continue;
            
            if(dir/2==k/2){
                if(x==H+1&&w==sw){
                    if(chmin(can[h][w][h][b][k],short(a+1))){
                        deq.push_back({h,w,h,b,k});
                        //cout<<h<<" "<<w<<endl;
                    }
                }else{
                    if(chmin(can[h][w][x][b][k],short(a+1))){
                        deq.push_back({h,w,x,b,k});
                        //cout<<h<<" "<<w<<endl;
                    }
                }
            }
            else{
                if(x==H+1&&w==sw){
                    if(chmin(can[h][w][h][b+1][k],short(a))){
                        deq.push_front({h,w,h,b+1,k});
                        //cout<<h<<" "<<w<<endl;
                    }
                }else{
                    if(chmin(can[h][w][x][b+1][k],short(a))){
                        deq.push_front({h,w,x,b+1,k});
                        //cout<<h<<" "<<w<<endl;
                    }
                }
            }
        }
    }
}

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    cin>>H>>W>>K;
    for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
            cin>>S[i][j];
            if(S[i][j]=='S'){
                sh=i;
                sw=j;
            }
            if(S[i][j]=='G'){
                gh=i;
                gw=j;
            }
        }
    }
    
    for(int i=0;i<=H;i++){
        for(int j=0;j<=W;j++){
            for(int k=0;k<=H+1;k++){
                for(int b=0;b<11;b++){
                    for(int l=0;l<4;l++){
                        can[i][j][k][b][l]=100;
                    }
                }
            }
        }
    }
    
    BFS();
    
    int ans=INF;
    
    /*for(int h=0;h<H;h++){
        for(int w=0;w<W;w++){
            for(int k=0;k<=H+1;k++){
                for(int b=0;b<=K;b++){
                    for(int l=0;l<4;l++){
                        if(can[h][w][k][b][l]<=K){
                            //chmin(ans,b+can[h][w][k][b][l]);
                            if(b==0&&can[h][w][k][b][l]==0) cout<<h<<" "<<w<<" "<<k<<" "<<b<<" "<<l<<" "<<can[h][w][k][b][l]<<endl;
                        }
                    }
                }
            }
        }
    }*/
    
    for(int k=0;k<=H+1;k++){
        for(int b=0;b<=K;b++){
            for(int l=0;l<4;l++){
                if(can[gh][gw][k][b][l]<=K){
                    chmin(ans,b+can[gh][gw][k][b][l]);
                    //cout<<k<<" "<<b<<" "<<l<<" "<<can[gh][gw][k][b][l]<<endl;
                }
            }
        }
    }
    
    if(ans>2*K) ans=-1;
    
    cout<<ans<<endl;
}
accuracy: 1
time_ms: 20
memory_kb: 78096
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using P = pair<int, int>;
const double eps = 1e-8;
const ll MOD = 1000000007;
const int INF = INT_MAX / 2;
const ll LINF = LLONG_MAX / 2;
template <typename T1, typename T2>
bool chmax(T1 &a, const T2 &b) {
  if(a < b) {a = b; return true;}
  return false;
}
template <typename T1, typename T2>
bool chmin(T1 &a, const T2 &b) {
  if(a > b) {a = b; return true;}
  return false;
}
template<typename T1, typename T2>
ostream& operator<<(ostream &os, const pair<T1, T2> p) {
  os << p.first << ":" << p.second;
  return os;
}
template<class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for(int i=0;i<((int)(v.size()));++i) {
    if(i) os << " ";
    os << v[i];
  }
  return os;
}
struct None{};
struct Elm {
  int r, c, p, q, dir;
};
int n, m, a;
vi dr = {1, 0, -1, 0};
vi dc = {0, -1, 0, 1};
vector<vector<vector<vector<vector<bool>>>>> dp;
void dfs(int r, int c, int p, int q, int dir, vector<vector<char>> &g, vector<vector<bool>> &sel) {
  if(dp[r][c][p][q][dir]) return;
  dp[r][c][p][q][dir] = true;
  int nr = r + dr[dir], nc = c + dc[dir];
  if(0 <= nr && nr < n && 0 <= nc && nc < m && g[nr][nc] != '#') {
    bool psel = sel[r][c];
    sel[r][c] = true;
    dfs(nr, nc, p, q, dir, g, sel);
    sel[r][c] = psel;
  }
  if(g[r][c] != 'S' && ((dir%2 && q < a) || (!(dir%2) && p < a))) {
    int ndir = (dir + 3) % 4;
    int nr = r + dr[ndir], nc = c + dc[ndir];
    int np = p + !(dir%2);
    int nq = q + dir%2;
    if(0 <= nr && nr < n && 0 <= nc && nc < m && g[nr][nc] != '#' && !sel[r][c]) {
      bool psel = sel[r][c];
      sel[r][c] = true;
      char prev = g[r][c];
      g[r][c] = '#';
      dfs(nr, nc, np, nq, ndir, g, sel);
      g[r][c] = prev;
      sel[r][c] = psel;
    }
  }
  if(g[r][c] != 'S' && ((dir%2 && p < a) || (!(dir%2) && q < a))) {
    int ndir = (dir + 1) % 4;
    int nr = r + dr[ndir], nc = c + dc[ndir];
    int np = p + dir%2;
    int nq = q + !(dir%2);
    if(0 <= nr && nr < n && 0 <= nc && nc < m && g[nr][nc] != '#' && !sel[r][c]) {
      bool psel = sel[r][c];
      sel[r][c] = true;
      char prev = g[r][c];
      g[r][c] = '#';
      dfs(nr, nc, np, nq, ndir, g, sel);
      g[r][c] = prev;
      sel[r][c] = psel;
    }
  }
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(10);
  cin >> n >> m >> a;
  vector<vector<char>> g(n, vector<char>(m));
  P st = {-1, -1}, gl = {-1, -1};
  for(int i=0;i<(n);++i) {
    for(int j=0;j<(m);++j) {
      cin >> g[i][j];
      if(g[i][j] == 'S') {
        st = {i, j};
      }
      if(g[i][j] == 'G') {
        gl = {i, j};
      }
    }
  }
  dp.resize(n,
    vector<vector<vector<vector<bool>>>>(m,
      vector<vector<vector<bool>>>(a+1,
        vector<vector<bool>>(a+1,
          vector<bool>(4, false)))));
  vector<vector<bool>> sel(n, vector<bool>(m));
  dfs(st.first, st.second, 0, 0, 0, g, sel);
  int mi = INF;
  for(int i=0;i<(a+1);++i) {
    for(int j=0;j<(a+1);++j) {
      for(int k=0;k<(4);++k) {
        if(dp[gl.first][gl.second][i][j][k]) chmin(mi, i+j);
      }
    }
  }
  cout << (mi == INF ? -1 : mi) << endl;
}
accuracy: 1
time_ms: 80
memory_kb: 48564
final_rank: 18

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

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

// std::vector Declaration
template<typename T>
vector<T> make_v(size_t a) { return vector<T>(a); }
template<typename T, typename... Ts>
auto make_v(size_t a, Ts... ts) {
    return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));
}

// std::vector Declaration and Initialization
template<typename T>
vector<T> make_vector(size_t a, T x) { return vector<T>(a, x); }
template<typename T, typename U, typename... Ts>
auto make_vector(size_t a, U b, Ts... ts) {
    return vector<decltype(make_vector<T>(b,ts...))>(a, make_vector<T>(b, ts...));
}

// std::vector Input
template<typename T>
istream& operator>>(istream& is, vector<T>& v) {
    for (auto &e : v) is >> e;
    return is;
}

// std::vector Debug
template<typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    os << "[";
    bool a = 1;
    for (auto e : v) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "]";
    return os;
}

// std::array Debug
template<typename T, size_t n>
ostream& operator<<(ostream& os, const array<T, n>& v) {
    os << "[";
    bool a = 1;
    for (auto e : v) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "]";
    return os;
}

// std::deque Debug
template<typename T>
ostream& operator<<(ostream& os, const deque<T>& d) {
    os << "[";
    bool a = 1;
    for (auto e : d) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "]";
    return os;
}

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

// std::set Debug
template<typename T>
ostream& operator<<(ostream& os, const set<T>& st) {
    os << "{";
    bool a = 1;
    for (auto e : st) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "}";
    return os;
}

// std::multiset Debug
template<typename T>
ostream& operator<<(ostream& os, const multiset<T>& st) {
    os << "{";
    bool a = 1;
    for (auto e : st) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "}";
    return os;
}

// std::map Debug
template<typename T, typename U>
ostream& operator<<(ostream& os, const map<T, U>& mp) {
    os << "{";
    bool a = 1;
    for (auto e : mp) {
        os << (a ? "" : " ");
        os << e.first << ":" << e.second;
        a = 0;
    }
    os << "}";
    return os;
}

// std::tuple Debug
template<int N, class Tuple>
void out(ostream& os, const Tuple& t){}
template<int N, class Tuple, class H, class ...Ts>
void out(ostream& os, const Tuple& t) {
    if (N) os << " ";
    os << get<N>(t);
    out<N+1,Tuple,Ts...>(os, t);
}
template<class ...Ts>
ostream& operator<<(ostream& os, const tuple<Ts...>& t) {
    os << "(";
    out<0,tuple<Ts...>,Ts...>(os, t);
    os << ")";
    return os;
}

// Debug
#define DUMP(x) cerr<<#x<<" = "<<(x)<<endl

// Weighted edge
template<typename T>
struct edge {
    int src, to;
    T cost;

    edge() {}
    edge(int to, T cost) : src(-1), to(to), cost(cost) {}
    edge(int src, int to, T cost) : src(src), to(to), cost(cost) {}

    friend ostream& operator<<(ostream& os, const edge& e) {
        return os << "(" << e.src << "->" << e.to << ":" << e.cost << ")";
    }
};

using LL = int64_t;

#define fs first
#define sc second

const int64_t MOD = 1e9+7;


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

    int n, m, a; cin >> n >> m >> a;
    vector<string> s(n);
    int si, sj, gi, gj;
    for (int i = 0; i < n; ++i) {
        cin >> s[i];
        for (int j = 0; j < m; ++j) {
            if (s[i][j] == 'S') si = i, sj = j;
            if (s[i][j] == 'G') gi = i, gj = j;
        }
    }

    if (n <= si+1 or s[si+1][sj] == '#') {
        cout << -1 << endl;
        return 0;
    }

    using data = tuple<int,int,int,int,int>;

    deque<data> deq;
    deq.push_front(make_tuple(si+1,sj,0,a,a));

    map<data,bool> used;

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

    while (!deq.empty()) {
        int i, j, d, p, q;
        tie(i,j,d,p,q) = deq.front();
        deq.pop_front();

        if (i == gi and j == gj) {
            cout << 2*a - (p+q) << endl;
            return 0;
        }

        for (int k = 0; k < 4; ++k) {
            int y = i + dy[k], x = j + dx[k];
            if (y < 0 or n <= y or x < 0 or m <= x
                    or s[y][x] == '#') continue;
            if (s[y][x] == 'S' and k == 2) continue;
            if (d == k) {
                auto tp = make_tuple(y,x,d,p,q);
                if (!used[tp]) {
                    deq.push_front(tp);
                    used[tp] = true;
                }
            } else if ((d+1)%4 == k) {
                if (s[i][j] == 'S') continue;
                if (d & 1) {
                    if (q == 0) continue;
                    auto tp = make_tuple(y,x,k,p,q-1);
                    if (!used[tp]) {
                        deq.push_back(tp);
                        used[tp] = true;
                    }
                } else {
                    if (p == 0) continue;
                    auto tp = make_tuple(y,x,k,p-1,q);
                    if (!used[tp]) {
                        deq.push_back(tp);
                        used[tp] = true;
                    }
                }
            } else if ((d+3)%4 == k) {
                if (s[i][j] == 'S') continue;
                if (d & 1) {
                    if (p == 0) continue;
                    auto tp = make_tuple(y,x,k,p-1,q);
                    if (!used[tp]) {
                        deq.push_back(tp);
                        used[tp] = true;
                    }
                } else {
                    if (q == 0) continue;
                    auto tp = make_tuple(y,x,k,p,q-1);
                    if (!used[tp]) {
                        deq.push_back(tp);
                        used[tp] = true;
                    }
                }
            }
        }
    }

    cout << -1 << endl;

    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 8268
final_rank: 11

code_snippet: #define  _CRT_SECURE_NO_WARNINGS
#define _USE_MATH_DEFINES

#pragma comment (linker, "/STACK:526000000")

#include "bits/stdc++.h"

using namespace std;
typedef string::const_iterator State;
#define eps 1e-5L
#define MAX_MOD 1000000007LL
#define GYAKU 500000004LL
#define seg_size 262144LL
#define MOD 998244353LL
#define pb push_back
#define mp make_pair
typedef long long ll;
#define REP(a,b) for(long long (a) = 0;(a) < (b);++(a))
#define ALL(x) (x).begin(),(x).end()

// geometry library

typedef complex<long double> Point;
typedef pair<complex<long double>, complex<long double>> Line;

typedef struct Circle {
    complex<long double> center;
    long double r;
}Circle;

//内積、 dot(a,b) = |a||b|cos()
long double dot(Point a, Point b) {
    return (a.real() * b.real() + a.imag() * b.imag());
}
//外積、cross(a,b) = |a||b|sin()
long double cross(Point a, Point b) {
    return (a.real() * b.imag() - a.imag() * b.real());
}

//線分と点の距離
long double Dist_Line_Point(Line a, Point b) {
    if (dot(a.second - a.first, b - a.first) < eps) return abs(b - a.first);
    if (dot(a.first - a.second, b - a.second) < eps) return abs(b - a.second);
    return abs(cross(a.second - a.first, b - a.first)) / abs(a.second - a.first);
}

//線分の交差判定
int is_intersected_ls(Line a, Line b) {
    return (cross(a.second - a.first, b.first - a.first) * cross(a.second - a.first, b.second - a.first) < 0) &&
        (cross(b.second - b.first, a.first - b.first) * cross(b.second - b.first, a.second - b.first) < 0);
}

//線分の交点
Point intersection_l(Line a, Line b) {
    Point da = a.second - a.first;
    Point db = b.second - b.first;
    return a.first + da * cross(db, b.first - a.first) / cross(db, da);
}

//線分と線分の距離
long double Dist_Line_Line(Line a, Line b) {
    if (is_intersected_ls(a, b) == 1) {
        return 0;
    }
    return min({ Dist_Line_Point(a,b.first), Dist_Line_Point(a,b.second),Dist_Line_Point(b,a.first),Dist_Line_Point(b,a.second) });
}

//円と円の交点
pair<Point, Point> intersection_Circle_Circle(Circle a, Circle b) {
    long double dist = abs(a.center - b.center);
    assert(dist <= eps + a.r + b.r);
    assert(dist+eps >= abs(a.r - b.r));
    Point target = b.center - a.center;
    long double pointer = target.real() * target.real() + target.imag() * target.imag();
    long double aa = pointer + a.r * a.r - b.r * b.r;
    aa /= 2.0L;
    Point l{ (aa * target.real() + target.imag() * sqrt(pointer * a.r * a.r - aa * aa))/pointer,
            (aa* target.imag() - target.real() * sqrt(pointer * a.r * a.r - aa * aa)) / pointer};
    Point r{ (aa * target.real() - target.imag() * sqrt(pointer * a.r * a.r - aa * aa)) / pointer,
        (aa * target.imag() + target.real() * sqrt(pointer * a.r * a.r - aa * aa)) / pointer };
    r = r + a.center;
    l = l + a.center;
    return mp(l, r);
}

//end of geometry

template<typename A>
A pows(A val, ll b) {
    assert(b >= 1);
    A ans = val;
    b--;
    while (b) {
        if (b % 2) {
            ans *= val;
        }
        val *= val;
        b /= 2LL;
    }
    return ans;
}

template<typename A>
class Compressor {
public:
    bool is_zipped = false;
    map<A, ll> zipper;
    map<ll, A> unzipper;
    queue<A> fetcher;
    Compressor(){
        is_zipped = false;
        zipper.clear();
        unzipper.clear();
    }
    void add(A now) {
        assert(is_zipped == false);
        zipper[now] = 1;
        fetcher.push(now);
    }
    void exec() {
        assert(is_zipped == false);
        int cnt = 0;
        for (auto i = zipper.begin(); i != zipper.end(); ++i) {
            i->second = cnt;
            unzipper[cnt] = i->first;
            cnt++;
        }
        is_zipped = true;
    }
    ll fetch() {
        assert(is_zipped == true);
        A hoge = fetcher.front();
        fetcher.pop();
        return zipper[hoge];
    }
    ll zip(A now) {
        assert(is_zipped == true);
        assert(zipper.find(now) != zipper.end());
        return zipper[now];
    }
    A unzip(ll a) {
        assert(is_zipped == true);
        assert(a < unzipper.size());
        return unzipper[a];
    }
    ll next(A now) {
        auto x = zipper.upper_bound(now);
        if (x == zipper.end()) return zipper.size();
        return (ll)((*x).second);
    }
    ll back(A now) {
        auto x = zipper.lower_bound(now);
        if (x == zipper.begin()) return -1;
        x--;
        return (ll)((*x).second);
    }
};

template<typename A>
class Matrix {
public:
    vector<vector<A>> data;
    Matrix(vector<vector<A>> a) :data(a){

    }
    Matrix operator + (const Matrix obj) {
        vector<vector<A>> ans;
        assert(obj.data.size() == this->data.size());
        assert(obj.data[0].size() == this->data[0].size());
        REP(i, obj.data.size()) {
            ans.push_back(vector<A>());
            REP(q, obj.data[i].size()) {
                A hoge = obj.data[i][q] + (this -> data[i][q]);
                ans.back().push_back(hoge);
            }
        }
        return Matrix(ans);
    }
    Matrix operator - (const Matrix obj) {
        vector<vector<A>> ans;
        assert(obj.data.size() == this->data.size());
        assert(obj.data[0].size() == this->data[0].size());
        REP(i, obj.data.size()) {
            ans.push_back(vector<A>());
            REP(q, obj.data[i].size()) {
                A hoge = this->data[i][q] - obj.data[i][q];
                ans.back().push_back(hoge);
            }
        }
        return Matrix(ans);
    }
    Matrix operator * (const Matrix obj) {
        vector<vector<A>> ans;
        assert(obj.data.size() == this->data[0].size());
        REP(i, this -> data.size()) {
            ans.push_back(vector<A>());
            REP(q, obj.data[0].size()) {
                A hoge = (this -> data[i][0]) * (obj.data[0][q]);
                for(int t = 1;t < obj.data[i].size();++t){
                    hoge += this -> data[i][t] * obj.data[t][q];
                }
                ans.back().push_back(hoge);
            }
        }
        return Matrix(ans);
    }
    Matrix &operator *= (const Matrix obj) {
        *this = (*this * obj);
        return *this;
    }
    Matrix& operator += (const Matrix obj) {
        *this = (*this + obj);
        return *this;
    }
    Matrix& operator -= (const Matrix obj) {
        *this = (*this - obj);
        return *this;
    }
};

class modint {
public:
    using u64 = std::uint_fast64_t;
    u64 value = 0;
    u64 mod;
    modint(ll a, ll b): value(((a%b) + 2 * b) % b),mod(b) {

    }
    modint operator+(const modint rhs) const{
        return modint(*this) += rhs;
    }
    modint operator-(const modint rhs) const{
        return modint(*this) -= rhs;
    }
    modint operator*(const modint rhs) const {
        return modint(*this) *= rhs;
    }
    modint operator/(const modint rhs) const{
        return modint(*this) /= rhs;
    }
    modint& operator+=(const modint rhs) {
        assert(rhs.mod == mod);
        value += rhs.value;
        if (value >= mod) {
            value -= mod;
        }
        return *this;
    }
    modint& operator-=(const modint rhs) {
        assert(rhs.mod == mod);
        if (value < rhs.value) {
            value += mod;
        }
        value -= rhs.value;
        return *this;
    }
    modint& operator*=(const modint rhs) {
        assert(rhs.mod == mod);
        value = (value *  rhs.value) % mod;
        return *this;
    }
    modint& operator/=(modint rhs) {
        assert(rhs.mod == mod);
        ll rem = mod - 2;
        while (rem) {
            if (rem % 2) {
                *this *= rhs;
            }
            rhs *= rhs;
            rem /= 2LL;
        }
        return *this;
    }
    friend ostream& operator<<(ostream& os, modint& p) {
        os << p.value;
        return (os);
    }
};

void init() {
    iostream::sync_with_stdio(false);
    cout << fixed << setprecision(20);
}

unsigned long xor128() {
    static unsigned long x = 123456789, y = 362436069, z = 521288629, w = 88675123;
    unsigned long t = (x ^ (x << 11));
    x = y; y = z; z = w;
    return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)));
}

#define int ll
bool dp[4][100][100][11][11];
int grid[100][100];
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
int P[4] = { 1,0,3,2 };
int Q[4] = { 3,2,1,0 };
void solve(){
    int n, m, a;
    cin >> n >> m >> a;
    pair<int, int> goal;
    queue<tuple<int, int, int, int, int>> next;
    REP(i, n) {
        string s;
        cin >> s;
        REP(q, m) {
            if (s[q] == '#') {
                grid[i][q] = 1;
            }
            if (s[q] == 'S') {
                grid[i][q] = 2;
                if (i + 1 >= n) {
                    cout << -1 << endl;
                    return;
                }
                dp[0][i + 1][q][a][a] = 1;
                next.push(make_tuple(0, i + 1, q, a, a));
            }
            if (s[q] == 'G') {
                goal = mp(i, q);
            }
        }
    }
    while (next.empty() == false) {
        auto verify = [n, m](int x, int y) {
            if (x >= 0 && x < n && y >= 0 && y < m&&grid[x][y] != 1) return 1;
            return 0;
        };
        tuple<int, int, int, int, int> now = next.front();
        next.pop();
        if (grid[get<1>(now)][get<2>(now)] == 1) continue;
        if (grid[get<1>(now)][get<2>(now)] == 2 && get<0>(now) == 2) continue;
        {
            int x = get<1>(now) + dx[get<0>(now)];
            int y = get<2>(now) + dy[get<0>(now)];
            if(verify(x,y))
            if (dp[get<0>(now)][x][y][get<3>(now)][get<4>(now)] == 0) {
                dp[get<0>(now)][x][y][get<3>(now)][get<4>(now)] = 1;
                next.push(make_tuple(get<0>(now), x, y, get<3>(now), get<4>(now)));
            }
        }
        if (grid[get<1>(now)][get<2>(now)] == 2) continue;
        if (get<3>(now) > 0) {
            int t = P[get<0>(now)];
            int x = get<1>(now) + dx[t];
            int y = get<2>(now) + dy[t];
            if (verify(x, y))
                if (dp[t][x][y][get<3>(now) - 1][get<4>(now)] == 0) {
                    dp[t][x][y][get<3>(now) - 1][get<4>(now)] = 1;
                    next.push(make_tuple(t, x, y, get<3>(now) - 1, get<4>(now)));
                }
        }
        if (get<4>(now) > 0) {
            int t = Q[get<0>(now)];
            int x = get<1>(now) + dx[t];
            int y = get<2>(now) + dy[t];
            if (verify(x, y))
                if (dp[t][x][y][get<3>(now)][get<4>(now) - 1] == 0) {
                    dp[t][x][y][get<3>(now)][get<4>(now) - 1] = 1;
                    next.push(make_tuple(t, x, y, get<3>(now), get<4>(now) - 1));
                }
        }
    }
    int ans = 30;
    REP(i, a + 1) {
        REP(q, a + 1) {
            REP(j, 4) {
                if (dp[j][goal.first][goal.second][i][q]) {
                    ans = min(ans, a - i + a - q);
                }
            }
        }
    }
    if (ans == 30)ans = -1;
    cout << ans << endl;
}

#undef int
int main() {
    init();
    solve();
}
accuracy: 1
time_ms: 10
memory_kb: 6660
final_rank: 3