跳到正文

题解

题解:AT_agc066_a [AGC066A] Adjacent Difference

_Ch1F4N_约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v1当前

简单题。

对网格图黑白染色,将相邻限制放到黑白之间,由于希望相邻差大于等于 dd,我们考虑将每个点的值按照黑白错开。

不妨把值域按照 dd 分块,一个数可以调整为 d×id \times i 或者 d×(i+1)d \times (i+1),考虑把黑格调为 dd 的奇数倍,白格调为 dd 的偶数倍,那么相邻项一定至少差 dd,但是这种方案的操作次数可能有 d×n2d \times n^2,注意这种调整方案的操作次数和将网格图的颜色翻转后的调整方案的操作次数之和恰好是 d×n2d \times n^2,所以两个方案中选取合法的就行。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn = 514;
int a[maxn][maxn],n,d,b[maxn][maxn];
signed main(){
	cin>>n>>d;
	long long res=0;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>a[i][j];
			a[i][j]+=1000;
			int z=a[i][j]/d;
			if(((i+j)&1)^(z&1)==1){
				z++;
			}
			b[i][j]=z*d;
			res+=abs(a[i][j]-b[i][j]);
		}
	}
	if(2*res>d*n*n){
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				int z=a[i][j]/d;
				if(((i+j+1)&1)^(z&1)==1){
					z++;
				}
				b[i][j]=z*d;
			}
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++) cout<<b[i][j]-1000<<" ";
		cout<<"\n";
	}
	return 0;
}
原文