Intervals
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 Source |
提示
题意:
给出n(1<=n<=50000)个闭区间,求出最少取几个数才能满足n个闭区间内至少有ci个不同的数在这几个数之中。
思路:
我们设a[0]到a[50000],表示从0到i一共有几个整数,比如a[0]为1个(其中有0),a[5]为6个(其中有0,1,2,3,4,5)。
那么利用它们之间的关系可以有这么几个不等式:
1.a[y]-a[x-1]>=ci.(y>x,表示[x,y]闭区间的个数)
2.a[i]-a[i+1]>=-1.
3.a[i+1]-a[i]>=0.
有了以上式子,把a[]作为点,右边数值当做是边权,直接上spfa就行了。
数据范围比较大,用邻接表吧,队列也尽量用STL。
这题完全是 poj1716的加强版,实际上只需改改数组大小就行了。示例程序
Source Code
Problem: 1201 Code Length: 1243B
Memory: 2908K Time: 282MS
Language: G++ Result: Accepted
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct edge
{
int v,d,next;
}w[150000];
int h[50002],numw;
void insert(int u,int v,int c)
{
w[numw].v=v;
w[numw].d=c;
w[numw].next=h[u];
h[u]=numw;
numw++;
}
int spfa(int n)
{
int d[50002],v[50002],i,pos,pos1;
memset(d,-1,sizeof(d));
memset(v,0,sizeof(v));
queue<int>q;
d[0]=0;
q.push(0);
v[0]=1;
while(q.empty()==0)
{
pos=q.front();
q.pop();
v[pos]=0;
for(i=h[pos];i!=-1;i=w[i].next)
{
pos1=w[i].v;
if(d[pos1]<d[pos]+w[i].d)
{
d[pos1]=d[pos]+w[i].d;
if(v[pos1]==0)
{
q.push(pos1);
v[pos1]=1;
}
}
}
}
return d[n];
}
int main()
{
int i,n,u,v,c,max=0;
numw=0;
memset(h,-1,sizeof(h)); //初始化
scanf("%d",&n);
for(i=1;n>=i;i++)
{
scanf("%d %d %d",&u,&v,&c);
if(v+1>max)
{
max=v+1; //n个闭区间中终点最大记录
}
insert(u,v+1,c);
}
for(i=0;max>i;i++) //注意如何写点与边的连线很关键
{
insert(i,i+1,0);
insert(i+1,i,-1);
}
printf("%d",spfa(max));
return 0;
}