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.
Analysis
最近自己搞一搞差分约束系统
给出一些形如 x−y≤b 不等式的约束,问你是否满足有解的问题
神奇的是这类问题竟然可以转换成图论里的最短路径问题
用
totx
表示
1..x
间元素的个数
这里根据题意不难得出
totb−tota≤c
,因此连边
a−>b
边权为
c
然而这是不足以让整个图联通的,所以我们还需要一些不等式
根据
跑一遍spfa找最长路
Code
#include <stdio.h>
#include <string.h>
#include <queue>
#define inf 0x7fffffff
using namespace std;
struct edge{int y,w,next;}e[250001];
int dis[50001],ls[250001],maxE=0;
bool vis[50001];
queue<int>q;
void add(int x,int y,int w)
{
e[++maxE]=(edge){y,w,ls[x]};
ls[x]=maxE;
}
int spfa(int st,int ed)
{
memset(dis,-63,sizeof(dis));
q.push(st);
dis[st]=0;
vis[st]=true;
while (!q.empty())
{
int now=q.front();q.pop();
for (int i=ls[now];i;i=e[i].next)
if (e[i].w+dis[now]>dis[e[i].y])
{
dis[e[i].y]=e[i].w+dis[now];
if (!vis[e[i].y])
{
vis[e[i].y]=true;
q.push(e[i].y);
}
}
vis[now]=false;
}
return dis[ed];
}
int main()
{
int n,mn=inf,mx=0;
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
y++;
add(x,y,w);
if (mx<y)
mx=y;
if (mn>x)
mn=x;
}
for (int i=mn;i<mx;i++)
{
add(i,i+1,0);
add(i+1,i,-1);
}
printf("%d\n",spfa(mn,mx));
return 0;
}