【BZOJ1877】最小费用流

BZOJ1877
乍一看以为是一个dp,其实分析之后可以发现,每个点每个边只能走一次,所以将点拆开,将流量设为1,跑MCMF这题就没了…

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
const int maxn= 2020;
using namespace std;
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> min_cost_max_flow(int s, int t) {
    int flow = 0;
    int cost = 0;
    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() 
{
    int n, m, s, t;
    scanf("%d%d",&n,&m);
    s = 1,t = 2*n;
    for(int i=1;i<=n;i++) add_edge(i,i+n,1,0);
    add_edge(s,n+1,INF,0);
    add_edge(n,t,INF,0);
    for(int i=0;i<m;i++)
    {
    	int x,y,z;
    	scanf("%d%d%d",&x,&y,&z);
    	add_edge(x+n,y,1,z);
	}
	pair<int, int>ans = min_cost_max_flow(s, t);
	printf("%d %d\n",ans.first,ans.second); 
    return 0;
}
发布了159 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/KIKO_caoyue/article/details/99953774