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
题意:有n个如下形式的条件:ai bi ci,表示在区间[ai, bi]内至少要选择ci个整数点.问你满足n个条件的情况下,最少需要选多少个点?
思路:这道题的话,题目说[ai, bi]区间内和点集Z至少有ci个共同元素,那也就是说如果我用Si表示区间[0,i]区间内至少有多少个元素的话,那么Sbi - Sai >= ci,这样我们就构造出来了一系列边,权值为ci,但是这远远不够,因为有很多点依然没有相连接起来(也就是从起点可能根本就还没有到终点的路线),此时,我们再看看Si的定义,也不难写出0<=Si - Si-1<=1的限制条件,虽然看上去是没有什么意义的条件,但是如果你也把它构造出一系列的边的话,这样从起点到终点的最短路也就顺理成章的出现了。
我们把限制条件写成不等式的形式:
Sbi - Sai >= ci
Si - Si-1 >= 0
Si-1 - Si >= -1
然后就可以做出这道题了。
AC代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <math.h>
#include <stack>
#include <queue>
#include <vector>
#include <map>
typedef long long ll;
const int maxn=50010;
const int inf=0x3f3f3f3f;
using namespace std;
struct node
{
int v;
int w;
int next;
} edge[maxn<<2];
int head[maxn],dis[maxn];
bool vis[maxn];
int cnt,n;
void add(int u,int v,int w)
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void spfa(int u)
{
vis[u]=true;
dis[u]=0;
queue<int>q;
q.push(u);
while(!q.empty())
{
int x=q.front();
q.pop();
vis[x]=false;
for(int i=head[x]; i!=-1; i=edge[i].next)
{
int v=edge[i].v;
int w=edge[i].w;
if(dis[v]<dis[x]+w)
{
dis[v]=dis[x]+w;
if(!vis[v])
{
vis[v]=true;
q.push(v);
}
}
}
}
}
void init()
{
cnt=0;
memset(head,-1,sizeof(head));
memset(vis,false,sizeof(vis));
memset(dis,-inf,sizeof(dis));
}
int main()
{
scanf("%d",&n);
init();
int a,b,c;
int state=inf,endd=-inf;
for(int i=1; i<=n; i++)
{
scanf("%d%d%d",&a,&b,&c);
add(a-1,b,c);
state=min(state,a-1);
endd=max(endd,b);
}
for(int i=state; i<=endd; i++)
{
add(i-1,i,0);
add(i,i-1,-1);
}
spfa(state);
printf("%d\n",dis[endd]);
return 0;
}