CodeForces 1521 E. Nastia and a Beautiful Matrix
首先想到的是对角线构造,接着就构造出了这种情况:

就是考虑让数量多的先填\(1\),后面接着填。但是这样有会个问题:

这样并不满足条件。对于这个问题,一开始我认为是要再加大面积,后来发现这样与下发的样例的\(p\)不匹配。然后试着对上图调整一下,确实能填下,看来是填的方法出了问题。
有构造了一会发现了以下图形:

x表示可以填任何数,这个成立的条件是"\(1\not=2\)"。
接着考虑填放顺序,首先数量最多的填\(1\),接着为了使\(1\not=2\)继续填x,最后填\(2\),通过反证法可知一定合法。
#include <bits/stdc++.h>
namespace io {
const int SIZE = (1 << 21) + 1;
char ibuf[SIZE], *iS, *iT, obuf[SIZE], *oS = obuf, *oT = oS + SIZE - 1, c, qu[55]; int f, qr;
// getchar
#define gc() (iS == iT ? (iT = (iS = ibuf) + fread (ibuf, 1, SIZE, stdin), (iS == iT ? EOF : *iS ++)) : *iS ++)
// print the remaining part
inline void flush () {
fwrite (obuf, 1, oS - obuf, stdout);
oS = obuf;
}
// putchar
inline void putc (char x) {
*oS ++ = x;
if (oS == oT) flush ();
}
// input a signed integer
template <class I>
inline void gi (I &x) {
for (f = 1, c = gc(); c < '0' || c > '9'; c = gc()) if (c == '-') f = -1;
for (x = 0; c <= '9' && c >= '0'; c = gc()) x = x * 10 + (c & 15); x *= f;
}
// print a signed integer
template <class I>
inline void print (I x) {
if (!x) putc ('0'); if (x < 0) putc ('-'), x = -x;
while (x) qu[++ qr] = x % 10 + '0', x /= 10;
while (qr) putc (qu[qr --]);
}
//no need to call flush at the end manually!
struct Flusher_ {~Flusher_(){flush();}}io_flusher_;
}
using io :: gi;
using io :: putc;
using io :: print;
int main(void) {
freopen("aztec.in", "r", stdin), freopen("aztec.out", "w", stdout);
int testCase = 1;
gi(testCase);
while (testCase--) {
int N, M, mx = 0;
gi(N), gi(M);
std::vector <int> A(N + 1), E(N + 1, 0);
for (int i = 1; i <= N; ++i) {
gi(A[i]), E[i] = i, mx = std::max(mx, A[i]);
}
std::sort(E.begin() + 1, E.end(), [&](const int& a, const int& b) { return A[a] > A[b]; });
auto ok = [&](int p) {
if ((p + 1 >> 1) * p < mx)
return false;
if (p * p - (p >> 1) * (p >> 1) < M)
return false;
return true;
};
int p = 1;
while (!ok(p))
++p;
print(p), putc('\n');
std::vector <std::vector <int>> R(p + 1, std::vector <int> (p + 1, 0));
if (N == 1) {
for (int i = 1; i <= p; i += 2) {
for (int j = 1; j <= p; ++j) {
if (A[1])
R[i][j] = 1, --A[1];
}
}
for (int i = 1; i <= p; ++i) {
for (int j = 1; j <= p;++j)
print(R[i][j]), putc(" \n"[j == p]);
}
continue;
}
int o = 1;
for (int i = 1; i <= p; i += 2) {
for (int j = p & 1 ? 2 : 1; j <= p; j += 2) {
if (!A[E[o]])
++o;
if (o > N || !A[E[o]])
break;
--A[E[o]], R[i][j] = E[o];
}
}
for (int i = 1; i <= p; i += 2) {
for (int j = p & 1 ? 1 : 2; j <= p; j += 2) {
if (o > N)
break;
if (!A[E[o]])
++o;
if (o > N || !A[E[o]])
break;
--A[E[o]];
R[i][j] = E[o];
}
}
for (int i = 2; i <= p; i += 2) {
for (int j = p & 1 ? 1 : 2; j <= p; j += 2) {
if (o > N)
break;
if (!A[E[o]])
++o;
if (o > N || !A[E[o]])
break;
--A[E[o]];
R[i][j] = E[o];
}
}
for (int i = 1; i <= p; ++i) {
for (int j = 1; j <= p; ++j) {
print(R[i][j]), putc(" \n"[j == p]);
}
}
}
return 0;
}

浙公网安备 33010602011771号