Problem Description
You are given n closed, integer intervals [ai, bi] and n integers c1, …, cn.
Write a program that:
1、reads the number of intervals, their endpoints and integers c1, …, cn from the standard input,
2、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,
3、 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
思路
显然有不等式Bi-A(i-1)>=Ci (A,B是两个端点),又因为如果从0点到x点有y个那么从0点到x+1点可能有y个也可能有y+1个,即相邻的两点之间可能增加一个也可能没有增加又得出两个不等式:Ai-A(i-1)>=0,Ai-A(i-1)<=1;得到三个约束条件:Bi-A(i-1)>=Ci ,Ai-A(i-1)>=0 ,A(i-1)-Ai>=-1; 依据b-a>=c建立一条从a到b的有向边,权值为c。
这样就有了要满足dis[v]>=dis[u]+w的不等式类似求最短路的spfa中dis[v]>dis[u]+w的松弛,因此起点到终点最小的序列长度就是求得起点的单源最短路中到终点的距离。
a,b,从0开始a-1会出现负数所以a++;b++;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int N=50000+5;
const int INF=0x7fffffff;
struct node
{
int to,next,w;
}edge[N*4];
int mark[N],head[N],tot,src,dis[N],n,minn,maxn;
void add(int u,int v,int w)
{
edge[tot].to=v;
edge[tot].w=w;
edge[tot].next=head[u];
head[u]=tot++;
}
void spfa(int s)
{
for(int i=minn;i<=maxn;i++)
dis[i]=-INF;
memset(mark,0,sizeof(mark));
queue<int>q;
dis[s]=0;
mark[s]=1;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
mark[u]=0;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(dis[v]<dis[u]+edge[i].w)
{
dis[v]=dis[u]+edge[i].w;
if(!mark[v])
{
q.push(v);
mark[v]=1;
}
}
}
}
}
int main()
{
while(scanf("%d",&n)==1)
{
int a,b,c;
memset(head,-1,sizeof(head));
tot=0;
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&a,&b,&c);
a++;b++;
minn=min(minn,a-1);
maxn=max(maxn,b);
add(a-1,b,c);
}
for(int i=minn;i<=maxn;i++)
{
add(i-1,i,0);
add(i,i-1,-1);
}
spfa(minn);
printf("%d\n",dis[maxn]);
}
return 0;
}