poj3680(费用流)

经典构图题。先将所有区间端点离散化到整数 1..M,另加源 s=0,汇 t=M+1;对
每个点 i (0 <= i <= M)加边(i, i+1, K, 0);对每个区间(ai, bi)加边(ai’, bi’, 1, -wi),其中

ai’, bi’分别表示 ai, bi 离散化后对应的数值。求一次最小费用流再取反即为结果

#include
#include
#include
#include
using namespace std;
#define INF 0x3f3f3f3f
const int maxn = 505;
const int N = 505;
struct Edge
{
    int from,to,cap,flow,cost;
    Edge(int u,int v,int ca,int f,int co):from(u),to(v),cap(ca),flow(f),cost(co){};
};

struct MCMF
{
    int n,m,s,t;
    vector edges;
    vector G[N];
    int inq[N];//是否在队列中
    int d[N];//距离
    int p[N];//上一条弧
    int a[N];//可改进量

    void init(int n)//初始化
    {
        this->n=n;
        for(int i=0;i Q;
        Q.push(s);
        while(!Q.empty())
        {
            int u=Q.front();
            Q.pop();
            inq[u]--;
            for(int i=0;ie.flow && d[e.to]>d[u]+e.cost)//满足可增广且可变短
                {
                    d[e.to]=d[u]+e.cost;
                    p[e.to]=G[u][i];
                    a[e.to]=min(a[u],e.cap-e.flow);
                    if(!inq[e.to])
                    {
                        inq[e.to]++;
                        Q.push(e.to);
                    }
                }
            }
        }
        if(d[t]==INF) return false;//汇点不可达则退出
        flow+=a[t];
        cost+=d[t]*a[t];
        int u=t;
        while(u!=s)//更新正向边和反向边
        {
            edges[p[u]].flow+=a[t];
            edges[p[u]^1].flow-=a[t];
            u=edges[p[u]].from;
        }
        return true;
    }

    int MincotMaxflow(int s,int t)
    {
        int flow=0,cost=0;
        while(SPFA(s,t,flow,cost));
        return cost;
    }
}mcmf;
int u[maxn],v[maxn],w[maxn];
int tmp[maxn<<1],pos[maxn<<1];
int main()
{
    int cases,n,k;
    scanf("%d",&cases);
    while(cases--)
    {
        scanf("%d%d",&n,&k);
        int id = 1; mcmf.init(2*n+10);
        for(int i=1;i<=n;i++)
        {
            scanf("%d%d%d",&u[i],&v[i],&w[i]);
            tmp[id++] = u[i];
            tmp[id++] = v[i];
        }
        sort(tmp+1,tmp+id);
        int len = 1; int s = 0; int t; pos[len] = tmp[1];
        for(int i=2;itmp[i-1]) pos[++len] = tmp[i];
        //for(int i=1;i<=len;i++) printf("%d ",pos[i]); printf("\n");
        t = len+1;
        for(int i=0;i<=len;i++) mcmf.addedge(i,i+1,k,0);
        for(int i=1;i<=n;i++)
        {
            int l = lower_bound(pos+1,pos+len+1,u[i])-pos-1;
            int r = lower_bound(pos+1,pos+len+1,v[i])-pos-1;
            //printf("%d %d\n",l,r);
            mcmf.addedge(l,r,1,-w[i]);
        }
        int ans = mcmf.MincotMaxflow(s,t);
        printf("%d\n",-ans);
    }
    return 0;
}


你可能感兴趣的:(图论)