POJ1201 Intervals
http://acm.sdut.edu.cn:8080/vjudge/contest/view.action?cid=267#problem/A
A - Intervals
Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64uDescription
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.
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
还是那句话差分约束的难点就在找条件!
设dis[i+1]表示有不超过i的Z集合里面的数的个数,可以列出不等式dis[b+1]-dis[a]>=ci
另有隐含条件 si[i+1]-s[i]>=0 si[i]-s[i+1]>=-1 利用spfa求出最长路
题意是说给出一些闭区间,这些区间上整点可以选择放一个元素或者不放,但是每个区间都有一个下限,就是说你在这个区间里面的元素个数不能低于这个下限值。
最后要求出最少需要几个元素才能满足每个区间的要求。
建图(参见这里)之后可以转化成最长路问题。
另:差分约束中dist[ ]的初始化很有意思,比如你初始化的是 0 ,那么按照最长路更新dist[ ]数组,最后得到的就是大于 0 的最小值;如果按照最短路更新dist[ ]的话,最后结果是小于 0 的最大值。 ——LC
还有,针对这种差分约束问题建图转化成为最短路问题的处理,很多 blog 的建图都是为了队列入队操作时方便,加入了一个虚点,这个虚点和图中每一个点都连一条权值为 0 的边,开始寻找最长路时,首先把这个虚点入队。其实我们可以省略这个点,这样的话,我们需要手动把图中每个点入队,同时把他们的dist[ ]值更新成 0 ,听着有点麻烦是吧,不过的确是个省时间的办法,至于优化效果怎么样,就不好说了。 ——LC
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <queue> #define N 1000001 using namespace std; int head[50005],v[50005],dis[50005]; struct node { int x,y,z; int next; }q1[200010]; int tt,min1,max1; void add(int xx,int yy,int zz) { q1[tt].x=xx; q1[tt].y=yy; q1[tt].z=zz; q1[tt].next=head[xx]; head[xx]=tt++; } void spfa() { queue<int>q; for(int i=min1;i<=max1;i++) { v[i]=0; dis[i]=-N; } q.push(min1); v[min1]=1; dis[min1]=0; while(!q.empty()) { int ff=q.front(); q.pop(); v[ff]=0; for(int i=head[ff];i!=-1;i=q1[i].next) { int vvv=q1[i].y; if(dis[vvv]<dis[ff]+q1[i].z) { dis[vvv]=dis[ff]+q1[i].z; if(!v[vvv]) { v[vvv]=1; q.push(vvv); } } } } printf("%d\n",dis[max1]); return ; } int main() { int n,xx,yy,zz; while(scanf("%d",&n)!=EOF) { tt=0; max1=-1; min1=N; memset(head,-1,sizeof(head)); while(n--) { scanf("%d%d%d",&xx,&yy,&zz); add(xx,yy+1,zz); if(yy+1>max1) max1=yy+1; if(xx<min1) min1=xx; } for(int i=min1;i<max1;i++) { add(i+1,i,-1); add(i,i+1,0); } spfa(); } return 0; }