Problem:
ふしぎな虫
会津生物学研究所のA博士は、とある南の島でふしぎな虫を発見しました。形は芋虫のように細長いのですが、ひとつの体節が玉のような形をしているので、糸でつないだビーズ玉のように見えます。ふしぎなのは体の色に様々なバリエーションがあることと、なかには時間がたつにつれて体の色が変っていく虫がいることでした。どの虫の体節の色も赤か緑か青のどれかに限られるようですが、1 秒ごとに体節の色が変わっていき、最後にはすべての体節が同じ色になって落ち着く場合もあれば、いつまで待ってもずっと色が変わりつづける場合もあるようでした。
調べていくうちに、ふだんはすべての体節が同じ色をしているのですが、何かに驚いたりして興奮した後は体節の色が勝手に変わってしまうことがわかりました。一度体節の色が変わってしまうと、ふたたびすべての体節が同じ色になるまではずっと色が変わり続けることがわかりました。
A博士はこの虫を何匹も捕まえて興奮させてみては、色が変わる様子を興味深く観察していましたが、やがて色が変化している最中の色の変わり方には次のような規則性があることに気がつきました。
色が変わるのは、隣り合っている色違いの 2つの体節のペア 1組だけが変わり、他の体節の色は変わらない。ただし、そのようなペアが複数あるときに、どのペアの色が変わるかはあらかじめ予測できない。
そのようなペアは、2つの体節の色のどちらでもない色に同時に変わる(たとえば、緑と赤の体節が隣り合っているときは、それらが同時に青に変わる)。
虫の色の変化を、2秒後まですべて書いたものが上の図です。図の上段のような色をした虫がいるとします。このとき、隣り合った色違いの体節のペアは 3組あるので、1秒後には中段に並べて描いた 3通りの色のどれかに変わります。1秒後に中段左側の 2つのように変わったときには、2秒後にすべての体節が緑色になることができます(図の下段の左側から 2番目)。 それに対して、1秒後に中段の1番右のように変わったときには、2秒後にすべての体節が同じ色に変わることはありません。
博士は、目の前にいる虫の体節がすべて同じ色になる可能性があるのか、あるとしたらそうなるのは最短で何秒後なのかを予測することにしました。
目の前にいる虫の体節の色の並びを入力とし、その虫の体節がすべて同じ色になるのに要する最短の時間を秒単位で出力するプログラムを作成してください。ただし、同じ色になる可能性がないときは「NA(半角英大文字)」と出力してください。また、虫の体節の色の並びは2  以上 10 以下のr(赤)、g(緑)、b(青)からなる文字列で表されます。
Input
複数のデータセットの並びが入力として与えられます。入力の終わりはゼロひとつの行で示されま
す。各データセットとして、 虫の体節の情報を表す１つの文字列が１行に与えられます。
データセットの数は 100 を超えません。
Output
データセット毎に、すべての体節の色が同じになるまでに要する最小時間 (秒単位の整数) または NA を１行に出力します。
Sample Input
rbgrg
rbbgbbr
bgr
bgrbrgbr
bggrgbgrr
gbrggrbggr
rrrrr
bgbr
0
Output for the Sample Input
5
7
1
6
NA
8
0
4

Submitted solutions:

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <map>
#include <cmath>
#include <queue>
#include <string>
#include <set>
#include <stack>
#include <numeric>
#include <functional>

using namespace std;
using ll = long long;

int main() {
    while (true) {
        string S;
        cin >> S;
        if (S == "0")break;
        int N = (int) S.size();
        int cs = 'r' + 'g' + 'b';

        string gr = string(N, 'r');
        string gg = string(N, 'g');
        string gb = string(N, 'b');
        queue<pair<int, string>> Q;
        set < string > st;

        Q.emplace(0, S);
        st.insert(S);
        int ans = -1;
        while (!Q.empty()) {
            auto [cnt, T] = Q.front();
            Q.pop();
            if (T == gr || T == gg || T == gb) {
                ans = cnt;
                break;
            }
            for (int i = 0; i < N - 1; i++) {
                string t = T;
                if (t[i] != t[i + 1]) {
                    char c = char(cs - t[i] - t[i + 1]);
                    t[i] = t[i + 1] = c;
                    if (st.find(t) == st.end()) {
                        Q.emplace(cnt + 1, t);
                        st.insert(t);
                    }
                }
            }
        }
        if (ans == -1) {
            cout << "NA" << endl;
        } else {
            cout << ans << endl;
        }
    }
}
accuracy: 1
time_ms: 90
memory_kb: 4068
final_rank: 5

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

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

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    string s;
    while (cin >> s , s != "0") {
        map<string,int> mp;
        int res = 1e9;
        mp[s] = 0;
        queue<string> q; q.push(s);
        while (q.size()) {
            s = q.front(); q.pop();
            int cur = mp[s];
            bool ok = true;
            for (int i = 0; i+1 < s.size(); ++i) {
                if (s[i] != s[i+1]) {
                    ok = false;
                    char a = s[i], b = s[i+1];
                    char c = 'r'+'g'+'b'-a-b;
                    s[i] = s[i+1] = c;
                    if (mp.find(s) == mp.end()) {
                        mp[s] = cur+1; q.push(s);
                    }
                    s[i] = a; s[i+1] = b;
                }
            }
            if (ok) {
                res = cur;
                break;
            }
        }
        if (res == 1e9) {
            cout << "NA" << "\n";
        }
        else {
            cout << res << "\n";
        }
    }
}
accuracy: 1
time_ms: 100
memory_kb: 4612
final_rank: 11

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

int main(){
    string s;
    while(cin >> s, s != "0"){
        map<string, int> mp;
        queue<string> nxt;
        mp[s] = 0;
        nxt.push(s);
        while(!nxt.empty()){
            s = nxt.front();
            nxt.pop();
            int d = mp[s];
            for(int i = 0; i + 1 < s.size(); i++){
                if(s[i] != s[i + 1]){
                    char c1 = s[i], c2 = s[i + 1];
                    s[i] = s[i + 1] = s[i] ^ s[i + 1] ^ 'r' ^ 'g' ^ 'b';
                    if(mp.find(s) == mp.end()){
                        mp[s] = d + 1;
                        nxt.push(s);
                    }
                    s[i] = c1, s[i + 1] = c2;
                }
            }
        }
        int ans = 1 << 30;
        for(auto c:{'r','g','b'}){
            string t(s.size(), c);
            if(mp.find(t) == mp.end())continue;
            ans = min(ans, mp[t]);
        }
        if(ans == (1 << 30))cout << "NA" << '\n';
        else cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 540
memory_kb: 4868
final_rank: 19

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

int main(){
  for(;;){
    string S;
    cin >> S;
    if(S == "0") break;
    int N = S.size();
    long long int INF = 1000000000000000000;
    vector<long long int> dist(59049,INF);
    int a = 0;
    for(int i=0;i<N;i++){
      if(S[i] == 'r') a *= 3;
      else if(S[i] == 'g') a = a*3+1;
      else a = a*3+2;
    }
    dist[a] = 0;
    priority_queue<pair<long long int,long long int>,vector<pair<long long int,long long int> >,greater<pair<long long int,long long int> > > que;
    que.push(make_pair(0,a));
    while(!que.empty()){
      int v = que.top().second;
      long long int d = que.top().first;
      que.pop();
      if(dist[v] < d) continue;
      string T = "";
      for(int i=0;i<N;i++){
        if(v%3 == 0) T += 'r';
        else if(v%3 == 1) T += 'g';
        else T += 'b';
        v /= 3;
      }
      reverse(T.begin(),T.end());
      for(int i=0;i<N-1;i++){
        if(T[i] == T[i+1]) continue;
        int k=3;
        if(T[i] == 'r') k -= 0;
        else if(T[i] == 'g') k -= 1;
        else k -= 2;
        if(T[i+1] == 'r') k -= 0;
        else if(T[i+1] == 'g') k -= 1;
        else k -= 2;
        string U = T;
        if(k == 0){
          U[i] = 'r';
          U[i+1] = 'r';
        }
        else if(k == 1){
          U[i] = 'g';
          U[i+1] = 'g';
        }
        else{
          U[i] = 'b';
          U[i+1] = 'b';
        }
        int l=0;
        for(int i=0;i<N;i++){
          if(U[i] == 'r') l *= 3;
          else if(U[i] == 'g') l = l*3+1;
          else l = l*3+2;
        }
        if(dist[l] <= d+1) continue;
        dist[l] = d+1;
        que.push(make_pair(dist[l],l));
      }
    }
    long long int ans = INF;
    int x=0,y=0,z=0;
    for(int i=0;i<N;i++){
      x = x*3;
      y = y*3+1;
      z = z*3+2;
    }
    ans = min(ans,dist[x]);
    ans = min(ans,dist[y]);
    ans = min(ans,dist[z]);
    if(ans != INF) cout << ans << endl;
    else cout << "NA" << endl;
  }
}
accuracy: 1
time_ms: 380
memory_kb: 3584
final_rank: 10

code_snippet: #define _USE_MATH_DEFINES
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<list>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<climits>
#include<iomanip>
#include<cctype>
#include<sstream>
#include<regex>
#include<bitset>
#include<random>
using namespace std;
#define int long long
#define uint unsigned long long
const int mod=1e9+7;
const int Mod=998244353;
const int inf=mod*mod;
const double eps=1e-9;
signed main(){
	string s;
	while(cin>>s,s!="0"){
		map<string,int>dist;
		set<string>used;
		queue<string>que;
		bool fnd=0;
		dist[s]=0;
		used.insert(s);
		que.push(s);
		while(!que.empty()){
			s=que.front();
			que.pop();
			if(s==string(s.size(),s[0])){
				cout<<dist[s]<<endl;
				fnd=1;
				break;
			}
			for(int i=0;i<s.size()-1;i++){
				if(s[i]!=s[i+1]){
					string ss=s;
					ss[i]=ss[i+1]='r'+'g'+'b'-s[i]-s[i+1];
					if(used.count(ss))
						continue;
					dist[ss]=dist[s]+1;
					used.insert(ss);
					que.push(ss);
				}
			}
		}
		if(!fnd)
			cout<<"NA"<<endl;
	}
}
accuracy: 1
time_ms: 130
memory_kb: 5576
final_rank: 17

code_snippet: #include <stdio.h>
#include<queue>
#include<string.h>
#include<map>

#define MAX_CODE  59049
char table[MAX_CODE];

char str[12];

struct Node
{
	int code;
	int depth;
};

int getNumber(char ch)
{
	if (ch == 'r')
		return 0;
	else if (ch == 'g')
		return 1;
	else if (ch == 'b')
		return 2;
	return 0;
}

char get_char(int number)
{
	if (number == 0)
		return 'r';
	else if (number == 1)
		return 'g';
	else if (number == 2)
		return 'b';
	return 'r';
}

int strToCode(char* str, int len)
{
	int sum = 0;
	int ans = 1;
	for (int i = 0; i < len; i++)
	{
		sum += getNumber(str[i]) * ans;
		ans *= 3;
	}
	return sum;
}

void codeToStr(int code, char* str, int len)
{
	int number;
	char ch;
	for (int i = 0; i < len; i++)
	{
		number = code % 3;
		code = code / 3;
		ch = get_char(number);
		str[i] = ch;
	}
}

int check(char* str, int len)
{
	int i;
	for (i = 0; i < len - 1; i++)
	{
		if (str[i] != str[i + 1])
			break;
	}
	return i == (len - 1);
}


int bfs(char* str, int len)
{
	if (check(str, len))
		return 0;
	int code;
	char chs[2];
	code = strToCode(str, len);
	table[code] = '1';

	std::queue<Node> Q;
	Node tmp, nd;
	tmp.code = code;
	tmp.depth = 0;
	Q.push(tmp);
	while (!Q.empty())
	{
		nd = Q.front();
		Q.pop();

		codeToStr(nd.code, str, len);
		for (int i = 0; i < len - 1; i++)
		{
			if (str[i] != str[i + 1])
			{
				chs[0] = str[i], chs[1] = str[i + 1];
				if (str[i] != 'r' && str[i + 1] != 'r') str[i] = str[i + 1] = 'r';
				else if (str[i] != 'g' && str[i + 1] != 'g') str[i] = str[i + 1] = 'g';
				else if (str[i] != 'b' && str[i + 1] != 'b') str[i] = str[i + 1] = 'b';

				if (check(str, len)) return nd.depth + 1;
				code = strToCode(str, len);
				if (table[code] == '0')
				{
					table[code] = '1';
					tmp.code = code;
					tmp.depth = nd.depth + 1;
					Q.push(tmp);
				}
				str[i] = chs[0], str[i + 1] = chs[1];
			}
		}
	}
	return -1;
}

int slove(char* str, int len)
{
	return bfs(str, len);
}

int main()
{
	int count;
	while (1)
	{
		scanf("%s", str);
		if (str[0] == '0')
			break;

		int len = strlen(str);
		for (int i = 0; i < MAX_CODE; i++) table[i] = '0';
		count = slove(str, len);
		if (count >= 0)
			printf("%d\n", count);
		else
			printf("NA\n");
	}
	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 2756
final_rank: 1

code_snippet: #include <stdio.h>
#include<queue>
#include<string>
#include<map>
#include<string.h>

char table[1001];
int len = 0;

struct Node
{
	std::string str;
	int depth;
};


int check(char* s, int len)
{
	int i = 0;
	for (i = 0; i < len - 1; i++)
	{
		if (s[i] != s[i + 1])
			break;
	}
	return i == (len - 1);
}

int insertMap(std::map<std::string, int>& strMap, std::string& key)
{
	std::map<std::string, int>::iterator iter = strMap.find(key);
	if (iter != strMap.end())
		return 0;

	strMap.insert(std::pair<std::string, int>(key, 1));
	return 1;
}

int bfs()
{
	len = strlen(table);
	if (check(table, len))
		return 0;
	char chs[2];
	Node tmp, nd;
	std::map<std::string, int > strMap;
	std::queue<Node> Q;
	tmp.str = table;
	tmp.depth = 0;
	Q.push(tmp);

	while (!Q.empty())
	{
		nd = Q.front();
		Q.pop();
		strcpy(table, nd.str.c_str());
		for (int i = 0; i < len - 1; i++)
		{
			if (table[i] != table[i + 1])
			{
				chs[0] = table[i];
				chs[1] = table[i + 1];
				if (table[i] != 'r' && table[i + 1] != 'r') table[i] = table[i + 1] = 'r';
				else if (table[i] != 'g' && table[i + 1] != 'g') table[i] = table[i + 1] = 'g';
				else if (table[i] != 'b' && table[i + 1] != 'b') table[i] = table[i + 1] = 'b';
				if (check(table, len))  return nd.depth + 1;
				tmp.str = table;
				tmp.depth = nd.depth + 1;
				if (insertMap(strMap, tmp.str))
				{
					Q.push(tmp);
				}
				table[i] = chs[0];
				table[i + 1] = chs[1];
			}
		}
	}
	return -1;
}

int slove()
{
	return bfs();
}

int main()
{
	int count;
	while (1)
	{
		scanf("%s", table);
		if (table[0] == '0')
			break;
		count = slove();
		if (count >= 0)
			printf("%d\n", count);
		else
			printf("NA\n");
	}
	return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 4208
final_rank: 6

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
const int inf = 1e9;

int main(){
    string col = "rgb";
    while(1){
        string s;
        cin >> s;
        if(s == "0") break;
        int n = s.length();
        
        queue<string> wait;
        map<string, int> dp;
        dp[s] = 0;
        wait.push(s);
        while(!wait.empty()){
            string t = wait.front();
            int cost = dp[t];
            wait.pop();
            for(int i=0; i<n-1; i++){
                if(t[i] == t[i+1]) continue;
                string tmp = t;
                char unuse;
                for(int j=0; j<3; j++){
                    if(t[i]!=col[j] and t[i+1]!=col[j]){
                        unuse = col[j];
                    }
                }
                tmp[i] = unuse;
                tmp[i+1] = unuse;
                if(dp.count(tmp) > 0) continue;
                wait.push(tmp);
                dp[tmp] = cost+1;
            }
        }
        int ans = inf;
        for(int i=0; i<3; i++){
            if(dp.count(string(n, col[i])) > 0){
                ans = min(ans, dp[string(n, col[i])]);
            }
        }
        if(ans == inf){
            cout << "NA" << endl;
        }else{
            cout << ans << endl;
        }
    }
    return 0;
}
accuracy: 1
time_ms: 990
memory_kb: 5196
final_rank: 20

code_snippet: #include <iostream>
#include <set>
#include <queue>

struct Worm {
	std::string body;
	int step;
	Worm() {}
	Worm(std::string body, int step) : body(body), step(step) {}
};

bool meetColor(std::string body)
{
	char c = body[0];
	for (int i=1; i<body.length(); i++) {
		if (body[i] != c) return false;
	}
	return true;
}

int getMinStep(std::queue<Worm> que, std::set<std::string>& checked)
{
	while (!que.empty()) {
		Worm worm = que.front(); que.pop();
		if (meetColor(worm.body)) return worm.step;
		if (checked.find(worm.body) != checked.end()) continue;
		checked.insert(worm.body);
		for (int i=0; i<worm.body.length()-1; i++) {
			if (worm.body[i] == worm.body[i+1]) continue;
			std::string new_body = worm.body;
			if (new_body[i] == 'r' && new_body[i+1] == 'g') new_body[i] = new_body[i+1] = 'b';
			else if (new_body[i] == 'r' && new_body[i+1] == 'b') new_body[i] = new_body[i+1] = 'g';
			else if (new_body[i] == 'g' && new_body[i+1] == 'r') new_body[i] = new_body[i+1] = 'b';
			else if (new_body[i] == 'g' && new_body[i+1] == 'b') new_body[i] = new_body[i+1] = 'r';
			else if (new_body[i] == 'b' && new_body[i+1] == 'r') new_body[i] = new_body[i+1] = 'g';
			else new_body[i] = new_body[i+1] = 'r';
			que.push(Worm(new_body, worm.step+1));
		}
	}
	return -1;
}

int main()
{
	std::string worm;
	while (true) {
		std::cin >> worm;
		if (worm=="0") break;
		std::queue<Worm> que;
		que.push(Worm(worm,0));
		std::set<std::string> checked;
		int res = getMinStep(que, checked);
		if (res >= 0) std::cout << res << std::endl;
		else std::cout << "NA" << std::endl;
	}
	return 0;
}
accuracy: 1
time_ms: 160
memory_kb: 4804
final_rank: 14

code_snippet: #include<iostream>
#include<algorithm>
#include <map>
#include <vector>
#include <stack>
#include<string>
#include<queue>
#include <regex>

using namespace std;

char GetDifColor(char c1, char c2)
{
	if (c1 != 'r' && c2 != 'r')
		return 'r';
	if (c1 != 'g' && c2 != 'g')
	    return 'g';
	if (c1 != 'b' && c2 != 'b')
		return 'b';
	return ' ';
}

int BF(string worm)
{
	int len = worm.length();
	string R(len,'r');
	string G(len,'g');
	string B(len,'b');
	if (worm == R || worm == G || worm == B)
		return 0;
	queue<string> nodes;
	map<string, int> records;
	nodes.push(worm);
	nodes.push("end");
	int count0 = 0;
	while (!nodes.empty())
	{
		string node = nodes.front();
		nodes.pop();
		if (node == "end")
		{
			if (nodes.empty())
				return -1;
			count0++;
			nodes.push("end");
			continue;
		}
		for (size_t i = 0; i < len - 1; i++)
		{
			if (node[i] != node[i + 1])
			{
				char c = GetDifColor(node[i], node[i + 1]);
				string part(2, c);
				string newNode = node;
				newNode.replace(i, 2, part);
				if (records.find(newNode) == records.end())
				{
					if (newNode == R || newNode == G || newNode == B)
						return count0 + 1;
					nodes.push(newNode);
					records[newNode] = 1;
				}
			}
		}
	}
	return -1;
}

int main()
{
	string worm;
	cin >> worm;
	while (worm != "0")
	{
		int count0 = BF(worm);
		string ret = count0 == -1 ? "NA" : to_string(count0);
		cout << ret << endl;
		cin >> worm;
	}
	//system("pause");
}
accuracy: 1
time_ms: 130
memory_kb: 4576
final_rank: 12

code_snippet: #include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>

static const int MOD = 1000000007;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;

template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;

int main() {
    string s;
    while(cin >> s, s != "0"){
        map<string, int> m;
        queue<string> Q;
        Q.emplace(s);
        m[s] = 0;
        int p = 0;
        while(!Q.empty()){
            string x = Q.front(); Q.pop();
            int ok = 1;
            for (int i = 0; i+1 < x.size(); ++i) {
                if(x[i] != x[i+1]) {
                    ok = 0;
                    break;
                }
            }
            if(ok) {
                p = 1;
                cout << m[x] << "\n";
                break;
            }
            for (int i = 0; i+1 < x.size(); ++i) {
                if(x[i] == x[i+1]) continue;;
                string y = x;
                auto w = 'r'^'g'^'b'^x[i]^x[i+1];
                y[i] = y[i+1] = w;
                if(!m.count(y)){
                    m[y] = m[x]+1;
                    Q.emplace(y);
                }
            }
        }
        if(!p){
            puts("NA");
        }
    }
    return 0;
}
accuracy: 1
time_ms: 180
memory_kb: 4828
final_rank: 15

code_snippet: #include<iostream>
#include<cstring>
#include<algorithm>
#include<math.h>
#include<map>
#include<queue>

using namespace std;

string InputStr, StrNow;
map<string, int> DpResult;


bool isAllSame() {
	int size;

	size = StrNow.size();
	for (int i = 1; i < size; i++) {
		if (StrNow[0] != StrNow[i]) {
			return false;
		}
	}
	return true;
}

bool solve() {
	int size;
	string strPrev;
	queue<string> CurrentStr;

	DpResult[InputStr] = 0;
	CurrentStr.push(InputStr);

	while (!CurrentStr.empty()) {
		StrNow = strPrev = CurrentStr.front();
		CurrentStr.pop();

		//cout << "befor:" << strPrev << endl;
		size = StrNow.size() - 1;
		for (int i = 0; i < size; i++) {
			StrNow = strPrev;
			if ((StrNow[i] == 'r' && StrNow[i + 1] == 'g') || (StrNow[i] == 'g' && StrNow[i + 1] == 'r')) {
				StrNow[i] = StrNow[i + 1] = 'b';
			}
			else if ((StrNow[i] == 'r' && StrNow[i + 1] == 'b') || (StrNow[i] == 'b' && StrNow[i + 1] == 'r')) {
				StrNow[i] = StrNow[i + 1] = 'g';
			}
			else if ((StrNow[i] == 'g' && StrNow[i + 1] == 'b') || (StrNow[i] == 'b' && StrNow[i + 1] == 'g')) {
				StrNow[i] = StrNow[i + 1] = 'r';
			}

			//cout << "after:" << StrNow << endl;
			if (DpResult.find(StrNow) == DpResult.end()) {
				CurrentStr.push(StrNow);
				DpResult[StrNow] = DpResult[strPrev] + 1;
			}

			if (isAllSame()) {
				return true;
			}
		}
	}

	return false;
}

int main() {

	while (cin >> InputStr, InputStr[0] != '0') {
		//cout << InputStr << endl;
		DpResult.clear();		
		if (solve()) {
			cout << DpResult[StrNow] << endl;
		}
		else {
			cout << "NA" << endl;
		}
	}

	return 0;
}
accuracy: 1
time_ms: 170
memory_kb: 4632
final_rank: 13

code_snippet: #include <cstdio>
#include <utility>
#include <string>
#include <queue>
#include <climits>
using namespace std;

#define _gp(l) const auto gcu{getchar##l}; const auto pcu{putchar##l}
#ifdef __linux
_gp(_unlocked);
#else
_gp();
#endif
#define _DEF(r, n, ...) inline r n(__VA_ARGS__) noexcept
#define _T template <typename T>
#define _HT template <typename H,typename... T>
#define _OP(t) inline operator t()
struct _in {
#ifdef _GLIBCXX_STRING
	_OP(string){string s;for(char c;c=gcu(),c!=' '&&c!='\n';)s+=c;return s;}
#define _S
#endif
	_OP(char){char c=gcu();gcu();return c;}
	_OP(double){double d; scanf("%lf",&d); gcu();return d;}
	_T _OP(T){T n{},m{1},c;if((c=gcu())=='-')m=-1,c=gcu();do{n=10*n+(c-'0'),c=gcu();}while(c>='0'&&c<='9');return m*n;}
} in;
#define _SCAN(...) _DEF(bool,scan,__VA_ARGS__)
#ifdef _S
_SCAN(string &o) {int c{gcu()};if(c==EOF)return false;else{ungetc(c,stdin);string t=move(in);o=t;return true;}}
#endif
_T _SCAN(T &o) {int c{gcu()};return c==EOF?false:(ungetc(c,stdin),o=in,true);}
_HT _SCAN(H &h,T&&... t){return scan(h)&&scan(t...);}
#define _OUT(...) _DEF(void,out,__VA_ARGS__)
#define _OUTL(...) _DEF(void,outl,__VA_ARGS__)
_OUT(bool b){pcu('0'+b);}
_OUT(const char *s){while(*s)pcu(*s++);}
_OUT(char c){pcu(c);}
#ifdef _S
_OUT(string &s){for(char c:s)pcu(c);}
#endif
_T _OUT(T n){static char b[20];char *p=b;T m=n<0?pcu('-'),-1:1;
	if(!n)*p++='0';else while(n)*p++=(char)(n%10*m+'0'),n/=10;while(p!=b)pcu(*--p);}
	_OUTL(){out('\n');}
#ifdef _GLIBCXX_VECTOR
	_T _OUT(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);}
#endif
	_HT _OUT(H &&h, T... t){out(h);out(t...);}
	template <typename... T> _OUTL(T... t){out(t...);outl();}
	struct range{
		int e,b=0,s=1;range(int _b,int _e,int _s):e(_e),b(_b),s(_s){} range(int _b,int _e): e(_e), b(_b){} range(int _e):e(_e){}
		struct it{int v,s; it(int _v,int _s):v(_v),s(_s){} operator int()const{return v;} operator int&(){return v;}int operator*()const{return v;}
			it& operator++(){v+=s;return *this;} }; it begin(){return {b,s};} it end(){return {e,s};}};
#define times(i,n) for(int i=n;i;i--)

struct N {
	int s, n;
};

bool all(int n) {
	int c = n & 3;
	n >>= 2;
	for (; n; n >>= 2)
		if ((n & 3) != c)
			return false;
	return true;
}

int main() {
	for (;;) {
		string s = in;
		if (s == "0")
			return 0;
		int r = [&] {
			bool m[1 << 2 * s.size()] {};
			int t {};
			for (char c: s) {
				t <<= 2;
				t |= c == 'r' ? 1 : c == 'g' ? 2 : 3;
			}
			m[t] = true;
			queue<N> q;
			q.push({t, 0});
			while (!q.empty()) {
				N f {q.front()};
				q.pop();
				if (all(f.s))
					return f.n;
				for (int i: range(1, s.size())) {
					if (((f.s >> (i - 1) * 2) & 3) != ((f.s >> i * 2) & 3)) {
						int t = f.s,
							g = ((t >> (i - 1) * 2) & 3) ^ ((t >> i * 2) & 3);
						t &= ~(15 << (i - 1) * 2);
						t |= (g | g << 2) << (i - 1) * 2;
						if (!m[t]) {
							m[t] = true;
							q.push({t, f.n + 1});
						}
					}
				}
			}
			return -1;
		}();
		if (r == -1)
			outl("NA");
		else
			outl(r);
	}
}
accuracy: 1
time_ms: 10
memory_kb: 3648
final_rank: 4

code_snippet: #include <cstdio>
#include <utility>
#include <string>
#include <queue>
#include <unordered_set>
using namespace std;

#define _gp(l) const auto gcu{getchar##l}; const auto pcu{putchar##l}
#ifdef __linux
_gp(_unlocked);
#else
_gp();
#endif
#define _DEF(r, n, ...) inline r n(__VA_ARGS__) noexcept
#define _T template <typename T>
#define _HT template <typename H,typename... T>
#define _OP(t) inline operator t()
struct _in {
#ifdef _GLIBCXX_STRING
	_OP(string){string s;for(char c;c=gcu(),c!=' '&&c!='\n';)s+=c;return s;}
#define _S
#endif
	_OP(char){char c=gcu();gcu();return c;}
	_OP(double){double d; scanf("%lf",&d); gcu();return d;}
	_T _OP(T){T n{},m{1},c;if((c=gcu())=='-')m=-1,c=gcu();do{n=10*n+(c-'0'),c=gcu();}while(c>='0'&&c<='9');return m*n;}
} in;
#define _SCAN(...) _DEF(bool,scan,__VA_ARGS__)
#ifdef _S
_SCAN(string &o) {int c{gcu()};if(c==EOF)return false;else{ungetc(c,stdin);string t=move(in);o=t;return true;}}
#endif
_T _SCAN(T &o) {int c{gcu()};return c==EOF?false:(ungetc(c,stdin),o=in,true);}
_HT _SCAN(H &h,T&&... t){return scan(h)&&scan(t...);}
#define _OUT(...) _DEF(void,out,__VA_ARGS__)
#define _OUTL(...) _DEF(void,outl,__VA_ARGS__)
_OUT(bool b){pcu('0'+b);}
_OUT(const char *s){while(*s)pcu(*s++);}
_OUT(char c){pcu(c);}
#ifdef _S
_OUT(string &s){for(char c:s)pcu(c);}
#endif
_T _OUT(T n){static char b[20];char *p=b;T m=n<0?pcu('-'),-1:1;
	if(!n)*p++='0';else while(n)*p++=(char)(n%10*m+'0'),n/=10;while(p!=b)pcu(*--p);}
	_OUTL(){out('\n');}
#ifdef _GLIBCXX_VECTOR
	_T _OUT(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);}
#endif
	_HT _OUT(H &&h, T... t){out(h);out(t...);}
	template <typename... T> _OUTL(T... t){out(t...);outl();}
	struct range{
		int e,b=0,s=1;range(int _b,int _e,int _s):e(_e),b(_b),s(_s){} range(int _b,int _e): e(_e), b(_b){} range(int _e):e(_e){}
		struct it{int v,s; it(int _v,int _s):v(_v),s(_s){} operator int()const{return v;} operator int&(){return v;}int operator*()const{return v;}
			it& operator++(){v+=s;return *this;} }; it begin(){return {b,s};} it end(){return {e,s};}};
#define times(i,n) for(int i=n;i;i--)

struct N {
	int s, n;
};

bool all(int n) {
	int c = n & 7;
	n >>= 3;
	for (; n; n >>= 3)
		if ((n & 7) != c)
			return false;
	return true;
}

int main() {
	for (;;) {
		string s = in;
		if (s == "0")
			return 0;
		int r = [&] {
			unordered_set<int> m;
			int t {};
			for (char c: s) {
				t <<= 3;
				t |= c == 'r' ? 1 : c == 'g' ? 2 : 4;
			}
			m.insert(t);
			queue<N> q;
			q.push({t, 0});
			while (!q.empty()) {
				N f {q.front()};
				q.pop();
				if (all(f.s))
					return f.n;
				for (int i: range(1, s.size())) {
					if (((f.s >> (i - 1) * 3) & 7) != ((f.s >> i * 3) & 7)) {
						int t = f.s,
							g = 7 & ~(((t >> (i - 1) * 3) & 7) | ((t >> i * 3) & 7));
						t &= ~(63 << (i - 1) * 3);
						t |= (g | g << 3) << (i - 1) * 3;
						if (!m.count(t)) {
							m.insert(t);
							q.push({t, f.n + 1});
						}
					}
				}
			}
			return -1;
		}();
		if (r == -1)
			outl("NA");
		else
			outl(r);
	}
}
accuracy: 1
time_ms: 30
memory_kb: 2984
final_rank: 3

code_snippet: #include <cstdio>
#include <utility>
#include <string>
#include <queue>
#include <unordered_set>
using namespace std;

#define _gp(l) const auto gcu{getchar##l}; const auto pcu{putchar##l}
#ifdef __linux
_gp(_unlocked);
#else
_gp();
#endif
#define _DEF(r, n, ...) inline r n(__VA_ARGS__) noexcept
#define _T template <typename T>
#define _HT template <typename H,typename... T>
#define _OP(t) inline operator t()
struct _in {
#ifdef _GLIBCXX_STRING
	_OP(string){string s;for(char c;c=gcu(),c!=' '&&c!='\n';)s+=c;return s;}
#define _S
#endif
	_OP(char){char c=gcu();gcu();return c;}
	_OP(double){double d; scanf("%lf",&d); gcu();return d;}
	_T _OP(T){T n{},m{1},c;if((c=gcu())=='-')m=-1,c=gcu();do{n=10*n+(c-'0'),c=gcu();}while(c>='0'&&c<='9');return m*n;}
} in;
#define _SCAN(...) _DEF(bool,scan,__VA_ARGS__)
#ifdef _S
_SCAN(string &o) {int c{gcu()};if(c==EOF)return false;else{ungetc(c,stdin);string t=move(in);o=t;return true;}}
#endif
_T _SCAN(T &o) {int c{gcu()};return c==EOF?false:(ungetc(c,stdin),o=in,true);}
_HT _SCAN(H &h,T&&... t){return scan(h)&&scan(t...);}
#define _OUT(...) _DEF(void,out,__VA_ARGS__)
#define _OUTL(...) _DEF(void,outl,__VA_ARGS__)
_OUT(bool b){pcu('0'+b);}
_OUT(const char *s){while(*s)pcu(*s++);}
_OUT(char c){pcu(c);}
#ifdef _S
_OUT(string &s){for(char c:s)pcu(c);}
#endif
_T _OUT(T n){static char b[20];char *p=b;T m=n<0?pcu('-'),-1:1;
	if(!n)*p++='0';else while(n)*p++=(char)(n%10*m+'0'),n/=10;while(p!=b)pcu(*--p);}
	_OUTL(){out('\n');}
#ifdef _GLIBCXX_VECTOR
	_T _OUT(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);}
#endif
	_HT _OUT(H &&h, T... t){out(h);out(t...);}
	template <typename... T> _OUTL(T... t){out(t...);outl();}
	struct range{
		int e,b=0,s=1;range(int _b,int _e,int _s):e(_e),b(_b),s(_s){} range(int _b,int _e): e(_e), b(_b){} range(int _e):e(_e){}
		struct it{int v,s; it(int _v,int _s):v(_v),s(_s){} operator int()const{return v;} operator int&(){return v;}int operator*()const{return v;}
			it& operator++(){v+=s;return *this;} }; it begin(){return {b,s};} it end(){return {e,s};}};
#define times(i,n) for(int i=n;i;i--)

struct N {
	int s, n;
};

int flag(char c) {
	return c == 'r' ? 3 : c == 'g' ? 5 : 6;
}

bool all(int n) {
	int c = n & 7;
	n >>= 3;
	for (; n; n >>= 3)
		if ((n & 7) != c)
			return false;
	return true;
}

int main() {
	for (;;) {
		string s = in;
		if (s == "0")
			return 0;
		int r = [&] {
			unordered_set<int> m;
			int t {};
			for (char c: s) {
				t <<= 3;
				t |= c == 'r' ? 1 : c == 'g' ? 2 : 4;
			}
			m.insert(t);
			queue<N> q;
			q.push({t, 0});
			while (!q.empty()) {
				N f {q.front()};
				q.pop();
				if (all(f.s))
					return f.n;
				for (int i: range(1, s.size())) {
					if (((f.s >> (i - 1) * 3) & 7) != ((f.s >> i * 3) & 7)) {
						int t = f.s,
							g = 7 & ~(((t >> (i - 1) * 3) & 7) | ((t >> i * 3) & 7));
						t &= ~(63 << ((i - 1) * 3));
						t |= (g | g << 3) << ((i - 1) * 3);
						if (!m.count(t)) {
							m.insert(t);
							q.push({t, f.n + 1});
						}
					}
				}
			}
			return -1;
		}();
		if (r == -1)
			outl("NA");
		else
			outl(r);
	}
}
accuracy: 1
time_ms: 30
memory_kb: 2972
final_rank: 2

code_snippet: #include <cstdio>
#include <utility>
#include <string>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;

#define _gp(l) const auto gcu{getchar##l}; const auto pcu{putchar##l}
#ifdef __linux
_gp(_unlocked);
#else
_gp();
#endif
#define _DEF(r, n, ...) inline r n(__VA_ARGS__) noexcept
#define _T template <typename T>
#define _HT template <typename H,typename... T>
#define _OP(t) inline operator t()
struct _in {
#ifdef _GLIBCXX_STRING
	_OP(string){string s;for(char c;c=gcu(),c!=' '&&c!='\n';)s+=c;return s;}
#define _S
#endif
	_OP(char){char c=gcu();gcu();return c;}
	_OP(double){double d; scanf("%lf",&d); gcu();return d;}
	_T _OP(T){T n{},m{1},c;if((c=gcu())=='-')m=-1,c=gcu();do{n=10*n+(c-'0'),c=gcu();}while(c>='0'&&c<='9');return m*n;}
} in;
#define _SCAN(...) _DEF(bool,scan,__VA_ARGS__)
#ifdef _S
_SCAN(string &o) {int c{gcu()};if(c==EOF)return false;else{ungetc(c,stdin);string t=move(in);o=t;return true;}}
#endif
_T _SCAN(T &o) {int c{gcu()};return c==EOF?false:(ungetc(c,stdin),o=in,true);}
_HT _SCAN(H &h,T&&... t){return scan(h)&&scan(t...);}
#define _OUT(...) _DEF(void,out,__VA_ARGS__)
#define _OUTL(...) _DEF(void,outl,__VA_ARGS__)
_OUT(bool b){pcu('0'+b);}
_OUT(const char *s){while(*s)pcu(*s++);}
_OUT(char c){pcu(c);}
#ifdef _S
_OUT(string &s){for(char c:s)pcu(c);}
#endif
_T _OUT(T n){static char b[20];char *p=b;T m=n<0?pcu('-'),-1:1;
	if(!n)*p++='0';else while(n)*p++=(char)(n%10*m+'0'),n/=10;while(p!=b)pcu(*--p);}
	_OUTL(){out('\n');}
#ifdef _GLIBCXX_VECTOR
	_T _OUT(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);}
#endif
	_HT _OUT(H &&h, T... t){out(h);out(t...);}
	template <typename... T> _OUTL(T... t){out(t...);outl();}
	struct range{
		int e,b=0,s=1;range(int _b,int _e,int _s):e(_e),b(_b),s(_s){} range(int _b,int _e): e(_e), b(_b){} range(int _e):e(_e){}
		struct it{int v,s; it(int _v,int _s):v(_v),s(_s){} operator int()const{return v;} operator int&(){return v;}int operator*()const{return v;}
			it& operator++(){v+=s;return *this;} }; it begin(){return {b,s};} it end(){return {e,s};}};
#define times(i,n) for(int i=n;i;i--)

struct N {
	string s;
	int n;
};

int flag(char c) {
	return c == 'r' ? 3 : c == 'g' ? 5 : 6;
}

int main() {
	for (;;) {
		string s = in;
		if (s == "0")
			return 0;
		int r = [&] {
			set<string> m;
			m.insert(s);
			queue<N> q;
			q.push({s, 0});
			while (!q.empty()) {
				N f {q.front()};
				q.pop();
				if(all_of(begin(f.s) + 1, end(f.s), [&](char c) {return c == f.s[0];}))
					return f.n;
				for (int i: range(1, f.s.size())) {
					if (f.s[i - 1] != f.s[i]) {
						string t = f.s;
						t[i - 1] = t[i] = "0bg0r"[flag(f.s[i - 1]) & flag(f.s[i])];
						if (!m.count(t)) {
							m.insert(t);
							q.push({t, f.n + 1});
						}
					}
				}
			}
			return -1;
		}();
		if (r == -1)
			outl("NA");
		else
			outl(r);
	}
}
accuracy: 1
time_ms: 160
memory_kb: 4148
final_rank: 8

code_snippet: #include <cstdio>
#include <utility>
#include <string>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;

#define _gp(l) const auto gcu{getchar##l}; const auto pcu{putchar##l}
#ifdef __linux
_gp(_unlocked);
#else
_gp();
#endif
#define _DEF(r, n, ...) inline r n(__VA_ARGS__) noexcept
#define _T template <typename T>
#define _HT template <typename H,typename... T>
#define _OP(t) inline operator t()
struct _in {
#ifdef _GLIBCXX_STRING
	_OP(string){string s;for(char c;c=gcu(),c!=' '&&c!='\n';)s+=c;return s;}
#define _S
#endif
	_OP(char){char c=gcu();gcu();return c;}
	_OP(double){double d; scanf("%lf",&d); gcu();return d;}
	_T _OP(T){T n{},m{1},c;if((c=gcu())=='-')m=-1,c=gcu();do{n=10*n+(c-'0'),c=gcu();}while(c>='0'&&c<='9');return m*n;}
} in;
#define _SCAN(...) _DEF(bool,scan,__VA_ARGS__)
#ifdef _S
_SCAN(string &o) {int c{gcu()};if(c==EOF)return false;else{ungetc(c,stdin);string t=move(in);o=t;return true;}}
#endif
_T _SCAN(T &o) {int c{gcu()};return c==EOF?false:(ungetc(c,stdin),o=in,true);}
_HT _SCAN(H &h,T&&... t){return scan(h)&&scan(t...);}
#define _OUT(...) _DEF(void,out,__VA_ARGS__)
#define _OUTL(...) _DEF(void,outl,__VA_ARGS__)
_OUT(bool b){pcu('0'+b);}
_OUT(const char *s){while(*s)pcu(*s++);}
_OUT(char c){pcu(c);}
#ifdef _S
_OUT(string &s){for(char c:s)pcu(c);}
#endif
_T _OUT(T n){static char b[20];char *p=b;T m=n<0?pcu('-'),-1:1;
	if(!n)*p++='0';else while(n)*p++=(char)(n%10*m+'0'),n/=10;while(p!=b)pcu(*--p);}
	_OUTL(){out('\n');}
#ifdef _GLIBCXX_VECTOR
	_T _OUT(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);}
#endif
	_HT _OUT(H &&h, T... t){out(h);out(t...);}
	template <typename... T> _OUTL(T... t){out(t...);outl();}
	struct range{
		int e,b=0,s=1;range(int _b,int _e,int _s):e(_e),b(_b),s(_s){} range(int _b,int _e): e(_e), b(_b){} range(int _e):e(_e){}
		struct it{int v,s; it(int _v,int _s):v(_v),s(_s){} operator int()const{return v;} operator int&(){return v;}int operator*()const{return v;}
			it& operator++(){v+=s;return *this;} }; it begin(){return {b,s};} it end(){return {e,s};}};
#define times(i,n) for(int i=n;i;i--)

struct N {
	string s;
	int n;
};

int flag(char c) {
	return c == 'r' ? 3 : c == 'g' ? 5 : 6;
}

int main() {
	for (;;) {
		string s = in;
		if (s == "0")
			return 0;
		int r = [&] {
			set<string> m;
			m.insert(s);
			queue<N> q;
			q.push({s, 0});
			while (!q.empty()) {
				N f {q.front()};
				q.pop();
				if(all_of(begin(f.s) + 1, end(f.s), [&](char c) {return c == f.s[0];}))
					return f.n;
				m.insert(f.s);
				for (int i: range(1, f.s.size())) {
					if (f.s[i - 1] != f.s[i]) {
						string t = f.s;
						t[i - 1] = t[i] = "0bg0r"[flag(f.s[i - 1]) & flag(f.s[i])];
						if (!m.count(t)) {
							m.insert(t);
							q.push({t, f.n + 1});
						}
					}
				}
			}
			return -1;
		}();
		if (r == -1)
			outl("NA");
		else
			outl(r);
	}
}
accuracy: 1
time_ms: 170
memory_kb: 4160
final_rank: 9

code_snippet: #include <cstdio>
#include <utility>
#include <string>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;

#define _gp(l) const auto gcu{getchar##l}; const auto pcu{putchar##l}
#ifdef __linux
_gp(_unlocked);
#else
_gp();
#endif
#define _DEF(r, n, ...) inline r n(__VA_ARGS__) noexcept
#define _T template <typename T>
#define _HT template <typename H,typename... T>
#define _OP(t) inline operator t()
struct _in {
#ifdef _GLIBCXX_STRING
	_OP(string){string s;for(char c;c=gcu(),c!=' '&&c!='\n';)s+=c;return s;}
#define _S
#endif
	_OP(char){char c=gcu();gcu();return c;}
	_OP(double){double d; scanf("%lf",&d); gcu();return d;}
	_T _OP(T){T n{},m{1},c;if((c=gcu())=='-')m=-1,c=gcu();do{n=10*n+(c-'0'),c=gcu();}while(c>='0'&&c<='9');return m*n;}
} in;
#define _SCAN(...) _DEF(bool,scan,__VA_ARGS__)
#ifdef _S
_SCAN(string &o) {int c{gcu()};if(c==EOF)return false;else{ungetc(c,stdin);string t=move(in);o=t;return true;}}
#endif
_T _SCAN(T &o) {int c{gcu()};return c==EOF?false:(ungetc(c,stdin),o=in,true);}
_HT _SCAN(H &h,T&&... t){return scan(h)&&scan(t...);}
#define _OUT(...) _DEF(void,out,__VA_ARGS__)
#define _OUTL(...) _DEF(void,outl,__VA_ARGS__)
_OUT(bool b){pcu('0'+b);}
_OUT(const char *s){while(*s)pcu(*s++);}
_OUT(char c){pcu(c);}
#ifdef _S
_OUT(string &s){for(char c:s)pcu(c);}
#endif
_T _OUT(T n){static char b[20];char *p=b;T m=n<0?pcu('-'),-1:1;
	if(!n)*p++='0';else while(n)*p++=(char)(n%10*m+'0'),n/=10;while(p!=b)pcu(*--p);}
	_OUTL(){out('\n');}
#ifdef _GLIBCXX_VECTOR
	_T _OUT(vector<T> &v){for(T &x:v)out(&x == &v[0]?"":" "),out(x);}
#endif
	_HT _OUT(H &&h, T... t){out(h);out(t...);}
	template <typename... T> _OUTL(T... t){out(t...);outl();}
	struct range{
		int e,b=0,s=1;range(int _b,int _e,int _s):e(_e),b(_b),s(_s){} range(int _b,int _e): e(_e), b(_b){} range(int _e):e(_e){}
		struct it{int v,s; it(int _v,int _s):v(_v),s(_s){} operator int()const{return v;} operator int&(){return v;}int operator*()const{return v;}
			it& operator++(){v+=s;return *this;} }; it begin(){return {b,s};} it end(){return {e,s};}};
#define times(i,n) for(int i=n;i;i--)

struct N {
	string s;
	int n;
};

int flag(char c) {
	return c == 'r' ? 3 : c == 'g' ? 5 : 6;
}

int main() {
	for (;;) {
		string s = in;
		if (s == "0")
			return 0;
		int r = [&] {
			set<string> m;
			m.insert(s);
			queue<N> q;
			q.push({s, 0});
			while (!q.empty()) {
				N f {q.front()};
				q.pop();
				if(count(begin(f.s) + 1, end(f.s), f.s[0]) == (int) s.size() - 1)
					return f.n;
				m.insert(f.s);
				for (int i: range(1, f.s.size())) {
					if (f.s[i - 1] != f.s[i]) {
						string t = f.s;
						t[i - 1] = t[i] = "0bg0r"[flag(f.s[i - 1]) & flag(f.s[i])];
						if (!m.count(t)) {
							m.insert(t);
							q.push({t, f.n + 1});
						}
					}
				}
			}
			return -1;
		}();
		if (r == -1)
			outl("NA");
		else
			outl(r);
	}
}
accuracy: 1
time_ms: 180
memory_kb: 4056
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
typedef vector<ll> V;
typedef complex<double> Point;
#define PI acos(-1.0)
#define EPS 1e-10
const ll INF = 1e16;
const ll MOD = 1e9 + 7;
#define FOR(i, a, b) for(int i=(a);i<(b);i++)
#define rep(i,N) FOR(i, 0, N)
#define ALL(s) (s).begin(), (s).end()
#define EQ(a, b) (abs((a) - (b)) < EPS)
#define EQV(a, b) (EQ((a).reeal(), (b).real) && EQ((a).imag(), (b).imag()))
#define NIL -1

ll g;
ll w;
ll d[100000];
char table[] = {'r','g','b'};

string myitos(ll num){
    string res = "";
    rep(i,w){
        res += table[num % 3];
        num /= 3;
    }
    reverse(ALL(res));
    return res;
}

ll mystoi(string s){
    ll res = 0;
    rep(i,s.size()){
        res *= 3;
        if(s[i] == 'g')res++;
        else if(s[i] == 'b')res += 2;
    }
    return res;
}

void dijkstra(ll start){
    fill(d,d+100000,INF);
    d[start] = 0;

    priority_queue<P,vector<P>,greater<P>> que;
    que.push(P(0,start));

    while(!que.empty()){
        P p = que.top();
        que.pop();
        ll v = p.second;
        ll cost = p.first;
        if(d[v] < cost)continue;
        // d[v] = cost;
        if(v == 0 || v == g || v == 2*g)continue;

        string now = myitos(v);

        rep(i,now.size() - 1){
            char c1 = now[i];
            char c2 = now[i+1];
            string t = now;
            if((c1 == 'r' && c2 == 'g') || (c1 == 'g' && c2 == 'r')){
                t[i] = 'b';
                t[i+1] = 'b';
            }
            if((c1 == 'g' && c2 == 'b') || (c1 == 'b' && c2 == 'g')){
                t[i] = 'r';
                t[i+1] = 'r';
            }
            if((c1 == 'b' && c2 == 'r') || (c1 == 'r' && c2 == 'b')){
                t[i] = 'g';
                t[i+1] = 'g';
            }
            ll to = mystoi(t);
            // cout << t << endl;
            if(d[to] > cost+1){
                d[to] = cost + 1;
                que.push(P(cost+1,to));
            }
        }

    }
}

string s;

int main(){
    while(cin >> s && s != "0"){
        int start = 0;
        w = s.size();
        g = 0;
        rep(i,s.size()){
            g *= 3;
            g++;
            int num = 0;
            if(s[i] == 'g')num++;
            if(s[i] == 'b')num += 2;
            start = 3*start + num;
        }
        // string t = myitos(start);
        // cout << t << endl;
        // cout << mystoi(t) << endl;
        // continue;
        dijkstra(start);
        ll ans = min(d[0],min(d[g],d[2*g]));
        if(ans == INF)cout << "NA" << endl;
        else cout << ans << endl;
    }
}
accuracy: 1
time_ms: 690
memory_kb: 3984
final_rank: 18

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <numeric>
#include <map>
#include <queue>
#include <utility>

#define REP(i, a, b) for (int i = int(a); i < int(b); i++)
#ifdef _DEBUG_
#define dump(val) cerr << __LINE__ << ":\t" << #val << " = " << (val) << endl
#else
#define dump(val)
#endif

using namespace std;

typedef long long int ll;

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

using P = pair<string, int>;

char getLast(char c1, char c2) {
    if (c1 > c2) swap(c1, c2);
    if (c1 == 'b' && c2 == 'g') return 'r';
    if (c1 == 'b' && c2 == 'r') return 'g';
    return 'b';
}

#include <set>
bool check(string s) {
    set<int> st;
    for(auto &c: s) {
        st.insert(c);
    }
    return st.size() == 1;
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    string s;
    while (cin >> s, s != "0") {
        map<string, int> mp;
        int n = s.size();
        queue<P> q;
        q.emplace(s, 0);
        int ans = -1;
        while (q.size()) {
            string e = q.front().first;
            int cnt = q.front().second;
            q.pop();
            if (check(e)) {
                ans = cnt;
                break;
            }
            mp[e] = cnt;
            REP (i, 0, n - 1) {
                if (e[i] != e[i + 1]) {
                    string tmp = e;
                    tmp[i] = tmp[i + 1] = getLast(e[i], e[i + 1]);
                    if (mp.count(tmp) == 0) {
                        q.emplace(tmp, cnt + 1);
                        mp[tmp] = cnt + 1;
                    }
                }
            }
        }
        if (ans == -1) {
            cout << "NA" << endl;
        } else {
            cout << ans << endl;
        }
    }
    return 0;
}
accuracy: 1
time_ms: 210
memory_kb: 4824
final_rank: 16