POJ1201: Intervals 题解

差分约束系统的经典题,感觉还挺巧妙的
d[i] d [ i ] 表示0~i的格子中选了多少个数,那么题目中的每个区间就能变成这样的条件: d[b[i]]d[a[i]1]c[i] d [ b [ i ] ] − d [ a [ i ] − 1 ] ≥ c [ i ]
然后发现如果某个 a[i]=0 a [ i ] = 0 的话会出现 d[1] d [ − 1 ] ,所以微调一下定义:设 d[i] d [ i ] 表示0~i-1的格子中选了多少个数,约束条件是 d[b[i]+1]d[a[i]]c[i] d [ b [ i ] + 1 ] − d [ a [ i ] ] ≥ c [ i ]
题目中还有一个隐藏的条件,就是每个格子只能选或不选,所以应该满足 0d[i]d[i1]1 0 ≤ d [ i ] − d [ i − 1 ] ≤ 1 ,由于题目要求的是最小值,所以全部化成大于等于的形式: d[i]d[i1]0 d [ i ] − d [ i − 1 ] ≥ 0 d[i1]d[i]1 d [ i − 1 ] − d [ i ] ≥ − 1
按照差分约束系统的套路建图,然后spfa跑最长路即可

*注意这道题好像卡STL,建图最好用链式前向星

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <utility>
#include <cctype>
#include <algorithm>
#include <bitset>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <cmath>
#define LL long long
#define LB long double
#define x first
#define y second
#define Pair pair<int,int>
#define pb push_back
#define pf push_front
#define mp make_pair
#define LOWBIT(x) x & (-x)
#define DEBUG(...)
using namespace std;

const int MOD=1e9+7;
const LL LINF=2e16;
const int INF=2e9;
const int magic=348;
const double eps=1e-10;

inline int getint()
{
    char ch;int res;bool f;
    while (!isdigit(ch=getchar()) && ch!='-') {}
    if (ch=='-') f=false,res=0; else f=true,res=ch-'0';
    while (isdigit(ch=getchar())) res=res*10+ch-'0';
    return f?res:-res;
}

int n;
int a[100048],b[100048],c[100048];
int dist[200048];
int head[200048],nxt[200048],to[200048],f[200048],tot=1;
inline void addedge(int s,int t,int cap)
{
    to[++tot]=t;nxt[tot]=head[s];head[s]=tot;f[tot]=cap;
}
queue<int> q;bool inq[100048];

inline void spfa()
{
    int i,cur,y;
    memset(inq,false,sizeof(inq));
    for (i=0;i<=60000;i++) dist[i]=-1;
    dist[0]=0;q.push(0);inq[0]=true;
    while (!q.empty())
    {
        cur=q.front();q.pop();inq[cur]=false;
        for (i=head[cur];i;i=nxt[i])
        {
            y=to[i];
            if (dist[cur]+f[i]>dist[y])
            {
                dist[y]=dist[cur]+f[i];
                if (!inq[y]) inq[y]=true,q.push(y);
            }
        }
    }
}

int main ()
{
    int i;n=getint();
    for (i=1;i<=n;i++) a[i]=getint(),b[i]=getint(),c[i]=getint();
    for (i=1;i<=60000;i++) addedge(i-1,i,0),addedge(i,i-1,-1);
    for (i=1;i<=n;i++) addedge(a[i],b[i]+1,c[i]);
    spfa();
    printf("%d\n",dist[60000]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值