版权声明:https://blog.csdn.net/qq_41730082 https://blog.csdn.net/qq_41730082/article/details/88883897
题目链接
这道题的建边倒是不难,但是要想到的是要去建一个从一点到另一点一个流量为INF但是费用为0的边,而有价值的边的时候,我们建立的边就是流量为1,并且费用为负价值的边。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int S = 0, maxN = 407, maxE = 4e3 + 7;
int A, B, P, Q, head[maxN], cnt, T, pre[maxN], Flow[maxN], dist[maxN];
bool inque[maxN];
queue<int> Que;
struct Eddge
{
int nex, u, v, flow, cost;
Eddge(int a=-1, int b=0, int c=0, int d=0, int f=0):nex(a), u(b), v(c), flow(d), cost(f) {}
}edge[maxE];
inline void addEddge(int u, int v, int flow, int cost)
{
edge[cnt] = Eddge(head[u], u, v, flow, cost);
head[u] = cnt++;
}
inline void _add(int u, int v, int flow, int cost) { addEddge(u, v, flow, cost); addEddge(v, u, 0, -cost); }
bool spfa()
{
memset(pre, -1, sizeof(pre)); memset(inque, false, sizeof(inque)); memset(dist, INF, sizeof(dist));
while(!Que.empty()) Que.pop(); Que.push(S); Flow[S] = INF; dist[S] = 0; inque[S] = true;
while(!Que.empty())
{
int u = Que.front(); inque[u] = false; Que.pop();
for(int i=head[u], v, flow, cost; ~i; i=edge[i].nex)
{
v = edge[i].v; flow = edge[i].flow; cost = edge[i].cost;
if(flow && dist[v] > dist[u] + cost)
{
dist[v] = dist[u] + cost;
pre[v] = i;
Flow[v] = min(Flow[u], flow);
if(!inque[v])
{
inque[v] = true;
Que.push(v);
}
}
}
}
return pre[T] ^ -1;
}
int EK()
{
int ans = 0;
while(spfa())
{
int now = T, last = pre[now];
while(now)
{
edge[last].flow -= Flow[T];
edge[last^1].flow += Flow[T];
now = edge[last].u;
last = pre[now];
}
ans += dist[T] * Flow[T];
}
return -ans;
}
inline void init()
{
cnt = 0; T = (Q + 1) * (P + 1) + 1;
memset(head, -1, sizeof(head));
}
int main()
{
scanf("%d%d", &A, &B);
scanf("%d%d", &P, &Q);
init();
for(int i=0, e1, now_id, to_id; i<=P; i++)
{
for(int j=1; j<=Q; j++)
{
scanf("%d", &e1);
now_id = i * (Q + 1) + j;
to_id = now_id + 1;
_add(now_id, to_id, 1, -e1);
_add(now_id, to_id, INF, 0);
}
}
for(int i=0, e1, now_id, to_id; i<=Q; i++)
{
for(int j=1; j<=P; j++)
{
scanf("%d", &e1);
now_id = (j - 1) * (Q + 1) + i + 1;
to_id = now_id + Q + 1;
_add(now_id, to_id, 1, -e1);
_add(now_id, to_id, INF, 0);
}
}
for(int i=1, k, x, y; i<=A; i++)
{
scanf("%d%d%d", &k, &x, &y);
int id = x * (Q + 1) + y + 1;
_add(S, id, k, 0);
}
for(int i=1, k, x, y; i<=B; i++)
{
scanf("%d%d%d", &k, &x, &y);
int id = x * (Q + 1) + y + 1;
_add(id, T, k, 0);
}
printf("%d\n", EK());
return 0;
}