Hdu 1384(差分约束)

时间:2022-04-14 07:54:50

题目链接

Intervals

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2931    Accepted Submission(s): 1067

Problem 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 endpoints 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 <= 50 000) -
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 <= 50
000 and 1 <= ci <= bi - ai + 1.

Process to the end of file.

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
令1..i共选d[i]个数,那么有0 <= d[i + 1] - d[i] <= 1; 
并且对于每个约束a, b, c, 都有 d[b] - d[a - 1] >= c
这样就是一个线性规划问题,可以用最短路求解。
对于求最大值,就将不等式转化为求最短路中的三角不等式,即:d[u] + w >= d[v], 然后求最短路即可。
对于求最小值,就将不等式转化为求最长路中的三角不等式,即:d[u] + w <= d[v], 然后求最长路即可。
当然求最小值时,也可以按求最大值的方法加边,只不过这时候加的边都是反向边,从终点到起点跑最短路,然后结果取反就可以了。
Accepted Code:
 /*************************************************************************
> File Name: 1384.cpp
> Author: Stomach_ache
> Mail: sudaweitong@gmail.com
> Created Time: 2014年08月26日 星期二 08时59分19秒
> Propose:
************************************************************************/
#include <queue>
#include <cmath>
#include <string>
#include <cstdio>
#include <vector>
#include <fstream>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
/*Let's fight!!!*/ const int INF = 0x3f3f3f3f;
const int MAX_N = ;
typedef pair<int, int> pii;
vector<pii> G[MAX_N];
int n, d[MAX_N];
bool inq[MAX_N]; void AddEdge(int u, int v, int w) {
G[u].push_back(pii(v, w));
} void spfa(int s) {
queue<int> Q;
memset(d, 0x3f, sizeof(d));
memset(inq, false, sizeof(inq));
d[s] = ;
inq[s] = true;
Q.push(s);
while (!Q.empty()) {
int u = Q.front(); Q.pop(); inq[u] = false;
for (int i = ; i < G[u].size(); i++) {
int v = G[u][i].first, w = G[u][i].second;
if (d[u] + w < d[v]) {
d[v] = d[u] + w;
if (!inq[v]) Q.push(v), inq[v] = true;
}
}
}
} int main(void) {
while (~scanf("%d", &n)) {
for (int i = ; i <= ; i++) G[i].clear();
int s = INF, t = -;
for (int i = ; i < n; i++) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
b++;
s = min(s, a); t = max(t, b);
AddEdge(b, a, -c);
}
for (int i = s; i < t; i++) AddEdge(i, i + , ), AddEdge(i + , i, ); spfa(t); printf("%d\n", -d[s]);
} return ;
}