跳到正文

题解

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

tophao约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月29日
收录
2026年9月10日
更新
2026年11月21日
篇幅
约 3 分钟
获赞
2
题目
P17022

版本

  1. v1当前

P17022 [ROI 2026 Day2] 广义象棋

题目大意

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

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

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

正解思路

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

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

最后输出的时候:

  • 如果红黑的最大值的位置相等,则用红的最大值搭配黑的次大值,或黑的最搭值搭配红的次大值。
  • 否则直接用红和黑的最大值。

代码

C++
#include <bits/stdc++.h>

using namespace std;

int n;
const int N=405;
int m[N*N],m1[N*N];
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<<i*j-max(hmax1+hmax4,hmax2+hmax3)<<' ';
			}
			else{
				cout<<j*i-(hmax1+hmax3)<<' ';
			}
		}
		cout<<"\n";
	}
	return 0;
}
原文
存档评论4 条抓取于