Intervals
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 |
题目大意是:告诉你一个数列B在另一个数列A中每一个闭区间[a,b]中至少包含c个数,求B数列的最小长度。
模型转换一下,使用二进制0、1表示当前数取还是不取,此问题即成为典型的查分约束系统。
令S[i]表示0..i中1的个数,第i位状态即 S[i]-S[i-1] ,满足 0 ≤ S[i]-S[i-1] ≤ 1.
对于每一个条件(a,b,c),满足 c ≤ S[b]-S[a-1] ≤ b-a+1.
即可得到 S[i]-S[i-1]≤1
S[i-1]-S[i]≤0
S[b]-S[a-1]≤b-a+1
S[a-1]-S[b]≤ -c (注意移项之后是 -c )
建图之后SPFA即可,答案为 S[区间下届]-S[区间上届-1],区间的上下界在读入中维护即可。
代码:
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#define mn 50003
#define mm 500000
#define inf ~0u >> 1
using namespace std;
template <class T> inline void gmax(T &a, T b){if (a < b) a = b;}
template <class T> inline void gmin(T &a, T b){if (a > b) a = b;}
queue <int> q;
int dist[mn], n, a, b, c, s, minn, maxn;
bool vis[mn];
struct EDGE
{
int pnt, dist;
EDGE *pre;
EDGE(){}
EDGE(int _pnt, int _dist, EDGE *_pre)
{
pnt = _pnt;
dist = _dist;
pre = _pre;
}
} Edge[mm * 2], *SP = Edge, *edge[mm];
inline void addedge(int a, int b, int c)
{
edge[a] = new(++SP)EDGE(b, c, edge[a]);
}
void SPFA()
{
memset(dist, 0x7f, sizeof(dist));
memset(vis, false, sizeof(vis));
dist[s] = 0, vis[s] = true;
q.push(s);
while (!q.empty())
{
int i = q.front();
q.pop();
vis[i] = false;
for (EDGE *j = edge[i]; j; j = j -> pre)
{
if (dist[j -> pnt] > dist[i] + j -> dist)
{
dist[j -> pnt] = dist[i] + j -> dist;
if (!vis[j -> pnt])
{
vis[j -> pnt] = true;
q.push(j -> pnt);
}
}
}
}
}
int main()
{
scanf("%d", &n);
maxn =0, minn = inf;
for (int i = 1; i <= n; ++i)
{
scanf("%d%d%d", &a, &b, &c);
gmin(minn, a);
gmax(maxn, b);
addedge(a - 1, b, b - a + 1);
addedge(b, a - 1, -c);
}
s = maxn + 1;
for (int i = 0; i <= maxn; ++i) addedge(s, i, 0);
for (int i = 1; i <= maxn; ++i)
{
addedge(i - 1, i, 1);
addedge(i, i - 1, 0);
}
SPFA();
printf("%d\n", dist[maxn] - dist[minn - 1]);
return 0;
}