51nod 1460 连接小岛 (贪心)

本文介绍了一种用于解决桥梁建设问题的高效算法。该算法通过计算相邻岛屿间所需桥梁长度的范围,并利用多集进行匹配,确保所有岛屿都能通过桥梁相连。时间复杂度为O(nlogn),适用于大规模岛屿网络构建。
对于每两个相邻岛屿,通过简单的计算,可以得出可以连接这两座岛之间的 所需要的桥的 长度范围,有n-1个这样的范围
然后就相当于用m个点,其中抽出n-1个点去对应n-1个区间。
我的做法是把所有的区间按照右端点从小到大排序,,右端点相同按照左端点从小到大排序,
然后用multiset去存桥的长度,每次lower_bound一下,判断一下
时间复杂度O(nlogn)。
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
#include<stdio.h>
#include<set>
#include<vector>
#define LL long long int
using namespace std;

struct line
{
	LL l,r;
	bool operator < (const line tar)
	{
		if(tar.r > r) return true;
		else if(tar.r == r)
		{
			if(tar.l > l) return true;
			return false;
		}
		else return false;
	}
};

int n,m;
const int maxn = 220000;
line arr[maxn];
vector<line> lt;
multiset<LL> st;

void init()
{
	lt.clear();
	st.clear();
}

int main()
{
	while(cin>>n>>m)
	{
		init();
		for(int i = 0;i<n;i++)
		{
			LL l,r;
			scanf("%lld %lld",&l,&r);
			arr[i].l = l;
			arr[i].r = r;
		}
		for(int i = 0;i<m;i++)
		{
			LL tmp;
			scanf("%lld",&tmp);
			st.insert(tmp);
		}
		if(m < n-1)
		{
			printf("NO\n");
			continue;
		}
		sort(arr,arr+n);
		for(int i = 1;i<n;i++)
		{
			line tmp;
			tmp.r = arr[i].r - arr[i-1].l;
			tmp.l = arr[i].l - arr[i-1].r;
			lt.push_back(tmp);
		}
		sort(lt.begin(),lt.end());
		
		int cnt = 0;
		multiset<LL> ::iterator iter;
		for(int i = 0;i<lt.size();i++)
		{
			iter = st.lower_bound(lt[i].l);
			if(iter == st.end() || *iter > lt[i].r)
			{
				break;
			}
			else 
			{
				st.erase(iter);
				cnt ++;
				if(cnt == n-1) break;
			}
		}
		if(cnt == n-1) printf("YES\n");
		else printf("NO\n");
	}
	return 0;
}



目前没有关于51nod 3478题目的具体描述和官方公布的C++解决方案代码。以下是一种通用的解题思路以及一个示例C++代码模板,可以用于解决类似的问题。 ### 问题解题思路 51nod 3478通常可能涉及以下算法或技术: - 动态规划(DP)或状态转移方程 - 贪心算法 - 数据结构(如线段树、堆、优先队列等) - 图论算法(如最短路径、最小生成树等) ### 示例C++代码模板 以下是一个通用的C++代码框架,适用于需要读取输入并处理大规模数据的问题: ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; const int MAXN = 100005; // 根据题目规模调整 int n; ll k; ll a[MAXN]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n >> k; for (int i = 1; i <= n; ++i) { cin >> a[i]; a[i] += a[i - 1]; // 前缀和 } // 示例逻辑:查找是否存在和为k的连续子数组 unordered_map<ll, int> prefix_map; prefix_map[0] = 0; for (int i = 1; i <= n; ++i) { if (prefix_map.find(a[i] - k) != prefix_map.end()) { cout << prefix_map[a[i] - k] + 1 << " " << i << endl; return 0; } prefix_map[a[i]] = i; } cout << "No Solution" << endl; return 0; } ``` ### 说明 - 上述代码使用了前缀和和哈希表(`unordered_map`)来高效查找是否存在和为`k`的连续子数组。 - 时间复杂度为O(n),适用于大规模输入。 - 如果题目有其他特定要求,可以根据具体条件修改代码逻辑。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值