1 Star 0 Fork 0

南陽劉子驥/OI Codes

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
p1004.cpp 1.76 KB
一键复制 编辑 原始数据 按行查看 历史
南陽劉子驥 提交于 2022-06-15 14:11 . 20220615
#include<bits/stdc++.h>
#define pfin (i-1)*n+j
#define pfout (i-1)*n+j+n*n
using namespace std;
const int N = 5010, M = 100010, INF = 1e8;
int n, m, S, T;
int h[N], e[M], f[M], w[M], ne[M], idx;
int q[N], d[N], pre[N], incf[N];
bool st[N];
int nums[10][10];
void add(int a, int b, int c, int d)
{
e[idx] = b, f[idx] = c, w[idx] = d, ne[idx] = h[a], h[a] = idx++;
e[idx] = a, f[idx] = 0, w[idx] = -d, ne[idx] = h[b], h[b] = idx++;
}
bool spfa()
{
int hh = 0, tt = 1;
memset(d, 0x3f, sizeof d);
memset(incf, 0, sizeof incf);
q[0] = S, d[S] = 0, incf[S] = INF;
while(hh != tt)
{
int t = q[hh++];
if(hh == N) hh = 0;
st[t] = false;
for(int i = h[t]; ~i; i = ne[i])
{
int ver = e[i];
if(f[i] && d[ver] > d[t] + w[i])
{
d[ver] = d[t] + w[i];
pre[ver] = i;
incf[ver] = min(f[i], incf[t]);
if(!st[ver])
{
q[tt++] = ver;
if(tt == N) tt = 0;
st[ver] = true;
}
}
}
}
return incf[T] > 0;
}
void EK(int &flow, int &cost)
{
flow = cost = 0;
while(spfa())
{
int t = incf[T];
flow += t, cost += t * d[T];
for(int i = T; i != S; i = e[pre[i] ^ 1])
{
f[pre[i]] -= t;
f[pre[i] ^ 1] += t;
}
}
}
int main()
{
scanf("%d", &n);
memset(h, -1, sizeof h);
int a, b, c;
while(scanf("%d%d%d", &a, &b, &c))
{
if((a == 0) && (b == 0) && (c == 0))break;
nums[a][b] = c;
}
S = 0, T = 2 * n * n + 1;
add(S, 1, 2, 0);
add(2 * n * n, T, 2, 0);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
{
add(pfin, pfout, 1, -nums[i][j]);
add(pfin, pfout, 1, 0);
if(j != n)add(pfout, pfin + 1, 2, 0);
if(i != n)add(pfout, pfin + n, 2, 0);
}
}
int flow, cost;
EK(flow, cost);
printf("%d\n", -cost);
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/kaiserwilheim/OIcodes.git
git@gitee.com:kaiserwilheim/OIcodes.git
kaiserwilheim
OIcodes
OI Codes
master

搜索帮助