题意:给出一个 n 个数的数列 {},对于第 i 个元素 ,定义 ,其中,。求
样例输入:
6
5 1 2 5 4 6
样例输出:
12
思路:用stl中的set维护序列,一个一个加入,加入前用set内置的upper_bound函数查找大于等于的数,再将加到sum里即可。
AC代码:
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
set<int> st;
int n,x;
cin>>n;
int ans=0;
for(int i=0;i<n;i++)
{
cin>>x;
if(i==0)
{
st.insert(x);
ans+=x;
}
else
{
auto up=st.upper_bound(x);
if(up!=st.begin()&&up!=st.end())
{
auto xx=up--;
ans+=min(abs(x-(*up)),abs(x-(*xx)));
}
else if(up==st.begin())
ans+=abs(x-(*up));
else
{
up--;
ans+=abs(x-(*up));
}
st.insert(x);
}
}
cout<<ans<<endl;
return 0;
}