HDU 1025 Constructing Roads In JGShining's Kingdom LIS -

本文提供了一种解决HDU 1025问题的有效算法,通过最长递增子序列(LIS)的方法实现了nlogn的时间复杂度。文中详细介绍了使用二分查找优化LIS算法的具体实现过程,并附上了完整的C++代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1025

要用nlogn的算法,不然会超时

参见博客讲解:http://blog.youkuaiyun.com/kaitangshouljz/article/details/41074187?locationNum=7

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=500000+5;
struct Road
{
	int poor,rich;
	bool operator < (const Road& r) const {
		return poor<r.poor;
	}
}road[maxn];
int d[maxn];
int BinerySearch(int L,int R,int x){
	int mid;
	while(L<=R){
		mid=L+(R-L)/2;
		if(d[mid]<x&&d[mid+1]>=x) return mid;
		else if(d[mid]<x) L=mid+1;
		else              R=mid-1;
	}
	return 0;
}
int LIS(int N){
	memset(d,0,sizeof(d));

	int len=1,p;
	d[1]=road[1].rich;
	for (int i = 2; i <= N; ++i)
	{
		int n=road[i].rich;
		if(n>d[len]) p=++len;
		else p=BinerySearch(1,len,n)+1;
		d[p]=n;
				
	}
	// for (int j = 1; j <=len; ++j)
	// 		cout<<d[j]<<' ';
	// 	cout<<endl;		
	return len;
}
int main()
{
	int N,kase=0;
	while(scanf("%d",&N)!=EOF)
	{
		for (int i = 1; i <= N; ++i) 
			scanf("%d%d",&road[i].poor,&road[i].rich);
		sort(road+1,road+N+1);

		int ans=LIS(N);
		printf("Case %d:\nMy king, at most %d %s can be built.\n\n",++kase,ans,ans==1?"road":"roads");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值