[代码]UVALive 5882 Racing Car Trail
Abstract
UVALive 5882 Racing Car Trail
博弈 二分图
解题报告见http://www.cnblogs.com/jffifa/archive/2011/12/17/2291069.html
Body
代码写得又长又烂。
#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int, int> pr;
pr (*mkpr)(int, int)=make_pair;
const int S = 10005;
int di[] = {0, 1, 0, -1};
int dj[] = {1, 0, -1, 0};
int X, Y;
int N, M;
int ban;
vector<int> adj[S], radj[S];
int match[S];
int m[S], rm[S];
int matchcnt;
bool vis[S];
char mdk[105][105];
char ans[105][105];
int cnt;
int f[105][105];
map<int, pr> g;
bool dfs(vector<int> adj[], int u)
{
int v;
for (int i = 0; i < adj[u].size(); ++i)
{
v = adj[u][i];
if (v==ban || vis[v]) continue;
vis[v] = 1;
if (!match[v] || dfs(adj, match[v]))
{
match[v] = u;
return 1;
}
}
return 0;
}
int hungarian()
{
int res = 0;
memset(match, 0, sizeof(match));
for (int u = 1; u <= X; ++u)
{
memset(vis, 0, sizeof(vis));
if (dfs(adj, u)) ++res;
}
return res;
}
int main()
{
int i, j, k, u, v;
while (scanf("%d%d", &N, &M), N||M)
{
ban = cnt = X = Y = 0;
g.clear();
for (i = 0; i < N; ++i)
scanf("%s", mdk[i]);
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j)
{
if (mdk[i][j]=='X'||(i+j)&1) continue;
X++;
cnt++;
f[i][j] = cnt;
g[cnt] = mkpr(i, j);
}
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j)
{
if (mdk[i][j]=='X'||((i+j)&1)==0) continue;
Y++;
cnt++;
f[i][j] = cnt;
g[cnt] = mkpr(i, j);
}
for (u = 1; u <= cnt; ++u)
{
adj[u].clear();
radj[u].clear();
}
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j)
{
if (mdk[i][j]=='X'||((i+j)&1)!=0) continue;
for (k = 0; k < 4; ++k)
{
int ni = i+di[k];
int nj = j+dj[k];
if (ni>=0&&ni<N&&nj>=0&&nj<M&&mdk[ni][nj]!='X')
{
adj[f[i][j]].push_back(f[ni][nj]);
radj[f[ni][nj]].push_back(f[i][j]);
}
}
}
matchcnt = hungarian();
memset(ans, 0, sizeof(ans));
memset(m, 0, sizeof(m));
memset(rm, 0, sizeof(rm));
for (u = X+1; u <= cnt; ++u)
{
m[u] = match[u];
if (!m[u])
{
i = g[u].first;
j = g[u].second;
ans[i][j] = 'B';
}
else rm[m[u]] = u;
}
for (u = 1; u <= X; ++u)
{
if (!rm[u])
{
i = g[u].first;
j = g[u].second;
ans[i][j] = 'B';
}
}
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j)
{
if (ans[i][j]) continue;
if (mdk[i][j]=='X')
{
ans[i][j] = 'X';
continue;
}
ban = f[i][j];
memset(vis, 0, sizeof(vis));
if ((i+j)&1)
{
memcpy(match, m, cnt+1<<2);
u = match[f[i][j]];
match[f[i][j]] = 0;
if (dfs(adj, u)) ans[i][j] = 'B';
else ans[i][j] = 'A';
}
else
{
memcpy(match, rm, cnt+1<<2);
u = match[f[i][j]];
match[f[i][j]] = 0;
if (dfs(radj, u)) ans[i][j] = 'B';
else ans[i][j] = 'A';
}
}
for (i = 0; i < N; ++i)
puts(ans[i]);
puts("");
}
return 0;
}