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
大意:有n个区间,这n个区间会给出,然后还有一个集合V,这个集合V是包含了这n个区间至少两个不一样的元素,问这个集合v最少有多少个元素在里面,就是说题目要求找出一个最小集合S,满足对于n个范围[ai,bi],S中存在两个及两个以上不同的点在范围内;
这里需要是一个数组dis[i]表示从当前给的区间中最小值,也就是左边界到i中至少被包含在V集合中的元素个数,因此可以到做到
dis[y+1]-dis[x]>=2这一个很好得出,但是还有一个隐含的关系式,那就是 0<=dis[i+1]-dis[i]<=1,这是比较难得出的一个约束关系,那剩下的就是将所有的这些点全部加入到边中,然后跑一下最短路就行
#include<iostream>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=10009;
const int INF=0x3f3f3f3f;
typedef long long ll;
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define ms(a,b) memset(a,b,sizeof a)
struct node
{
int next,to,val;
}num[N<<4];
int head[N];
int dis[N];
int cot[N];
bool vis[N];
int n;
int tot;
void add(int u,int v,int w)
{
num[tot].to=v;
num[tot].val=w;
num[tot].next=head[u];
head[u]=tot++;
}
int minn,maxx;
void spfa(int s)
{
ms(dis,-INF);
ms(vis,0);
//ms(cot,0);
vis[s]=1;
dis[s]=0;
queue<int> q;
q.push(s);
while(q.size())
{
int now=q.front();
q.pop();vis[now]=0;
// if(cot[now]>=n)
// {
// cout<<-1<<endl;return;
// }
for(int i=head[now];i!=-1;i=num[i].next)
{
int v=num[i].to;
int w=num[i].val;
if(dis[v]<dis[now]+w)
{
dis[v]=dis[now]+w;
if(!vis[v])
{
vis[v]=1;q.push(v);
}
}
}
}
cout<<dis[maxx]<<endl;
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);
int ml,md;
tot=1;
minn=INF;maxx=-INF;
ms(head,-1);
cin>>n;
int x,y,z;
rep(i,1,n)//先由题目可知,先设dis[i]表示区间长度从0到i所含有在V集合中的元素个数,那么dis[y+1]-dis[x]>=2才能满足题意
{
cin>>x>>y;
minn=min(minn,x);
maxx=max(maxx,y+1);
add(x,y+1,2);
}
rep(i,minn,maxx-1)//只有上面那一个约束条件还是不够的,还有一个隐含的必要条件是0<=dis[i+1]-dis[i]<=1;
add(i,i+1,0),add(i+1,i,-1);
spfa(minn);
}