Integer Intervals
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 13676 Accepted: 5827
传送门
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
/*
差分约束.
维护三个不等式.
先找出上下界x,y.
那么答案贡献必定在 [x,y]里.
dis[i]表示1到i的贡献.
*/
#include<iostream>
#include<cstdio>
#define MAXN 20001
using namespace std;
int dis[MAXN],n,m,x=0x7777ffff,y;
bool flag;
struct data
{
int l;
int r;
}
s[MAXN];
int main()
{
int x1,y1;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d %d",&x1,&y1);
s[i].l=x1;
s[i].r=y1+1;
x=min(s[i].l,x);
y=max(s[i].r,y);
}
while(!flag)
{
flag=true;
for(int i=1;i<=n;i++)
if(dis[s[i].l]>dis[s[i].r]-2)
dis[s[i].l]=dis[s[i].r]-2,flag=false;
for(int i=x;i<y;i++)
if(dis[i+1]>dis[i]+1)
dis[i+1]=dis[i]+1,flag=false;
for(int i=x;i<y;i++)
if(dis[i]>dis[i+1])
dis[i]=dis[i+1],flag=false;
}
printf("%d",dis[y]-dis[x]);
return 0;
}
/*
spfa松弛.
这题是poj 1201的弱化版.
http://blog.csdn.net/sinat_34550050/article/details/54906031
*/
#include<cstring>
#include<cstdio>
#include<queue>
#define MAXN 50001
using namespace std;
struct data{int v,next,x;}e[MAXN*3];
int n,m,head[MAXN],dis[MAXN],cut,maxv,maxn,minn=1e6;
bool b[MAXN];
void add(int u,int v,int x)
{
e[++cut].v=v;
e[cut].x=x;
e[cut].next=head[u];
head[u]=cut;
}
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-48,ch=getchar();
return x*f;
}
void spfa()
{
memset(dis,-127/3,sizeof dis);
queue<int>q;q.push(minn);dis[minn]=0;
while(!q.empty())
{
int u=q.front();q.pop();b[u]=false;
for(int i=head[u];i;i=e[i].next)
{
int v=e[i].v;
if(dis[v]<dis[u]+e[i].x)
{
dis[v]=dis[u]+e[i].x;
if(!b[v]) b[v]=true,q.push(v);
}
}
}
return ;
}
int main()
{
int x,y,z;
m=read();
for(int i=1;i<=m;i++)
{
x=read(),y=read();y++;
add(x,y,2);
minn=min(minn,x),maxn=max(maxn,y);
}
for(int i=minn;i<=maxn;i++) add(i,i+1,0),add(i+1,i,-1);
spfa();
printf("%d",dis[maxn]);
return 0;
}