题解:AT_agc066_a [AGC066A] Adjacent Difference
思路
先考虑一个特殊情况,当
可以想到一种最简单的构造方法:
当
当
这样一定可以满足条件,但代价并不优。不过我们注意到,这时对于每个
当
当
尝试枚举每个可能的
但我们还有更好的解法,注意到
当
当
可以发现,
代码
#include<bits/stdc++.h>
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <math.h>
#include <cstdio>
#define int long long
using namespace std;
const int inf=1e18;
const int N=505;
int n,d,a[N][N],b[N][N];
int read(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
signed main(){
//freopen("std.in","r",stdin);
//ios::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
n=read();d=read();int mod=2*d;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)a[i][j]=read(),b[i][j]=a[i][j];
}
int cost=0;
//(i+j)%2=0,a(i,j)mod 2d=k
//(i+j)%2=1,a(i,j)mid 2d=k+d;
//k=0,k=d
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
int x=abs(a[i][j])%mod;
if((i+j)%2==0){
if(x<=d){
cost+=x;
if(a[i][j]<0)a[i][j]+=x;
else a[i][j]-=x;
}
else{
cost+=(2*d-x);
if(a[i][j]<0)a[i][j]-=(2*d-x);
else a[i][j]+=(2*d-x);
}
if(x<=d){
if(b[i][j]<0)b[i][j]-=(d-x);
else b[i][j]+=(d-x);
}
else{
if(b[i][j]<0)b[i][j]+=(x-d);
else b[i][j]-=(x-d);
}
}
else{
if(x<=d){
cost+=(d-x);
if(a[i][j]<0)a[i][j]-=(d-x);
else a[i][j]+=(d-x);
}
else{
cost+=(x-d);
if(a[i][j]<0)a[i][j]+=(x-d);
else a[i][j]-=(x-d);
}
if(x<=d){
if(a[i][j]<0)b[i][j]+=x;
else b[i][j]-=x;
}
else{
if(b[i][j]<0)b[i][j]-=(2*d-x);
else b[i][j]+=(2*d-x);
}
}
}
}
int lim=d*n*n;lim/=2;
if(cost<=lim){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)cout<<a[i][j]<<" ";
cout<<endl;
}
return 0;
}
else{
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)cout<<b[i][j]<<" ";
cout<<endl;
}
}
return 0;
}