题目链接:A-Leftbest
这一题如果出现二重循环,我想你应该换一换思路,因为一定会超时。
我感觉这一题在考察STL,可以用set集合,因为集合中的元素是按照升序排列的(去重),这时,我们只需找a[i]的下一个元素即可,因为这恰好是临界点,恰好大于a[i]又是大于a[i]中最小的。
#include <iostream>
#include <algorithm>
#include <set> // STL 的知识
using namespace std;
int n;
long long sum = 0;
int val;
set <int> s;
int main()
{
cin >> n;
s.clear();
set<int>::iterator it; // 迭代器
for(int i = 0; i < n; ++i) {
cin >> val;
it = s.find(val); // set 集合已经排好序
if(it == s.end()) s.insert(val); // 未找到, 直接插入
it = s.find(val);
++it;
if(it != s.end()) sum += *it;
}
cout << sum << endl;
return 0;
}