欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

[CODEVS 1285] 宠物收养所

发布时间:2025/3/15 编程问答 30 豆豆
生活随笔 收集整理的这篇文章主要介绍了 [CODEVS 1285] 宠物收养所 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

http://codevs.cn/problem/1285/

题解

运用STL的set,和算法库(Algorithm)的upper_bound()与lower_bound(),实现log(n)的查找。要注意的是set类的upper_bound(x) 返回在集合中第一个大于x的元素,而lower_bound()返回在集合中第一个大于或等于x的元素,与它们在数组中的作用不太一样。

代码

总时间耗费: 657ms
总内存耗费: 748B

#include<cstdio> #include<iostream> #include<cstring> #include<string> #include<set> #include<cmath> #include<algorithm> using namespace std;set<int> S; int main() {int n;bool flag;cin >> n;int ans = 0;for(int i = 1; i <= n; i++) {int a, b;cin >> a >> b;if(S.empty() || flag == a) {S.insert(b);flag = a;} else {set<int>::iterator it = S.lower_bound(b);int x = *it, y = (it == S.begin())? (*it) : *(--it);if(abs(b-x) <= abs(b-y)) S.erase(x); else S.erase(y);ans = (ans + min(abs(b-x), abs(b-y))) % 1000000;}}cout << ans << endl;return 0; }

总结

以上是生活随笔为你收集整理的[CODEVS 1285] 宠物收养所的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。