(模板题)poj 1716 Integer Intervals(差分约束系统)

Integer Intervals
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 14114 Accepted: 5988

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

提示

题意:

给出n(1<=n<=10000)个闭区间,求出最少取几个数才能满足n个闭区间内至少有两个不同的数在这几个数之中。

思路:

一道经典的差分约束系统题,我们设a[0]到a[10000],表示从0到i一共有几个整数,比如a[0]为1个(其中有0),a[5]为6个(其中有0,1,2,3,4,5)。

那么利用它们之间的关系可以有这么几个不等式:

1.a[y]-a[x-1]>=2.(y>x,表示[x,y]闭区间的个数)

2.a[i]-a[i+1]>=-1.

3.a[i+1]-a[i]>=0.

有了以上式子,把a[]作为点,右边数值当做是边权,直接上spfa就行了。

数据范围比较大,用邻接表吧,队列也尽量用STL。

注意:

1. 如果不等式是x-y<=k的形式,然后建立一条从x到y的k边,变得时候注意x-y<k => x-y<=k-1,求出最短路径即可。

    如果不等式是x-y>=k的形式,然后建立一条从x到y的k边,求出最长路径即可。

2.如果权值为正,用dij,spfa,bellman都可以,如果为负不能用dij,并且需要判断是否有负环,有的话就不存在。

示例程序

Source Code

Problem: 1716		Code Length: 1234B
Memory: 940K		Time: 94MS
Language: G++		Result: Accepted
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct edge
{
    int v,d,next;
}w[30000];
int h[10002],numw;
void insert(int u,int v,int c)
{
    w[numw].v=v;
    w[numw].d=c;
    w[numw].next=h[u];
    h[u]=numw;
    numw++;
}
int spfa(int n)
{
    int d[10002],v[10002],i,pos,pos1;
    memset(d,-1,sizeof(d));
    memset(v,0,sizeof(v));
    queue<int>q;
    d[0]=0;
    q.push(0);
    v[0]=1;
    while(q.empty()==0)
    {
        pos=q.front();
        q.pop();
        v[pos]=0;
        for(i=h[pos];i!=-1;i=w[i].next)
        {
            pos1=w[i].v;
            if(d[pos1]<d[pos]+w[i].d)
            {
                d[pos1]=d[pos]+w[i].d;
                if(v[pos1]==0)
                {
                    q.push(pos1);
                    v[pos1]=1;
                }
            }
        }
    }
    return d[n];
}
int main()
{
    int i,n,u,v,max=0;
    numw=0;
    memset(h,-1,sizeof(h));			//初始化
    scanf("%d",&n);
    for(i=1;n>=i;i++)
    {
        scanf("%d %d",&u,&v);
        if(v+1>max)
        {
            max=v+1;					//n个闭区间中终点最大记录
        }
        insert(u,v+1,2);
    }
    for(i=0;max>i;i++)					//注意如何写点与边的连线很关键
    {
        insert(i,i+1,0);
        insert(i+1,i,-1);
    }
    printf("%d",spfa(max));
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值