跳到正文

题解

题解:AT_arc119_d [ARC119D] Grid Repainting 3

zhengpie约 4 分钟
原文

这是 2026年3月30日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年3月26日
收录
2026年3月30日
更新
2026年11月9日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

思路

经典的 trick,看到这种类似矩形表格的图可以考虑图论建模,建成一个二分图。

考虑每一个在 (i,j)(i,j) 的红色格子,不妨从 ii 向 j+Hj + H 连一条无向边,那么我们就得到了一个二分图。

不难发现不同连通块之间是互不影响的,不妨先对焦一个连通块内部的情况。

对于一个连通块,发现在一个对二分图上的一个点的操作就是将其连接的所有边全部断开。(因为染色后所有其他红色点全部失效,变成白色点)那么在遍历一个连通块的时候,不妨对于每个遍历到的点都操作,此时一定会剩下一个点无法操作(因为这个点本来连的边被删光了)。

考虑枚举连通块最后剩下的点在二分图的一侧的数量对涂成白色的格子数的影响,发现这很难算。正难则反,考虑计算非白色格子数的最小值,列出其的式子为:

min⁡x=0k(H−l+x)×(W−r+(k−x))\min{_{x=0}^{k} (H - l + x) \times (W-r+(k-x))}

其中的 l,r,kl,r,k 分别表示遍历时经过的二分图左侧(表示行的那侧)的点的总数,经过的二分图右侧(表示列的那侧)的点的总数,连通块的总数。

至于为何是这样的式子,请读者自证。(提示:将图画出来后很好证)

此时的构造是好做的,分别在每个联通块里跑 dfs 就行了。

时间复杂度 O(nm)O(nm),瓶颈在于最后的构造。

代码

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ioimprove(); ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define FILE(x); freopen(x".in","r",stdin);freopen(x".out","w",stdout);
int n,m,vis[5005],cntscc,cntl,cntr,lmax;
vector<int> g[5005],scc[5005];
char ch[2505][2505];
void dfs(int root)
{
	vis[root] = 1;scc[cntscc].push_back(root);
	if(root <= n) cntl++;
	else cntr++;
	for(int i : g[root])
		if(!vis[i]) dfs(i);
}
void dfs2(int root,int fa)
{
	vis[root] = 1;
	for(int i : g[root]) if(!vis[i]) dfs2(i,root);
	if(fa)
	{
		if(root <= n) cout<<"X "<<root<<" "<<fa - n<<"\n";
		else cout<<"Y "<<fa<<" "<<root - n<<"\n";
	}
}
signed main()
{
	ioimprove();
	cin>>n>>m;
	for(int i = 1;i <= n;i++)
		for(int j = 1;j <= m;j++)	
		{
			cin>>ch[i][j];
			if(ch[i][j] == 'R') g[i].push_back(j + n),g[j + n].push_back(i);
		}
	for(int i = 1;i <= n;i++) if(!vis[i] && !g[i].empty()) ++cntscc,dfs(i);
	for(int i = 1;i <= cntscc;i++) if((n - cntl + lmax) * (m - cntr + cntscc - lmax) > (n - cntl + i) * (m - cntr + cntscc - i)) lmax = i;
	int q = cntl + cntr - cntscc;
	cout<<q<<"\n";
	memset(vis,0,sizeof vis);
	for(int i = 1;i <= lmax;i++)
		for(int u : scc[i]) if(u <= n) {dfs2(u,0);break;}
	for(int i = lmax + 1;i <= cntscc;i++)
		for(int u : scc[i]) if(u > n) {dfs2(u,0);break;}
	
	return 0;
}