이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
#define N 100010
#define int long long
using namespace std;
int n, k, q;
struct BIT{
int node[N];
void add(int pos, int x){
for(int i = pos;i <= k;i += (i & -i)){
node[i] += x;
}
}
int query(int pos){
int s = 0;
for(int i = pos;i > 0;i -= (i & -i)){
s += node[i];
}
return s;
}
} dp;
map <pair <int, int>, int> m;
vector <int> mark[N];
int32_t main(){
cin >> n >> k >> q;
vector <int> v;
int ig = 0;
for(int i = 0;i < n;i++){
int x;
cin >> x;
v.push_back(x);
mark[x].push_back(i);
}
for(int i = 1;i <= k;i++){
sort(mark[i].begin(), mark[i].end());
ig += (mark[i].size()*(mark[i].size() -1))/2;
}
int res = 0;
for(int i = 0;i < n;i++){
res += dp.query(v[i]-1);
dp.add(v[i], 1);
}
res = n*(n-1)/2 - res;
res -= ig;
// cout << res << '\n';
vector <int> pos;
for(int i = 1;i <= n;i++){
pos.push_back(i);
}
for(int i = 0;i < q;i++){
int x;
cin >> x;
int a = pos[x-1], b = pos[x];
swap(pos[x-1], pos[x]);
if(m.find({a, b}) != m.end()){
res += m[{a, b}];
cout << res << '\n';
continue;
}
bool swp = false;
if(mark[a].size() > mark[b].size()){swap(a, b); swp = true;}
int aux = 0;
for(auto x : mark[a]){
auto it = upper_bound(mark[b].begin(), mark[b].end(), x);
aux += it - mark[b].begin();
}
if(!swp){
res += -2*aux + mark[a].size()*mark[b].size();
m[{a, b}] = -2*aux + mark[a].size()*mark[b].size();
}
else{
res -= mark[a].size()*mark[b].size() - 2*aux;
m[{b, a}] = -(mark[a].size()*mark[b].size() - 2*aux);
}
cout << res << "\n";
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |