2019暑期集训牛客多校8-C.CDMA
思路
给你一个n * n的矩阵,n=2 ^ k(k=1、2、3、…、10),矩阵由1和-1组成,且任意两行对应位置元素相乘再相加为0。要你输出这样的n*n矩阵。
显然n=2时矩阵可以为:
1 1
1 -1
而n=4时,矩阵为:
1 1 1 1
1 -1 1 -1
1 1 -(1 1)
1 -1 -(1 -1)
由此发现n=2^k的矩阵是由四个n=2 ^ (k-1)的矩阵演变而来的。左上角、右上角、左下角是n=2 ^(k-1)的矩阵,右下角是n=2 ^(k-1)矩阵整体变号后的矩阵。
题解
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1025;
int a[maxn][maxn];
struct node {
int x1, y1, x2, y2, v;
};
stack<node> s;
int main() {
int cot=0;
int n;
scanf("%d", &n);
s.push(node{1, 1, n, n, 1});
while (!s.empty()) {
cot++;
node tmp = s.top();
s.pop();
if (tmp.x1 == tmp.x2) { // 每个子矩阵分到最小时会有tmp.x1 == tmp.x2,这是最骚的地方
a[tmp.x1][tmp.y1] = tmp.v;
continue;
}
int x1 = tmp.x1;
int x2 = tmp.x2;
int xm = (x1 + x2) / 2;
int y1 = tmp.y1;
int y2 = tmp.y2;
int ym = (y1 + y2) / 2;
s.push(node{x1, y1, xm, ym, tmp.v}); //每次将矩阵分为四个部分,压入栈中
s.push(node{x1, ym + 1, xm, y2, tmp.v});
s.push(node{xm + 1, y1, x2, ym, tmp.v});
s.push(node{xm + 1, ym + 1, x2, y2, -tmp.v});
// cot++;
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
printf("%d%c", a[i][j], (j == n) ? '\n' : ' ');
cout<<endl<<cot<<endl;
}