题意如图
思路:
判断k是n的因子 k是(n+1)的因子 或者其他情况
把这三种情况枚举即可。
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+15;
typedef long long ll;
int main()
{
ll t;
cin>>t;
while(t--)
{
ll n,m,k;
cin>>n>>k;
ll op=(n)*(n+1)*2;
if(op%k!=0)
{
cout<<"-1"<<endl;
continue;
}
if(k==1||n==1)
{
cout<<"-1"<<endl;
continue;
}
if(n%k==0)
{
ll d=n/k;
for(int i=1;i<=2*n+2;i++)
{
int x=(i+1)%2;
for(int j=1;j<=d;j++)
{
for(int l=1;l<=k;l++)
{
int y=x+l; y%=k; if(y==0) y=k;
cout<<y<<" ";
}
}
cout<<endl;
}
continue;
}
if( (n+1)%k==0)
{
ll d=n/(k+1);
for(int i=1;i<=2*n+2;i++)
{
for(int j=1;j<=n;j++)
{
int x=(j+1)%2;
int y=i%k; if(y==0) y=k;
x=x+y; x%=k; if(x==0) x=k;
cout<<x<<" ";
}
cout<<endl;
}
continue;
}
ll anp=0;
for(int i=1;i<=2*n+2;i++)
{
for(int j=1;j<=n;j++)
{
anp++;
anp%=k;
if(anp==0)
anp=k;
cout<<anp<<" ";
}
cout<<endl;
}
continue;
}
return 0;
}