【BZOJ1834】最小费用流

题意很好懂
分析:
第一问费用为0的最大流
第二问在残余网络上连边,容量INF,费用W,
然后0->1连k的容量

然后最小费用最大流

#include 
#define INF 0x3f3f3f3f
const int maxn= 5050;
using namespace std;
int n,m,k;
int x[maxn],y[maxn],w[maxn];
struct edge
{
    int to, cap, cost, rev;
};
struct node 
{
    int now;
    int cost;
    bool operator < (const node &a) const 
	{
        return cost > a.cost;
    }
};
vector<edge>G[maxn];
int dis[maxn];
int pv[maxn], pe[maxn];
int h[maxn];
void add_edge(int from, int to, int cap, int cost) 
{
    G[from].push_back({to, cap, cost, G[to].size()});
    G[to].push_back({from, 0, -cost, G[from].size()-1});
}
void dijkstra(int s) 
{
    memset(dis,INF,sizeof(dis));
    dis[s] = 0;
    priority_queue<node>q;
    q.push({s, dis[s]});
    while (!q.empty()) {
        int now = q.top().now;
        int nowc = q.top().cost;
        q.pop();
        if(dis[now]<nowc) continue;
        for (int i = 0; i < G[now].size(); ++i) 
		{
            edge &e = G[now][i];
            if (e.cap > 0 && dis[e.to] > dis[now] + e.cost + h[now]-h[e.to]) 
			{
                dis[e.to] = dis[now] + e.cost + h[now] - h[e.to];
                pv[e.to] = now;
                pe[e.to] = i;
                q.push({e.to, dis[e.to]});
            }
        }
    }
}
pair<int, int> MCMF(int s, int t) {
    int flow = 0;
    int cost = 0;
    memset(dis,0,sizeof(dis));
    memset(h,0,sizeof(h));
    while (true) 
	{
        dijkstra(s);
        if (dis[t] == INF) return {flow, cost};
        for(int i=0;i<maxn;i++)
        {
        	h[i] += dis[i];
		}
        int d = INF;
        for (int v = t; v != s; v = pv[v]) 
		{
            d = min(d, G[pv[v]][pe[v]].cap);
        }
        flow += d;
        cost += d*h[t];
        for (int v = t; v != s; v = pv[v]) 
		{
			edge &e = G[pv[v]][pe[v]];
            e.cap -= d;
            G[v][e.rev].cap += d;
        }       
    }
}
int main() 
{
    scanf("%d%d%d",&n,&m,&k);
    for(int i=1;i<=m;i++)
    {
    	int c;
    	scanf("%d%d%d%d",x+i,y+i,&c,w+i);
    	add_edge(x[i],y[i],c,0);
	}
	int ans1 = MCMF(1,n).first;
	add_edge(0,1,k,0);
	for(int i=1;i<=m;i++)
	{
		add_edge(x[i],y[i],INF,w[i]);
	}
	int ans2 = MCMF(0,n).second;
	printf("%d %d\n",ans1,ans2);
    return 0;
}

你可能感兴趣的:(BZOJ)