#include "testlib.h" #include using namespace std; /* ------------------- Grid structure & validation ------------------- */ struct Grid { int n = 0, m = 0; vector a; // '0'/'1' grid int ones = 0; vector> idx2rc; // compact index -> (r,c) for '1' cells vector rc2idx; // size n*m: -1 if wall, else compact index array,4> mv; // move maps for U,D,L,R over compact indices }; static const int DR[4] = {-1, +1, 0, 0}; // U,D,L,R static const int DC[4] = { 0, 0,-1, +1}; static void fail_invalid(const char* who, const string& msg) { quitf(_wa, "%s grid invalid: %s", who, msg.c_str()); } static void read_grid_from_stream(const char* who, InStream& st, Grid& G) { G.n = st.readInt(1, 20, "n"); G.m = st.readInt(1, 20, "m"); G.a.resize(G.n); for (int i = 0; i < G.n; ++i) { G.a[i] = st.readToken(); if ((int)G.a[i].size() != G.m) fail_invalid(who, "row length mismatch at row " + to_string(i+1)); for (char c : G.a[i]) if (c!='0' && c!='1') fail_invalid(who, "non 0/1 character in row " + to_string(i+1)); } // Build compact indexing for '1' cells G.ones = 0; G.rc2idx.assign(G.n * G.m, -1); G.idx2rc.clear(); for (int r=0;r> vis(G.n, vector(G.m, 0)); int sr=-1, sc=-1; for (int r=0;r> q; q.push({sr,sc}); vis[sr][sc]=1; int reached=0; while(!q.empty()){ auto [r,c]=q.front(); q.pop(); ++reached; for (int k=0;k<4;++k){ int nr=r+DR[k], nc=c+DC[k]; if (nr<0||nr>=G.n||nc<0||nc>=G.m) continue; if (G.a[nr][nc]!='1' || vis[nr][nc]) continue; vis[nr][nc]=1; q.push({nr,nc}); } } if (reached != G.ones) fail_invalid(who, "1-cells not connected"); // Acyclic: edges between adjacent '1's (right+down) must be ones-1 long long edges=0; for (int r=0;r& seqs) { const int K = G.ones; // de-dup stamps vector stamp(K, 0); int curStamp = 1; vector cur; cur.reserve(K); vector nxt; nxt.reserve(K); auto step_dir = [&](int dir){ nxt.clear(); int myStamp = curStamp++; for (int x : cur) { int y = G.mv[dir][x]; if (stamp[y] != myStamp) { stamp[y] = myStamp; nxt.push_back(y); } } cur.swap(nxt); }; int not_gathered = 0; for (int s=0; s seqs(t); for (int i=0;i 1.0) score_ratio = 1.0; } long long participant_value = part_score; // match required message format quitp(score_ratio, "Value: %lld. Ratio: %.4f, RatioUnbounded: %.4f", participant_value, score_ratio, unbounded_ratio); }