题解:P17022 [ROI 2026 Day2] 广义象棋

· · 题解

P17022 [ROI 2026 Day2] 广义象棋

题目大意

给定一个 n \times n 的棋盘,棋盘上涂有若干颜色。

对于每一组 (i,j),求把前 i 行、前 j 列修改成合法棋盘最少需要修改多少个格子。

合法棋盘要求:仅使用两种颜色,且任意相邻格子颜色不相同。

正解思路

数据范围 N \le 400,可以考虑三重循环。 从一行转移到下一行时,上一行的部分状态不能继续沿用,因此需要额外两层循环来计算求值。

合法棋盘是红黑交替的二色棋盘。 维护红,黑色格子的最大代价、次大代价,以及对应颜色编号。

最后输出的时候:

using namespace std;

int n; const int N=405; int m[NN],m1[NN]; int a[N][N],b[N*N];

int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>n; int cnt=0,len=0; for(int i=1;i<=n;++i){ for(int j=1;j<=n;++j){ cin>>a[i][j]; b[++len]=a[i][j]; } } sort(b+1,b+len+1); len=unique(b+1,b+len+1)-(b+1); for(int i=1;i<=n;++i){ for(int j=1;j<=n;++j){ a[i][j]=lower_bound(b+1,b+len+1,a[i][j])-b;; } } int hmax1=0,hmax2=0,hmax3=0,hmax4=0,id1=0,id2=0; for(int i=1;i<=n;++i){ hmax1=0,hmax2=0,hmax3=0,hmax4=0,id1=0,id2=0; memset(m,0,sizeof(m)); memset(m1,0,sizeof(m1)); for(int j=1;j<=n;++j){ for(int k=1;k<=i;++k){ int t=a[k][j]; if((k+j)%2==0){ m[t]++; if(m[t]>=hmax1){ if(t==id1){ hmax1=m[t]; } else{ hmax2=hmax1; hmax1=m[t]; id1=t; } } else{ hmax2=max(hmax2,m[t]); } } else{ m1[t]++; if(m1[t]>=hmax3){ if(t==id2){ hmax3=m1[t]; } else{ hmax4=hmax3; hmax3=m1[t]; id2=t; } } else{ hmax4=max(hmax4,m1[t]); } } } if(id1==id2){ cout<<ij-max(hmax1+hmax4,hmax2+hmax3)<<' '; } else{ cout<<ji-(hmax1+hmax3)<<' '; } } cout<<"\n"; } return 0; }