**楼主求助
查看原帖
**楼主求助
668875
_Pluckyduck_楼主2022/2/14 17:56

我xjb打的,套的最小费用流模板,样例过不了,lg上20pts

#include<bits/stdc++.h>
#define inf 2147483647
using namespace std;
typedef pair<int,int> PII;
const int N = 405, M = 4e4 + 5;
static char buf[100000],*pa=buf,*pd=buf;
#define gc pa==pd&&(pd=(pa=buf)+fread(buf,1,100000,stdin),pa==pd)?EOF:*pa++
inline int read()
{
    register int x(0);register char c(gc);
    while(c<'0'||c>'9')c=gc;
    while(c>='0'&&c<='9')x=(x<<1)+(x<<3)+(c^48),c=gc;
    return x;
}

struct node {
    int to, edg;
}pre[N];
int n, m, s, t, maxflow, mincost;
int h[N], e[M<<1], w[M<<1], cost[M<<1], ne[M<<1], idx = 1;
int dis[N], H[N], vis[N];
inline void add(int x, int y, int z, int co)
{
    e[++ idx] = y, w[idx] = z, cost[idx] = co, ne[idx] = h[x], h[x] = idx;
}
void spfa()
{
    queue<int> q;
    for(int i = 1;i <= 2 * n;i ++)
        H[i] = inf;
    H[s] = 0, vis[s] = 1;
    q.push(s);
    while(!q.empty())
    {
        int u = q.front();
        q.pop();
        vis[u] = 0;
        for(int i = h[u];i;i = ne[i])
        {
            int j = e[i];
            if(w[i] && H[j] > H[u] + cost[i])
            {
                H[j] = H[u] + cost[i];
                if(!vis[j])
                {
                  vis[j] = 1;
                  q.push(j);
                }
            }
        }
    }
}
inline bool dij()
{
    priority_queue<PII, vector<PII>, greater<PII> > hp;
    for(int i = 1;i <= 2 * n;i ++)
        dis[i] = inf, vis[i] = 0;
    dis[s] = 0;
    hp.push({0, s});
    while(!hp.empty())
    {
        int u = hp.top().second;
        hp.pop();
        if(vis[u])
            continue;
        vis[u] = 1;
        for(int i = h[u];i;i = ne[i])
        {
            int j = e[i], tmp = cost[i] + H[u] - H[j];
            if(w[i] && dis[j] > dis[u] + tmp)
            {
                dis[j] = dis[u] + tmp;
                pre[j].to = u;
                pre[j].edg = i;
                if(!vis[j]) 
                    hp.push({dis[j], j});
            }
        }
    }
    return dis[t] != inf;
}
int main()
{
    n = read(), m = read();
    s = 1 + n, t = n;
    for(int i = 1;i <= m;i ++)
    {
        int x = read(), y = read(), z = read();
        add(x + n, y, 1, z);
        add(y + n, x, 0, -z);
    }
    for(int i = 1;i <= n;i ++)
    {
		add(i, i + n, 1, 0);
		add(i + n, i, 0, 0);
	}
    spfa();
    while(dij())
    {
        int minf = inf;
        for(int i = 1;i <= 2 * n;i ++)
            H[i] += dis[i];
        for(int i = t;i != s;i = pre[i].to)
            minf = min(minf, w[pre[i].edg]);
        for(int i = t;i != s;i = pre[i].to)
        {
            w[pre[i].edg] -= minf;
            w[pre[i].edg ^ 1] += minf;
        }
        maxflow += minf;
        mincost += minf * H[t];
    }
    printf("%d %d",maxflow,mincost);
    return 0;
}

2022/2/14 17:56
加载中...