#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define maxn 5550
#define maxm 25000
#define Inf 210000000
using namespace std;
struct Edge{
int u, v, cap ,flow, cost;
int next;
}e[maxm];
int fi[maxn], ecnt = 0;
int d[maxn], a[maxn], p[maxn];
bool inq[maxn];
int flow = 0, cost = 0;
int s, t, N;
void add_edge(int u, int v, int cap , int cost) {
e[ecnt] = (Edge){u, v, cap, 0, cost, fi[u]};
fi[u] = ecnt;
ecnt++;
}
bool spfa(int s, int t) {
memset(d, -1, sizeof(d));
memset(inq, 0, sizeof(inq));
d[s] = 0, inq[s] = 1, p[s] = 0, a[s] = Inf;
int q[maxn*10], head = 0, tail = 1;
q[head] = s;
while(head < tail) {
int u = q[head++];
inq[u] = 0;
for(int i = fi[u]; i != -1; i = e[i].next)
if(e[i].cap > e[i].flow && d[e[i].v] < d[u] + e[i].cost) {
d[e[i].v] = d[u] + e[i].cost;
p[e[i].v] = i;
a[e[i].v] = min(a[u], e[i].cap - e[i].flow);
if(!inq[e[i].v]) {
q[tail++] = e[i].v, inq[e[i].v] = 1;
}
}
}
if(d[t] == -1) return false;
flow += a[t], cost += d[t]*a[t];
int u = t;
while(u != s) {
e[p[u]].flow += a[t];
e[p[u]^1].flow -= a[t];
u = e[p[u]].u;
}
return true;
}
int main() {
memset(fi, -1, sizeof(fi));
int x, k = 2;
int G[100][100];
scanf("%d", &x);
int n = x*x;
int num = 0;
int a, b, c; scanf("%d%d%d", &a, &b, &c);
while(!(a == 0 && b == 0 && c == 0)) {
G[a][b] = c;
scanf("%d%d%d", &a, &b, &c);
}
for(int i = 1; i <= x; i++)
for(int j = 1; j <= x; j++) {
num++;
add_edge(num, num+n, 1, G[i][j]);
add_edge(num+n, num, 0, -G[i][j]);
add_edge(num, num+n, k, 0);
add_edge(num+n, num, 0, 0);
if(i != x)
add_edge(num+n, num+x, Inf, 0), add_edge(num+x, num+n, 0, 0);
if(j != x)
add_edge(num+n, num+1, Inf, 0), add_edge(num+1, num+n, 0, 0);
}
N = n*2+2;
s = N-1, t = N;
add_edge(s, 1, k, 0); add_edge(1, s, 0, 0);
add_edge(num+n, t, Inf, 0); add_edge(t, num+n, 0, 0);
while(spfa(s, t));
printf("%d", cost);
return 0;
}
codevs 1227 方格取数
最新推荐文章于 2024-08-01 12:10:06 发布