結果

問題 No.3567 Modulo Grid
コンテスト
ユーザー GOTKAKO
提出日時 2026-06-05 22:39:46
言語 C++17
(gcc 15.2.0 + boost 1.89.0)
コンパイル:
g++-15 -O2 -lm -std=c++17 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 32 ms / 2,000 ms
コード長 2,388 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,695 ms
コンパイル使用メモリ 223,856 KB
実行使用メモリ 12,156 KB
最終ジャッジ日時 2026-06-05 22:39:50
合計ジャッジ時間 4,098 ms
ジャッジサーバーID
(参考情報)
judge3_0 / judge1_0
純コード判定待ち
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 25
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

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

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int H,W; cin >> H >> W;
    if(H*W == 1){cout << 1 << endl; return 0;}
    int N = H*W;
    vector<vector<int>> G(N);
    vector<int> V(N+1);
    for(int i=1; i<=N; i++) if(N%i == 0) for(int k=i; k<=N; k+=i) V.at(k) = i;
    V.at(N) = 1;
    for(int i=1; i<=N; i++) G.at(V.at(i)).push_back(i);
    for(int i=2; i<N; i++) if(gcd(N,i) == 1){
        for(auto v : G.at(i)) G.at(1).push_back(v);
        G.at(i).clear(); 
    }
    bool S = false;
    if(H > W) swap(H,W),S = true;
 
    vector<vector<int>> A(H,vector<int>(W)),B = A;
    int x = 0,y = 0,L = 0,ok = 0;
    bool dx = false;
    vector<int> P(N);
    auto get = [&]() -> pair<int,int> {
        if(dx) return {x,L};
        else return {L,y};
    };
    auto put = [&](int v) -> void {
        assert(G.at(v).size());
        ok++;
        int now = G.at(v).back(); G.at(v).pop_back();
        auto [X,Y] = get();
        A.at(X).at(Y) = now,B.at(X).at(Y) = v;
        if(dx) x++;
        else y++;
        if(ok == N) return;
        while(true){
            tie(X,Y) = get();
            if(!dx){
                if(X >= H || Y >= W || X < Y) dx = true,x = 0,y = 0,L++;
                else break;
            }
            else{
                if(X >= H || Y >= W || X == Y) dx = false;
                else break;
            }
        }    
    };
    for(int i=1; i<N; i++) P.at(i) = i;
    int start = 2;
    while(ok < N){
        while(start < N && G.at(start).size() == 0) start++;
        if(start == N) start = 1;
        long long lcm = start;
        auto [X,Y] = get();
        if(X || Y){
            lcm = 1;
            if(X) lcm = B.at(X-1).at(Y);
            if(Y) lcm = lcm*B.at(X).at(Y-1)/gcd(lcm,B.at(X).at(Y-1));
            if(lcm == 1) lcm = start;
        }
        if(lcm >= N) lcm = 1;
        while(lcm >= 2 && P.at(lcm) < N && G.at(P.at(lcm)).size() == 0) P.at(lcm) += lcm;
        if(P.at(lcm) >= N) lcm = 1;
        //cout << X << " " << Y << " " << P.at(lcm) << endl;
        assert(G.at(P.at(lcm)).size());
        put(P.at(lcm));
    }

    if(S) swap(H,W);
    for(int i=0; i<H; i++){
        for(int k=0; k<W; k++){
            if(k) cout << " ";
            int a = S?A.at(k).at(i):A.at(i).at(k);
            cout << a;
        }   
        cout << "\n";
    }

}
0