跳到正文

题解

UVA 10615 Rooks

idiotgoose约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
题目
UVA10615

版本

  1. v1当前

直接爆搜是不行的,回溯的情况贼多,时间复杂度太大。

我们可以先想想每个点都是车的情况,对于N乘N的图,显然N种颜色就行(每行右移一个)。

然后可以猜测,最少颜色数就是某行/列的最大车数 ma 。(后面会证明)

显然可以建立二分图。

但是我们不能直接求最大匹配、删去匹配边这样重复操作,

给个例子

***.

***.

***.

***.

很容易想明白的。

结果可能是这样

2 3 1 0

3 1 2 0

1 2 3 0

4 0 0 0

所以我们需要补边,让每个点的度都是上面的 ma

这样做之后,每个点度数相同,由定理:二部图存在完备匹配当且仅当V1中任意k个顶点至少与V2中的k个顶点相邻(当V1与V2点数相同时,完备匹配即完美匹配),可以知道,一定存在完美匹配,并且删边后依然如此。所以 ma 次操作后一定可以恰好删完所有的边。

C++
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<vector>
#include<string.h>
#include<queue>
#include<assert.h>
#include<stack>
using namespace std;
const int maxn =100+5;
const int INF = 1e8;
int n;
int arr[maxn][maxn];
vector<int> G[maxn];
int ll[maxn];
int rr[maxn];
int ans[maxn][maxn];
int ma;
void init()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		G[i].clear();
	}
	memset(ans, 0, sizeof(ans));
	ma = 0;
	for (int i = 1; i <= n; i++)
	{
		int cnt = 0;
		for (int g = 1; g <= n; g++)
		{
			char c; scanf(" %c", &c);
			if (c == '*')
			{
				arr[i][g] = 1;
				cnt++;
				G[i].push_back(g);
			}
			else
			{
				assert(c == '.');
				arr[i][g] = 0;
			}
		}
		ma = max(ma, cnt);
		ll[i] = cnt;
	}
	for (int g = 1; g <= n; g++)
	{
		int cnt = 0;
		for (int i = 1; i <= n; i++)
		{
			if (arr[i][g] == 1)
				cnt++;
		}
		ma = max(ma, cnt);
		rr[g] = cnt;
	}
	vector<int> v1, v2;
	for (int i = 1; i <= n; i++)
	{
		int t1 = ma - ll[i];
		int t2 = ma - rr[i];
		while (t1--)
		{
			v1.push_back(i);
		}
		while (t2--)
		{
			v2.push_back(i);
		}
	}
	assert(v1.size() == v2.size());
	for (int i = 0; i < v1.size(); i++)
	{
		G[v1[i]].push_back(v2[i]);
	}

}
int check[maxn];
int match[maxn];
int dfs(int u)
{
	for (int i = 0; i < G[u].size(); i++)
	{
		int v = G[u][i];
		if (!check[v])
		{
			check[v] = 1;
			if (!match[v] || dfs(match[v]))
			{
				match[v] = u; return 1;
			}
		}
	}
	return 0;
}
void KM(int c)
{
	memset(match, 0, sizeof(match));
	for (int i = 1; i <= n; i++)
	{
		memset(check, 0, sizeof(check));
		dfs(i);
	}
	for (int i = 1; i <= n; i++)
	{
		if (match[i])
		{
			if (arr[match[i]][i])
			{
				ans[match[i]][i] = c;
			}
			int u = match[i];
			for (int j = 0; j < G[u].size(); j++)
			{
				int v = G[u][j];
				if (v == i)
				{
					for (int g = j; g < G[u].size() - 1; g++)
					{
						G[u][g] = G[u][g + 1];
					}
					G[u].pop_back();
					break;
				}
			}
		}
	}
}
void solve()
{
	for (int i = 1; i <= ma; i++)
	{
		KM(i);
	}
	cout << ma << endl;
	for (int i = 1; i <= n; i++)
	{
		for (int g = 1; g <= n; g++)
		{
			cout << ans[i][g];
			if (g == n)cout << endl;
			else cout << " ";
		}
	}
}
int main()
{
	int T; cin >> T;
	while (T--)
	{
		init();
		solve();

	}
	return 0;
}
原文