1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include<bits/stdc++.h> #define x first #define y second #define ok puts("ok"); using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> pii; typedef pair<ll, ll> pll; const double PI = acos(-1.0); const int INF=0x3f3f3f3f; const ll LINF=0x3f3f3f3f3f3f3f3f; const int N=2e5+9; const int shift=1e3+9; const double Eps=1e-7;
ll sum[4][N], n, k, ans; pii a[N];
ll query(int p, int id) { ll ans = 0; while(p > 0) { ans += sum[id][p]; p -= p & -p; } return ans; }
void add(int p, int v, int id) { while(p <= n) { sum[id][p] += v; p += p & -p; } }
int main(void) { if(fopen("in", "r")!=NULL) {freopen("in", "r", stdin); freopen("out", "w", stdout);} while(cin >> n >> k) { ans = 0; memset(sum, 0, sizeof sum); for(int i = 1; i <= n; i++) { scanf("%d", &a[i].x); a[i].y = i; } sort(a+1, a+n+1); for(int i = 1; i <= n; i++) { int id = a[i].y & 1; int r = a[i].y + k - 1; int l = a[i].y - k + 1; if(l < 1) l = k - a[i].y + 1; if(r > n) r = 2*n - a[i].y - k + 1;
if(k & 1) ans += 1LL * a[i].x * (query(r, id+2) - query(l-1, id+2)) - (query(r, id) - query(l-1, id)); else ans += 1LL * a[i].x * (query(r, (id+2)^1) - query(l-1, (id+2)^1)) - (query(r, id^1) - query(l-1, id^1));
add(a[i].y, a[i].x, id); add(a[i].y, 1, id + 2); } printf("%lld\n", ans); } return 0; }
|