#include #include #include #include #define debug(fmt, ...) //#define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__) #define INFLL 8000000000000000000LL using namespace std; typedef long long int lint; typedef pair plint; typedef pair PLL; PLL extgcd(lint a, lint b) { if (a x=%lld, y=%lld, r=%lld\n", a1,m1,a2,m2,x,y,r); if ((a1-a2)%r) return plint(-1,-1); x = a1 + m1 * (a2-a1)/r*x; r = m1*m2/r; lint c = x%r; if (c<0LL) c += r; return plint(c,r); } plint congr(lint a1, lint m1, lint a2, lint m2) { plint ret = do_congr(a1,m1,a2,m2); debug("congr(%lld,%lld, %lld,%lld) = (%lld,%lld)\n",a1,m1,a2,m2,ret.first,ret.second); return ret; } lint do_solve(const vector &v) { for(int i=0;i<5;i++) if(v[i].first == -1) return -1; plint x = congr(v[0].first, v[0].second, v[1].first, v[1].second); if(x.first == -1) return -1; x = congr(x.first, x.second, v[2].first, v[2].second); if(x.first == -1) return -1; x = congr(x.first, x.second, v[3].first, v[3].second); if(x.first == -1) return -1; x = congr(x.first, x.second, v[4].first, v[4].second); if(x.first == -1) return -1; return x.first; } lint solve(const vector &v) { lint ret = do_solve(v); debug("solve (%lld,%lld) (%lld,%lld) (%lld,%lld) (%lld,%lld) (%lld,%lld) = %lld\n", v[0].first,v[0].second, v[1].first,v[1].second, v[2].first,v[2].second, v[3].first,v[3].second, v[4].first,v[4].second, ret); return ret; } static void solve() { int N; scanf("%d", &N); if (!N) exit(0); vector perm(5*N); vector init(5*N); int pos[5], cykl[5]; for (int i=0; i<5*N; i++) { scanf("%d", &init[i]); init[i] --; for (int j=0; j<5; j++) if (init[i] == j) pos[j] = i; } for (int i=0; i > dist(5*N, vector(5,-1)); for (int i=0; i<5; i++) { debug("tracing %d\n ", i); int x = pos[i]; for (int d = 0; ; d++) { debug(" %d", x); dist[x][i] = d; x = perm[x]; if (x == pos[i]) { cykl[i] = d+1; break; } } debug("\n"); } vector pi(5); lint result = -1; int winner = -1; for(int G = 0; G < N; G++) { for (int i=0; i<5; i++) pi[i] = i; do { vector instance(5); instance[0] = plint(dist[2*G][pi[0]], cykl[pi[0]]); instance[1] = plint(dist[2*G+1][pi[1]], cykl[pi[1]]); instance[2] = plint(dist[2*N+2*G][pi[2]], cykl[pi[2]]); instance[3] = plint(dist[2*N+2*G+1][pi[3]], cykl[pi[3]]); instance[4] = plint(dist[4*N+G][pi[4]], cykl[pi[4]]); lint tmp = solve(instance); if (tmp != -1LL && (result==-1 || result > tmp)) { result = tmp; winner = 0; } } while(next_permutation(pi.begin(), pi.end())); } if (winner == -1) printf("Neverending game.\n"); else printf("Player %d wins game number %lld.\n", winner+1, result+1); } int main(void) { for(;;) solve(); }