URAL 1203

题目大意:给出N个区间:[li,ri](i=1,2,3,...,N),求互不相交的最大区间的数目。

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

数据规模:1<=N<=100000,1<=li<ri<=30000。

理论基础:无。

题目分析:用dp[i]表示区间[1,i]中互不相交的最大区间的数目。

首先:预处理。首先对每个区间按照词典序排序(右端点在前比较,相等时比较左端点。这样,后面可以进行优化,去除覆盖别的区间的大区间,可以证明,去掉这些区间后的最优解是不会变劣的),然后记录每个区间右端点为i时的左端点为last[i](按排序后的数据操作,最后得到的last[i]一定是最大的,因为是左端点,所以得到的区间是最小的,达到优化目的),排序后的最后一个区间的右端点值即为dp[]的边界值bor,即答案为dp[bor]。

然后,我们可以推出状态转移方程dp[i]=max(dp[i-1],dp[last[i]-1]+1)。即此区间加与不加之间进行比较,取最大值。因为是互不相交,而且每个区间的跨度大于1,所以只需要比较dp[i-1]与dp[last[i]-1]+1即可。

最后我们就可以得出答案了,注意dp数组初始值为0。

代码如下:

#include<iostream>
#include<cstring>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<ctime>
#include<vector>
#include<map>
using namespace std;
typedef double db;
#define DBG 0
#define maa (1<<31)
#define mii ((1<<31)-1)
#define ast(b) if(DBG && !(b)) { printf("%d!!|\n", __LINE__); while(1) getchar(); }  //调试
#define dout DBG && cout << __LINE__ << ">>| "
#define pr(x) #x"=" << (x) << " | "
#define mk(x) DBG && cout << __LINE__ << "**| "#x << endl
#define pra(arr, a, b)  if(DBG) {\
    dout<<#arr"[] |" <<endl; \
    for(int i=a,i_b=b;i<=i_b;i++) cout<<"["<<i<<"]="<<arr[i]<<" |"<<((i-(a)+1)%8?" ":"\n"); \
    if((b-a+1)%8) puts("");\
}
template<class T> inline bool updateMin(T& a, T b) { return a>b? a=b, true: false; }
template<class T> inline bool updateMax(T& a, T b) { return a<b? a=b, true: false; }
typedef long long LL;
typedef long unsigned int LU;
typedef long long unsigned int LLU;
typedef pair<int,int> PT;
#define N 100000
#define M 30000
istream& operator >>(istream &in,PT &x)
{
    int a,b;
    in>>a>>b;
    x.first=a;
    x.second=b;
    return in;
}
ostream& operator <<(ostream &out,const PT &x)
{
    printf("(%d,%d)",x.first,x.second);
    return out;
}
bool cmp(PT a,PT b)
{
    if(a.second!=b.second)return a.second<b.second;
    else return a.first<b.first;
}
PT pt[N+1];
int dp[M+1],last[M+1],n;
int main()
{
    while(~scanf("%d",&n))
    {
        memset(dp,0,sizeof dp);
        memset(last,-1,sizeof last);
        for(int i=1;i<=n;i++)cin>>pt[i];
        sort(pt+1,pt+n+1,cmp);
        pra(pt,1,n)
        int bor=pt[n].second;
        for(int i=1;i<=n;i++)last[pt[i].second]=pt[i].first;
        pra(last,1,bor)
        for(int i=1;i<=bor;i++)
        {
            if(last[i]==-1)
            dp[i]=dp[i-1];
            else dp[i]=max(dp[i-1],dp[last[i]-1]+1);
        }
        printf("%d\n",dp[bor]);
    }
	return 0;
}

其中,pair<int,int>即为一个容器,用来表示区间。

by:Jsun_moon http://blog.csdn.net/jsun_moon

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值