#include #include #include #include #include #include #include #include #include #include #include using namespace std; template istream& operator >> (istream& is, vector& vec){for(T& val: vec) is >> val; return is;} template istream& operator , (istream& is, T& val){ return is >> val;} template ostream& operator << (ostream& os, vector& vec){for(int i=0; i x){ if(x.size() != 3) return false; if(x[0] < x[1] && x[1] > x[2] && x[2] != x[0]) return true; if(x[0] > x[1] && x[1] < x[2] && x[2] != x[0]) return true; return false; } bool is_kadomatsu_matrix(vector& mat){ for(int i=0; i<3; i++){ if(!is_kadomatsu_sequence({mat[3*i+0], mat[3*i+1], mat[3*i+2]})) return false; if(!is_kadomatsu_sequence({mat[3*0+i], mat[3*1+i], mat[3*2+i]})) return false; } if(!is_kadomatsu_sequence({mat[3*0+0], mat[3*1+1], mat[3*2+2]})) return false; if(!is_kadomatsu_sequence({mat[3*0+2], mat[3*1+1], mat[3*2+0]})) return false; return true; } int naive(int L, vector arr){ vector x; for(int i=0; i<9; i++){ if(arr[i] == 0) x.push_back(i); } int ans = 0; for(int k=1; k arr){ assert(1<= L && L<=1000000000); vector x; for(int i=0; i<9; i++){ if(arr[i] == 0) x.push_back(i); assert(0<= arr[i] && arr[i]<=1000000000); } assert(x.size() == 2); set y; y.insert(0); y.insert(1); y.insert(L-1); y.insert(L); for(int i=0; i<9; i++){ if(arr[i] == 0) continue; y.insert(arr[i]-1); y.insert(arr[i]); y.insert(arr[i]+1); y.insert(L-arr[i]-1); y.insert(L-arr[i]); y.insert(L-arr[i]+1); } y.insert(L/2-1); y.insert(L/2); y.insert(L/2+1); long long ans = 0; int last = 0; bool valid = false; for(int u : y){ if(u<=0 || u>=L) continue; int v = L - u; arr[ x[0] ] = u; arr[ x[1] ] = v; bool is_km = is_kadomatsu_matrix(arr); if(is_km){ if(valid == false){ ans++; }else{ ans += u-last; } last = u; valid = true; }else{ valid = false; } } //cout << ans << endl; return ans; } int main(){ int t; cin >> t; assert(1<=t && t<=100); while(t--){ int L; vector arr(9); cin >> L, arr; auto ans = solver(L, arr); cout << ans << endl; } return 0; } #include /* int main_(){ mt19937 mt((unsigned)time(NULL)); uniform_int_distribution dstr(10, 20); uniform_int_distribution L_dstr(1, 40); vector arr(9); vector hoge(9); iota(hoge.begin(), hoge.end(), 0); for(int t=0; t<100000; t++){ int L = L_dstr(mt); shuffle(hoge.begin(), hoge.end(), mt); while(1){ for(int i=0; i<9; i++){ arr[i] = dstr(mt); } if(is_kadomatsu_matrix(arr)) break; } arr[hoge[0]] = arr[hoge[1]] = 0; if( naive(L,arr) != solver(L,arr) ){ cout << L << endl; cout << arr; abort(); } } return 0; } */