您的位置:首页 > 其它

CodeForces 830B - Cards Sorting

2017-07-14 20:53 387 查看
将每个数字的位置存进该数字的vector中

原数组排个序从小到大处理,每次在vector里二分找到距离当前位置“最远”的位置(相差最大),更新答案

树状数组维护每个数字现在的位置和原位置之差

#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 100005;
int n;
int a
, b
;
vector<int> v
;
int c
;
void modify(int x, int num)
{
while (x <= 100000) c[x] += num, x += x&-x;
}
int sum(int x)
{
int s = 0;
while (x) s += c[x], x -= x&-x;
return s;
}
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++) scanf("%d", &a[i]), b[i] = a[i];
sort(b+1, b+1+n);
for (int i = 1; i <= n; i++)
v[a[i]].push_back(i);
LL ans = 0;
int now = 0;
for (int i = 1; i <= n;)
{
int p = lower_bound(v[b[i]].begin(), v[b[i]].end(), now) - v[b[i]].begin();
if (p == 0)
{
int pos = v[b[i]][v[b[i]].size()-1];
ans += pos - sum(pos) - (now - sum(now));
now = pos;
}
else
{
int pos = v[b[i]][p-1];
ans += n - sum(n) - (now-sum(now)) + pos - sum(pos);
now = pos;
}
for (int j = 0; j < v[b[i]].size(); j++) modify(v[b[i]][j], 1);
i += v[b[i]].size();
}
cout << ans << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: