POJ1201 Intervals差分约束系统(最短路)

时间:2021-08-21 04:57:11

Description

You are given n closed, integer intervals [ai, bi] and n integers c1, ..., cn. 
Write a program that: 
reads the number of intervals, their end points and integers c1, ..., cn from the standard input, 
computes the minimal size of a set Z of integers which has at least ci common elements with interval [ai, bi], for each i=1,2,...,n, 
writes the answer to the standard output. 

Input

The first line of the input contains an integer n (1 <= n <= 50000) -- the number of intervals. The following n lines describe the intervals. The (i+1)-th line of the input contains three integers ai, bi and ci separated by single spaces and such that 0 <= ai <= bi <= 50000 and 1 <= ci <= bi - ai+1.

Output

The output contains exactly one integer equal to the minimal size of set Z sharing at least ci elements with interval [ai, bi], for each i=1,2,...,n.

Sample Input

5
3 7 3
8 10 3
6 8 1
1 3 1
10 11 1

Sample Output

6

Source

题意是给你n个闭区间,形如[ai,bi],在这n个区间的每一个整点位置放东西,每个区间至少要放ci个,求总的最少要放的个数
了解过查分约束系统之后,比较容易知道是差分系统的最小差问题,那么就是找全形如 y-x>=k的不等式,然后再求一个最长路
关键是建图问题:p[i]表示1~i放的东西个数,那么对于每一个区间,就要满足p[bi] - p[ai-1]>=ci,即拉一条(ai-1)->bi的有向边
但是有一个隐藏的约束条件,由于是整点放,那么p[x] - p[x-1] <= 1 && p[x] - p[x-1] >= 0  即p[x-1]-p[x]>=-1 && p[x]-p[x-1]>=0
另外,由于区间可以从0开始,那么把所有的区间整体右移2个位置,就是从1开始的了
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 5e4 + ;
struct Edge {
int v, cost;
Edge() {}
Edge(int v, int cost) : v(v), cost(cost) {}
};
vector<Edge> E[N];
void add(int u, int v, int w) {
E[u].push_back(Edge(v, w));
}
bool vis[N];
int d[N];
void SPFA(int st, int n) {
memset(vis, false, sizeof vis);
for(int i = ; i <= n; ++i) d[i] = -INF;
d[st] = ;
vis[st] = true;
queue<int> que;
while(!que.empty()) que.pop();
que.push(st);
while(!que.empty()) {
int u = que.front();
que.pop();
vis[u] = false;
int sx = E[u].size();
for(int i = ; i < sx; ++i) {
int v = E[u][i].v;
int w = E[u][i].cost;
if(d[v] < d[u] + w) {
d[v] = d[u] + w;
if(!vis[v]) {
vis[v] = true;
que.push(v);
}
}
}
}
}
int main() {
int n;
while(~scanf("%d", &n)) {
int a, b, c, m = , st = INF;
for(int i = ; i < n; ++i) {
scanf("%d%d%d", &a, &b, &c);
a+=; b+=;
add(a - , b, c);
m = max(m, b);
st = min(st, a - );
}
for(int i = ; i <= m; ++i) {
add(i, i - , -);
add(i - , i, );
}
SPFA(st, m);
printf("%d\n", d[m]);
}
return ;
}