题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=6118
分析: 看题意知道了是求最大价值,那么我们转换一下加个负号就变成了最小费用最大流,建图嘛,因为每个点都费用,所以把点拆分成两个,然后建图。我们弄一个起始点和终点,然后连接到每个点上,起始点到片区的流量为bi,点到终点的流量为di,然后片区到片区的消费一商品价值 cj - ai - 两地最短路(这个可以用floyd算),当大于0的时候说明这两地是盈利的。所以可加边 i ->j+n,流量最大,费用为盈利的负数
代码如下:
#include
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int MAXN = 1005;
const int MAXM = 500005;
LL low[MAXN][MAXN];
int a[MAXN],b[MAXN],c[MAXN],d[MAXN];
int n,m;
struct Edge{ //MAXN为点数,MAXM为边数
int to,nxt,cap,flow,cost;
}edge[MAXM<<2];
int head[MAXN],cnt;
bool vis[MAXN];
int pre[MAXN];
LL dis[MAXN];
int N;
void init(int n){
N=n;
cnt=0;
memset(head,-1,sizeof(head));
}
void add(int u,int v,int cap,int cost){
edge[cnt].to=v;
edge[cnt].cap=cap;
edge[cnt].cost=cost;
edge[cnt].flow=0;
edge[cnt].nxt=head[u];
head[u]=cnt++;
}
void add_edge(int u,int v,int cap,int cost){
add(u,v,cap,cost);
add(v,u,0,-cost);
}
bool spfa(int s,int t){
queue Q;
for(int i=0;iedge[i].flow&&dis[v]>dis[u]+edge[i].cost){
dis[v]=dis[u]+edge[i].cost;
pre[v]=i;
if(!vis[v]){
vis[v]=true;
Q.push(v);
}
}
}
}
if(pre[t]==-1) return false;
else return true;
}
//返回的是最大流,cost存的是最小费用
//求流为K时的最小费用时,S与开始的点连流为K,费用为0的边
int minCostMaxFlow(int s,int t,LL &cost){
int flow=0;
cost=0;
while(spfa(s,t)){
int Min=100000000;
for(int i=pre[t];i!=-1;i=pre[edge[i^1].to]){
if(Min>edge[i].cap-edge[i].flow)
Min=edge[i].cap-edge[i].flow;
}
for(int i=pre[t];i!=-1;i=pre[edge[i^1].to]){
edge[i].flow+=Min;
edge[i^1].flow-=Min;
cost+=(LL)edge[i].cost*Min;
}
flow+=Min;
}
return flow;
}
void floyd() {
for(int k = 1; k <= n; k++) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(low[i][j] > low[i][k] + low[k][j])
low[i][j] = low[i][k] + low[k][j];
}
}
}
}
int main() {
while(scanf("%d%d",&n,&m) != EOF) {
for(int i = 1; i <= n; i++) {
scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
}
memset(low,INF,sizeof(low));
for(int i = 1; i <= n; i++) low[i][i] = 0;
int u,v,k;
for(int i = 1; i <= m; i++) {
scanf("%d%d%d",&u,&v,&k);
low[u][v] = min(low[u][v],1LL * k);
low[v][u] = min(low[v][u],1LL * k);
}
floyd();
int s = 0,t = n + n + 1;
init(t+1);
for(int i = 1; i <= n; i++) {
add_edge(s,i,b[i],0);
add_edge(i+n,t,d[i],0);
for(int j = 1;j <= n; j++){
int tp = c[j] - a[i] - low[i][j];
if(tp > 0)
add_edge(i,j+n,1005,-tp);
}
add_edge(i,t,b[i],0); //不知道为啥不加这句就哇了
}
LL ans=0;
minCostMaxFlow(s,t,ans);
printf("%I64d\n",-ans);
}
return 0;
}