1. 程式人生 > 實用技巧 >Grid Coloring【構造】-2020牛客暑期多校6

Grid Coloring【構造】-2020牛客暑期多校6

題意:

構造一個塗色的方案,使得塗色後滿足要求。
https://ac.nowcoder.com/acm/contest/5671/G

分析:

當時卡在了不知道如何取避免出現單色的環。
可以按照如下的構造方案:一行一行的塗,把列也當作行一樣處理,最後在分別輸出即可。

程式碼:

#include <bits/stdc++.h>
using namespace std;
const int N=410;
int ans[N][N];
int main()
{
    int t,n,k;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&k);
        if(n==1||k==1||2*(n+1)*n%k)
        {
            printf("-1\n");
            continue;
        }
        int color=1;
        for(int i=1;i<=2*n+1;i++)
        {
            if(i%2)
            {
                for(int j=1;j<=n;j++)
                {
                    ans[i][j]=color;
                    color++;
                    if(color>k) color%=k;
                }
            }
            else
            {
                for(int j=1;j<=n+1;j++)
                {
                    ans[i][j]=color;
                    color++;
                    if(color>k) color%=k;
                }
            }
        }
        for(int i=1;i<=2*n+1;i+=2)
        {
            for(int j=1;j<=n;j++)
                printf("%d%c",ans[i][j],j==n?'\n':' ');
        }
        for(int j=1;j<=n+1;j++)
        {
            for(int i=2;i<=2*n;i+=2)
                printf("%d%c",ans[i][j],i==2*n?'\n':' ');
        }
    }
    return 0;
}