原题链接:5396. 棋盘 - AcWing题库
二维差分思想:
可以学习这位佬的博客:
思考:
记录棋盘中的棋子的被操作数,被操作数为奇数则为黑子,偶数则为白子
方法一:暴力求解
结果:测试点6/10,最后TLE
#include <bits/stdc++.h>
using namespace std;
int m,n;
int b[2010][2010];
void convert(int x1, int y1, int x2, int y2)
{
for(int i=x1;i<=x2;i++)
for(int j=y1;j<=y2;j++)
b[i][j]++;
}
int main()
{
cin>>n>>m;
int x1,x2,y1,y2;
for(int i=0;i<m;i++)
{
cin>>x1>>y1>>x2>>y2;
convert(x1,y1,x2,y2);
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(b[i][j]%2==0) cout<<0;
else cout<<1;
//cout<<b[i][j]%2;
}
cout<<endl;
}
}
方法二:二维差分
AC代码:
//二维差分维护
#include <bits/stdc++.h>
using namespace std;
const int N = 2010;
int b[N][N];
int n, m;
void convert(int x1, int y1, int x2, int y2)
{
b[x1][y1] ++;
b[x1][y2 + 1] --;
b[x2 + 1][y1] --;
b[x2 + 1][y2 + 1] ++;
}
int main()
{
cin>>n>>m;
while(m --)
{
int x1, y1, x2, y2;
cin>>x1>>y1>>x2>>y2;
convert(x1, y1, x2, y2);
}
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++)
b[i][j] += b[i - 1][j] + b[i][j - 1] - b[i - 1][j - 1];
for(int i = 1; i <= n; i ++)
{
for(int j = 1; j <= n; j ++)
{
if(b[i][j] % 2 == 0) cout<<0;
else cout<<1;
//cout<<b[i][j]%2;
}
cout<<endl;
}
return 0;
}