题目 | Circle of Mistery
2023牛客暑期多校训练营5
B - Circle of Mistery
https://ac.nowcoder.com/acm/contest/57359/B
题意
考虑长度为
题解
首先,需要考虑选择了
然后,需要考虑选择了
现在,根据上面的策略,如果我们选择了
那么对于位于最后的最小值(本例中的
综上,给定一个置换环元素集合,它的逆序对数目为:
现在,问题就转换为了选出
注意到逆序对数目这个式子,对于一个固定区间
考虑贪心思想,要求求和最大的话,对于
可用一个 multiset
储存元素并维护大小,取的时候从最大开始往小取。时间复杂度
总时间复杂度:
注意,无法取任何数成环是代表不成立,即代码中出现
代码
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
using namespace std;
void solve()
{
int n, k;
cin >> n >> k;
vector<int> w(n + 10);
for (int i = 1; i <= n; i++)
cin >> w[i];
int ans = INT64_MAX;
for (int i = 1; i <= n; i++)
{
int sum = 0, cnt = 0;
multiset<int> ms;
for (int j = i; j <= n; j++)
{
if (w[j] < 0)
{
ms.insert(w[j]);
}
else
{
sum += w[j];
cnt++;
}
if (sum >= k)
{
int tsum = sum, tcnt = cnt;
for (auto ti = ms.rbegin(); ti != ms.rend(); ++ti)
{
if (tsum + *ti < k)
break;
tsum += *ti;
tcnt++;
}
if (tcnt)
ans = min(ans, 2 * (j - i) - tcnt + 1);
}
}
}
if (ans == INT64_MAX)
cout << -1 << endl;
else
cout << ans << endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
while (t--)
solve();
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi