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
题意:给定n个区间,[ai,bi]这个区间至少选选出ci个整数,求一个集合z,满足每个区间的要求,输出集合z的大小。
分析:令d[i]表示0到i这个区间内至少要选出d[i]个数,那么对于每个[ai,bi],有d[b] - d[ai-1] >= ci,同时隐含的一个条件是0 <= d[i] - d[i-1] <= 1,但是因此d[-1]不能表示,令d[i+1]示0到i这个区间内至少要选出d[i+1]个数,然后d[0] = 0,直接求取最长路就行了。边的存储使用链式向前星,这样效率最高。
求满足的不等式包括s[b[i]]−s[a[i]−1]≥c[i] ,0≤s[i]−s[i−1]≤1,其中s[i]s[i]表示到第ii个位置为止选择的点的个数,转换一下,就可以得到:
s[b[i]]≥s[a[i]−1]+c[i],
s[i]≥s[i−1]+0,
s[i−1]≥s[i]+(−1),
这就得到了三种边权的边,就可以建图了。
#include <cstdio>
#include <cstring>
#include <queue>
#include <cctype>
#include <algorithm>
#include<iostream>
using namespace std;
const int N=5e4+10;
const int inf=0x3f3f3f3f;
struct node
{
int to,dis,next;
}edge[N<<2];
int cnt,head[N];
void addedge(int from,int to,int dis)
{
edge[cnt].to=to;
edge[cnt].dis=dis;
edge[cnt].next=head[from];
head[from]=cnt++;
}
int dis[N];
bool vis[N];
void spfa(int t)
{
memset(vis,false,sizeof(vis));
memset(dis,-inf,sizeof(dis));
vis[t]=true;
dis[t]=0;
queue<int>Q;
Q.push(t);
while(!Q.empty()){
int u=Q.front();
Q.pop();
vis[u]=false;
for(int i=head[u];i!=-1;i=edge[i].next){
int to=edge[i].to;
if(dis[to]<dis[u]+edge[i].dis){
dis[to]=dis[u]+edge[i].dis;
if(!vis[to]){
vis[to]=true;
Q.push(to);
}
}
}
}
}
int main()
{
memset(head,-1,sizeof(head));
int n;
scanf("%d",&n);
int minn=inf,maxn=-1;
for(int i=0;i<n;i++){
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
addedge(a,b+1,c);
minn=min(a,minn);
maxn=max(b,maxn);
}
//这里相当于真个区间向后移动一位
maxn++;
for(int i=minn;i<=maxn;i++){
addedge(i,i+1,0);
addedge(i+1,i,-1);
}
spfa(minn);
printf("%d\n",dis[maxn]);
return 0;
}