1716 Integer Intervals

Integer Intervals
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 7404 Accepted: 2991

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

 

 

贪心能过,不过我还是用了差分约束系统,也就是SPFA

1201的简化版

 

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int E=10005;
const int V=10005;
const int INF=1<<25-1;
struct EDGE
{
    int link,val,next;
}edge[E*3];
int head[V],dist[V],e,rmin,rmax;
bool vis[V];
void addedge(int a,int b,int c)
{
    edge[e].link=b;
    edge[e].val=c;
    edge[e].next=head[a];
    head[a]=e++;
}
int relax(int u,int v,int c)
{
    if(dist[v]<dist[u]+c)//不能是<=,会死循环
    {
        dist[v]=dist[u]+c;
        return 1;
    }
    return 0;
}
void SPFA(int src)
{
    memset(vis,false,sizeof(vis));
    for(int i=rmin;i<=rmax;i++) dist[i]=-INF;
    int top=1;
    dist[src]=0;
    vis[src]=true;
    queue<int> q;
    q.push(src);
    while(!q.empty())
    {
        int u,v;
        u=q.front();
        q.pop();
        vis[u]=false;
        for(int i=head[u];i!=-1;i=edge[i].next)
        {
            v=edge[i].link;
            if(relax(u,v,edge[i].val)==1&&!vis[v])
            {
                 q.push(v);
                 vis[v]=true;
            }
        }
    }
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        e=0;
        memset(head,-1,sizeof(head));
        rmin=1<<25-1; rmax=-1;
        for(int i=1;i<=n;i++)
        {
            int a,b,c;
            scanf("%d%d",&a,&b);
            if(a<rmin)  rmin=a;
            if(b+1>rmax)  rmax=b+1;
            addedge(a,b+1,2);
        }
        for(int i=rmin;i<rmax;i++) addedge(i,i+1,0);
        for(int i=rmin;i<rmax;i++) addedge(i+1,i,-1);
        SPFA(rmin);
        printf("%d/n",dist[rmax]-dist[rmin]);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值