Submission details
Task:Ruudukko
Sender:anton_h
Submission time:2025-09-27 22:54:30 +0300
Language:C++ (C++20)
Status:READY
Result:100
Feedback
groupverdictscore
#1ACCEPTED100
Test results
testverdicttime
#1ACCEPTED0.01 sdetails

Code

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

using ll=long long;
using vl=vector<ll>;
#define all(c) begin(c),end(c)
#define pb push_back
#define sz(c) ll((c).size())

#define FOR(i,a,b) for(ll i=(a);i<(b);i++)

#define TR(x) ({ if(1) cout << __LINE__ << ": " #x " = " << (x) << endl; })

// Only when needed
using dd = double;
const dd eps = 1e-10;
using vd = vector<dd>;
using vvd = vector<vd>;

using vvl = vector<vl>;

bool check(vvl a){
    ll n = sz(a), m = sz(a[0]);
    FOR(i, 0, n){
        FOR(j, 0, m - 1) 
            if(abs(a[i][j] - a[i][j + 1]) <= 1) 
                return false;
    }
    FOR(i, 0, n - 1){
        FOR(j, 0, m) 
            if(abs(a[i][j] - a[i + 1][j]) <= 1) 
                return false;
    }
    return true;
}

pair<bool, vvl> construct(ll n, ll m){
    assert(n <= m);
    vvl res(n, vl(m));
    if(m <= 3){
        vl perm(n * m);
        iota(all(perm), 1);
        do{
            FOR(i, 0, n){
                FOR(j, 0, m){
                    res[i][j] = perm[i * m + j];
                } 
            }
            if(check(res)) return {true, res};
        }while(next_permutation(all(perm)));
        return {false, {}};
    }
    if(m == 4){
        res[0] = {2, 4, 1, 3};
    }else{
        ll b2 = (m + 1) / 2 + 1;
        FOR(i, 1, b2)
            res[0][(i - 1) * 2] = i;
        FOR(i, b2, m + 1){
            res[0][(i - b2) * 2 + 1] = i;
        }
    }
    FOR(i, 1, n) FOR(j, 0, m) res[i][j] = res[i - 1][j] + m;
    assert(check(res));
    return {true, res};
}
void solve(){

    ll n, m;
    cin >> n >> m;

    auto [ans, res] = construct(min(n, m), max(n, m));
    if(!ans){
        cout << "NO\n";
        return;
    }
    cout << "YES\n";
    if(n <= m){
        FOR(i, 0, n){
            FOR(j, 0, m){
                cout << res[i][j] << " ";
            }
            cout << "\n";
        }
    }else{
        FOR(i, 0, n){
            FOR(j, 0, m){
                cout << res[j][i] << " ";
            }
            cout << "\n";
        }
        cout << "\n";
    }

}
int main(int argc, char const *argv[])
{
    cin.sync_with_stdio(0);
    cin.tie(0);

    ll tc; cin >> tc;
    while(tc--) solve();

    return 0;
}

Test details

Test 1

Verdict: ACCEPTED

input
100
1 1
1 2
2 1
1 3
...

correct output
YES
1
NO
NO
NO
...

user output
YES

NO
NO
NO
...