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个区间,要求你找出M个数,这M个数满足在每个区间都至少有两个不同的数。
思路:设dis[i]表示[0,i-1]这个区间有dis[i]个数满足要求,则给定一个区间[a,b],就有dis[b+1]-dis[a]>=2(b+1是因为b也算在区间内)将其转换为dis[a]-dis[b+1]<=-2,这是第一个式子。接着在区间[i,i+1]中满足dis[i+1]-dis[i]>=0转换为dis[i]-dis[i+1]<=0;还有dis[i+1]-dis[i]<=1,有了三个不等式约束就可以建图了。以maxx(最右边界+1)为源点,进行spfa,最后答案为dis[maxx]-dis[minn]。
AC代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <math.h>
#include <stack>
#include <queue>
#include <vector>
#include <map>
typedef long long ll;
const int maxn=10010;
const int inf=0x3f3f3f3f;
using namespace std;
struct node
{
int v;
int w;
int next;
} edge[maxn<<2];
int head[maxn],dis[maxn];
bool vis[maxn];
int cnt,n;
void add(int u,int v,int w)
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void spfa(int u)
{
dis[u]=0;
vis[u]=true;
queue<int>q;
q.push(u);
while(!q.empty())
{
int x=q.front();
q.pop();
vis[x]=false;
for(int i=head[x]; i!=-1; i=edge[i].next)
{
int v=edge[i].v;
int w=edge[i].w;
if(dis[v]>dis[x]+w)
{
dis[v]=dis[x]+w;
if(!vis[v])
{
vis[v]=true;
q.push(v);
}
}
}
}
}
void init()
{
cnt=0;
memset(head,-1,sizeof(head));
memset(vis,false,sizeof(vis));
memset(dis,inf,sizeof(dis));
}
int main()
{
scanf("%d",&n);
init();
int minn=inf;
int maxx=-inf;
int a,b;
for(int i=0; i<n; i++)
{
scanf("%d%d",&a,&b);
minn=min(minn,a);
maxx=max(maxx,b+1);
add(b+1,a,-2);
}
for(int i=0; i<maxx; i++)
{
add(i+1,i,0);
add(i,i+1,1);
}
spfa(maxx);
printf("%d\n",dis[maxx]-dis[minn]);
return 0;
}