Intervals
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
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
题意:给n个[st,en]区间,每个区间取出val个数,问至少能取出多少数。
差分约束,设total[i]为区间[0,i]最多要取多少数。所以根据区间可以写出
total[en]-total[st-1] >= val,题中包含一个隐含的不等式:
0<=total[i]-total[i-1]<=1。根据这三个不等式就可以建图并切跑最长路并输出dis[minen];
跑最长路的原因是:
①:对于差分不等式,a - b <= c ,建一条 b 到 a 的权值为 c 的边,求的是最短路,得到的是最大值
②:对于不等式 a - b >= c ,建一条 b 到 a 的权值为 c 的边,求的是最长路,得到的是最小值。
这里找的是最小值,所以跑最长路。
CODE
#include"stdio.h"
#include"iostream"
#include"algorithm"
#include"string.h"
#include"math.h"
#include"stdlib.h"
#include"queue"
#define maxn 200010
#define inf 0x7fffffff
using namespace std;
struct node
{
int en;
int val;
int next;
}edge[maxn]; ///边
int n,len,minst,minen; ///len 边的数量,minst 起点,minen 终点
int dis[maxn]; ///spfa用
int head[maxn]; ///头结点
int vis[maxn]; ///spfa用
void init() ///初始化
{
minst = inf;
minen = -1;
len = 0;
for(int i = 0;i < maxn;i++)
{
dis[i] = -inf;
head[i] = -1;
vis[i] = false;
}
}
void add(int st,int en,int val) ///邻接表加边
{
edge[len].en = en;
edge[len].val = val;
edge[len].next = head[st];
head[st] = len++;
}
void spfa() ///spfa模版
{
dis[minst] = 0;
queue<int>q;
q.push(minst); ///起点进队
vis[minst] = true;
while(!q.empty())
{
int t = q.front();
q.pop();
vis[t] = false;
///printf("a");
for(int i = head[t];i != -1;i = edge[i].next)
{
node e = edge[i];
if(dis[e.en] < dis[t]+e.val)
{
dis[e.en] = dis[t]+e.val;
if(!vis[e.en])
{
vis[e.en] = true;
q.push(e.en);
}
}
}
}
}
int main(void)
{
while(scanf("%d",&n) !=EOF)
{
init();
for(int i = 1;i <= n;i++) ///total[en]-total[st-1] >= val
{
int st,en,val;
scanf("%d%d%d",&st,&en,&val);
add(st-1,en,val);
if(minst > st-1) minst = st-1;
if(minen < en) minen = en;
}
for(int i = minst;i <= minen;i++)
{
add(i-1,i,0); ///total[i]-total[i-1] >= 0
add(i,i-1,-1); ///total[i-1]-total[i] >= -1
}
spfa();
/*for(int i = minst;i <= minen;i++)
printf("%d ",dis[i]);*/
printf("%d\n",dis[minen]);
}
return 0;
}