题目
二分
cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 5e5 + 10;
bool vis[N];
int a[N];
int two, pos = 1, n;
ll sum;
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
sort(a + 1, a + n + 1, greater<int>());
while (pos <= n)
{
if (vis[pos] == 1)
{
pos++;
continue;
}
vis[pos] = 1;
two++;
sum += a[pos];
if (two >= 2)
{
int l = pos + 1;
int r = n;
while (l < r)
{
int mid = l + r >> 1;
if (a[mid] <= a[pos] / 2)
r = mid;
else
l = mid + 1;
}
if (a[l] <= a[pos] / 2)
{
while (vis[l])
l++;
vis[l] = 1;
}
two = 0;
}
pos++;
}
cout << sum;
}
妙用STL
cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> v;
long long sum;
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
v.push_back(x);
}
sort(v.begin(), v.end());
while (v.size())
{
auto it = prev(v.end());
int v1 = *it;
sum += v1;
if (it == v.begin())
break;
int v2 = *prev(it);
sum += v2;
v.erase(prev(v.end()));
v.erase(prev(v.end()));
auto lower = upper_bound(v.begin(), v.end(), v2 / 2);
if (lower == v.begin())
continue;
v.erase(prev(lower));
}
cout << sum;
}