Integer Intervals
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 15199 Accepted: 6429
Description
An integer interval [a,b], a < b, is a set of all consecutive integers beginning with a and ending with b.
Write a program that: finds the minimal number of elements in a set containing at least two different integers from each interval.
Input
The first line of the input contains the number of intervals n, 1 <= n <= 10000. Each of the following n lines contains two integers a, b separated by a single space, 0 <= a < b <= 10000. They are the beginning and the end of an interval.
Output
Output the minimal number of elements in a set containing at least two different integers from each interval.
Sample Input
4
3 6
2 4
0 2
4 7
Sample Output
4
Source
CEOI 1997
题意:
在数轴上,给你一些区间[a,b],让你找出一个点的集合,使得对于每个区间,在区间内的点的数量不少于2个。问集合中最少的点的数目。
这个题和之前做过的一道题很像。
定义f[i]表示从数轴的原点到i这个位置的前一个位置(因为f[b]-f[a-1]>=2,但a可能取到0,所以干脆a、b都+1,即f[b+1]-f[a]>=2)的最小的点的数目。
由于是求最小点数目,所以直接a到b+1连边,建图跑最长路.
但这显然是不对的。题目中还有一些隐藏的图的性质我们没有挖掘到。因为点都是整数,所以数轴上相邻的两个点之间的元素差应该在0和1之间。
即f[i]-f[i-1]>=0&&f[i]-f[i-1]<=1
统一为大于等于,建图跑最长路。
【注意最长路的初始值定义为无穷小。
【够了只有你会犯这种傻逼错误。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int N = 100000 + 10;
const int M = 200000 + 10;
int n,m,mmin=0x73f3f3f;
struct node{
int pre,v,w;
}e[M<<1];
int num=0,head[N];
void addedge(int from,int to,int w){
e[++num].pre=head[from],e[num].v=to;
head[from]=num,e[num].w=w;
}
inline int Max(int a,int b) {return a>b?a:b;}
inline int Min(int a,int b) {return a<b?a:b;}
deque<int> q;
int dis[N];
bool vis[N];
void spfa(){
memset(dis,-0x7,sizeof(dis));
memset(vis,0,sizeof(vis));
q.push_back(mmin);dis[mmin]=0;
while(!q.empty()){
int u=q.front();q.pop_front();
vis[u]=false;
for(int i=head[u];i;i=e[i].pre){
int v=e[i].v;
if(dis[v]<dis[u]+e[i].w){
dis[v]=dis[u]+e[i].w;
if(!vis[v]){
if(!q.empty()&&dis[v]>dis[q.front()]) q.push_front(v);
else q.push_back(v);
vis[v]=true;
}
}
}
}
}
int main(){
m=read();n=0;
for(int i=1;i<=m;++i){
int u=read(),v=read();
n=Max(n,v+1);mmin=Min(u,mmin);
addedge(u,v+1,2);
}
for(int i=mmin;i<n;++i){
addedge(i,i+1,0);
addedge(i+1,i,-1);
}
spfa();
printf("%d\n",dis[n]);
return 0;
}