P2234 [HNOI2002]营业额统计
#include <bits/stdc++.h>
using namespace std;
int n, x, ans;
set<int> s;
set<int>::iterator iter, before;
int main()
{
scanf("%d", &n);
scanf("%d", &x);
s.insert(x);
ans+=x;
for(int i=2; i<=n; ++i){
scanf("%d", &x);
//找到第一个大于等于x的位置
iter=s.lower_bound(x);
//x在里面是最小的
if(iter==s.begin()){
ans+=abs(*iter-x);
}
else{
before=iter;
before--;
ans+=min(abs(x-*iter), abs(x-*before));
}
s.insert(x);
}
printf("%d", ans);
return 0;
}
或者
#include <bits/stdc++.h>
using namespace std;
int n, x, ans;
set<int> s;
set<int>::iterator iter, before;
int main()
{
scanf("%d", &n);
s.insert(1e9);
s.insert(-1e9);
for(int i=1; i<=n; ++i){
scanf("%d", &x);
if(i==1){
ans+=x;
}
else{
iter=s.lower_bound(x);
before=iter;
before--;
ans+=min(abs(x-*iter), abs(x-*before));
}
s.insert(x);
}
printf("%d", ans);
return 0;
}
multiset
P1090 [NOIP2004 提高组] 合并果子 / [USACO06NOV] Fence Repair G
#include<bits/stdc++.h>
using namespace std;
int n, x, ans, cur;
multiset<int> s;
multiset<int>::iterator asd;
int main(){
scanf("%d", &n);
//nlogn复杂度
for(int i=1; i<=n; ++i){
scanf("%d", &x);
s.insert(x); //将元素插入到multiset中
}
for(int i=1; i<n; ++i){ //总共n-1次即可
//每次选最小的两个合并
cur=0; //当前两个果子的和
//找出multiset中当前最小的值 O(1)的复杂度
cur+=*s.begin(); //将它的值加到cur中
s.erase(s.begin()); //将最小的值删掉 O(logn)的复杂度
//找出multiset中当前最小的值 O(1)的复杂度
cur+=*s.begin();
s.erase(s.begin()); //将最小的值删掉 O(logn)的复杂度
ans+=cur; //加到答案里
s.insert(cur); //将大果子插入到multiset中
}
printf("%d", ans);
return 0;
}
P5250 【深基17.例5】木材仓库
#include <bits/stdc++.h>
using namespace std;
int n, opt, len, ans1, ans2;
multiset<int> s;
multiset<int>::iterator asd;
int main()
{
scanf("%d", &n);
s.insert(-2000000000);
s.insert(2000000000);
while(n--){
scanf("%d %d", &opt, &len);
if(opt==1){ //放入
if(s.count(len)){
printf("Already Exist\n");
}
else{
s.insert(len);
}
}
else if(opt==2){
if(s.size()==2){
printf("Empty\n");
}
else{
//找到第一个大于等于len的
asd=s.lower_bound(len);
ans2=*asd;
asd--;
ans1=*asd;
if(abs(ans1-len)<=abs(ans2-len)){
printf("%d\n", ans1);
s.erase(ans1);
}
else{
printf("%d\n", ans2);
s.erase(ans2);
}
}
}
}
return 0;
}