初賽(B)1005 度度熊的交易計劃(【網路流】)
阿新 • • 發佈:2019-01-09
【中文題意】
度度熊的交易計劃 Accepts: 460 Submissions: 2329
Time Limit: 12000/6000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
度度熊參與了喵哈哈村的商業大會,但是這次商業大會遇到了一個難題:
喵哈哈村以及周圍的村莊可以看做是一共由n個片區,m條公路組成的地區。
由於生產能力的區別,第i個片區能夠花費a[i]元生產1個商品,但是最多生產b[i]個。
同樣的,由於每個片區的購買能力的區別,第i個片區也能夠以c[i]的價格出售最多d[i]個物品。
由於這些因素,度度熊覺得只有合理的調動物品,才能獲得最大的利益。
據測算,每一個商品運輸1 公里,將會花費1元。
那麼喵哈哈村最多能夠實現多少盈利呢?
Input
本題包含若干組測試資料。 每組測試資料包含: 第一行兩個整數n,m表示喵哈哈村由n個片區、m條街道。 接下來n行,每行四個整數a[i],b[i],c[i],d[i]表示的第i個地區,能夠以a[i]的價格生產,最多生產b[i]個,以c[i]的價格出售,最多出售d[i]個。 接下來m行,每行三個整數,u[i],v[i],k[i],表示該條公路連線u[i],v[i]兩個片區,距離為k[i]
可能存在重邊,也可能存在自環。
滿足: 1<=n<=500, 1<=m<=1000, 1<=a[i],b[i],c[i],d[i],k[i]<=1000 , 1<=u[i],v[i]<=n
Output
輸出最多能賺多少錢。
Sample Input
2 1
5 5 6 1
3 5 7 7
1 2 1
Sample Output
23
【思路分析】
要求最大的利益,而且可以進行物品的調動,想到了最小費用最大流,從網上抄了個板子就搞上了,設一個源點和一個匯點就好了。
【AC程式碼】
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<bitset>
#include<queue>
using namespace std;
template<typename flow_t, typename cost_t>
struct MCMF
{
static const int N = 2000, M = 10000;
const flow_t inf = 1e9;
struct node
{
int from, to, nxt;
flow_t cap, flow;
cost_t cost;
node() {}
node(int from, int to, int nxt, flow_t cap, cost_t cost):
from(from), to(to), nxt(nxt), cap(cap), flow(0), cost(cost) {}
} E[M];
cost_t dis[N];
int G[N], pre[N], vis[N], n, m;
void init(int n)
{
this->n = n;
this->m = 0;
fill(G, G + n, -1);
}
void add(int u, int v, flow_t f, cost_t c)
{
E[m] = node(u, v, G[u], f, +c);
G[u] = m++;
E[m] = node(v, u, G[v], 0, -c);
G[v] = m++;
}
bool bfs(int S, int T)
{
fill(vis, vis + n, 0);
fill(dis, dis + n, inf);
queue<int> queue;
dis[S] = 0;
queue.push(S);
for (; !queue.empty(); queue.pop())
{
int u = queue.front();
vis[u] = false;
for (int it = G[u]; ~it; it = E[it].nxt)
{
int v = E[it].to;
if (E[it].cap > E[it].flow && dis[v] > dis[u] + E[it].cost)
{
dis[v] = dis[u] + E[it].cost;
pre[v] = it;
if (!vis[v]) queue.push(v);
vis[v] = true;
}
}
}
return dis[T] < 0; // 改成dis[T] <= 0 求可行流
}
int Mincost(int S, int T)
{
flow_t max_flow = 0;
cost_t min_cost = 0;
while (bfs(S, T))
{
flow_t delta = inf;
for (int u = T; u != S; u = E[pre[u]].from)
{
delta = std::min(delta, E[pre[u]].cap - E[pre[u]].flow);
}
min_cost += delta * dis[T];
max_flow += delta;
for (int u = T; u != S; u = E[pre[u]].from)
{
E[pre[u]].flow += delta;
E[pre[u] ^ 1].flow -= delta;
}
}
return min_cost;
}
};
int main()
{
int n, m;
int a, b, c, d;
while(~ scanf("%d %d", &n, &m) )
{
MCMF<int, int> mcmf;
mcmf.init(n + 2);
int S = 0, T = n + 1;
for(int i = 1; i <= n; i ++)
{
scanf("%d %d %d %d", &a, &b, &c, &d);
mcmf.add(S, i, b, a);
mcmf.add(i, T, d, -c);
}
for(int i = 1; i <= m; i ++)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
mcmf.add(u, v, mcmf.inf, w);
mcmf.add(v, u, mcmf.inf, w);
}
int re = mcmf.Mincost(S, T);
printf("%d\n",-re);
}
return 0;
}