zoukankan      html  css  js  c++  java
  • 最长k可重区间集问题

    费用流,离散化后,l向r连费用为负长度的边容量为1
    相邻的连容量为k的边,最好建S和T

    # include <bits/stdc++.h>
    # define RG register
    # define IL inline
    # define Fill(a, b) memset(a, b, sizeof(a))
    # define Copy(a, b) memcpy(a, b, sizeof(a))
    using namespace std;
    typedef long long ll;
    const int _(1010), __(1e6 + 10), INF(2e9);
    
    IL ll Read(){
        char c = '%'; ll x = 0, z = 1;
        for(; c > '9' || c < '0'; c = getchar()) if(c == '-') z = -1;
        for(; c >= '0' && c <= '9'; c = getchar()) x = x * 10 + c - '0';
        return x * z;
    }
    
    int n, k, l[_], r[_], o[_], len;
    int cnt, fst[_], w[__], to[__], nxt[__], dis[_], vis[_], S, T, cost[__], pe[_], pv[_], max_flow, max_cost;
    queue <int> Q;
    
    IL void Add(RG int u, RG int v, RG int f, RG int co){
        cost[cnt] = co; w[cnt] = f; to[cnt] = v; nxt[cnt] = fst[u]; fst[u] = cnt++;
        cost[cnt] = -co; w[cnt] = 0; to[cnt] = u; nxt[cnt] = fst[v]; fst[v] = cnt++;
    }
    
    IL bool Bfs(){
        Q.push(S); Fill(dis, 127); dis[S] = 0; vis[S] = 1;
        while(!Q.empty()){
            RG int u = Q.front(); Q.pop();
            for(RG int e = fst[u]; e != -1; e = nxt[e]){
                if(!w[e] || dis[to[e]] <= dis[u] + cost[e]) continue;
                dis[to[e]] = dis[u] + cost[e];
                pe[to[e]] = e; pv[to[e]] = u;
                if(!vis[to[e]]) vis[to[e]] = 1, Q.push(to[e]);
            }
            vis[u] = 0;
        }
        if(dis[T] >= dis[T + 1]) return 0;
        RG int ret = INF;
        for(RG int u = T; u != S; u = pv[u]) ret = min(ret, w[pe[u]]);
        for(RG int u = T; u != S; u = pv[u]) w[pe[u]] -= ret, w[pe[u] ^ 1] += ret;
        max_cost -= ret * dis[T]; max_flow += ret;
        return 1;
    }
    
    int main(RG int argc, RG char *argv[]){
        Fill(fst, -1); n = Read(); k = Read();
        for(RG int i = 1; i <= n; ++i){
            l[i] = Read(); r[i] = Read();
            o[++cnt] = l[i]; o[++cnt] = r[i];
        }
        sort(o + 1, o + cnt + 1); len = unique(o + 1, o + cnt + 1) - o - 1;
        cnt = 0; T = len + 1;
        for(RG int i = 0; i <= len; ++i) Add(i, i + 1, k, 0);
        for(RG int i = 1; i <= n; ++i){
            if(l[i] >= r[i]) continue;
            RG int le = r[i] - l[i];
            l[i] = lower_bound(o + 1, o + len + 1, l[i]) - o;
            r[i] = lower_bound(o + 1, o + len + 1, r[i]) - o;
            Add(l[i], r[i], 1, -le);
        }
        while(Bfs()); printf("%d
    ", max_cost);
        return 0;
    }
    
  • 相关阅读:
    linux 树型显示文件 tree ls tree 命令
    Linux常用命令大全
    My kingdom for a good timer! 规格严格
    org.dom4j.DocumentException: no protocol 规格严格
    利用GetObject("WinMgmts:")获取系统信息 规格严格
    给力URL 规格严格
    几个Servlet小Sample网站 规格严格
    使用SQL PLUS生成报表 规格严格
    High Resolution Timer in Java 5 规格严格
    GC调优文章精选:逐步添加 规格严格
  • 原文地址:https://www.cnblogs.com/cjoieryl/p/8206324.html
Copyright © 2011-2022 走看看