实现细节见代码:
#include <bits/stdc++.h>
using namespace std;
#define int long long
typedef long long ll;
const int MAXN = 1e5 + 10;
int sum[2][MAXN];
struct Node {
int v, w;
}a[MAXN];
bool cmp(Node x, Node y) {
return x.v < y.v;
}
int lowbit(int x) {
return x & -x;
}
void add(int x, int k) {
for (int i = x; i < 100005; i += lowbit(i)) {
sum[k][i] += k ? x : 1;
}
}
int getsum(int x, int k) {
int ans = 0;
for (int i = x; i; i -= lowbit(i)) {
ans += sum[k][i];
}
return ans;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i].v >> a[i].w;
}
sort(a + 1, a + 1 + n, cmp); // 按照v从小到大排序,方便之后的答案统计
int all = 0; // 目前总的距离数
int ans = 0;
for (int i = 1; i <= n; i++) {
int cnt1 = getsum(a[i].w, 0); // 个数
int cnt2 = getsum(a[i].w, 1); // 距离
int l = cnt1 * a[i].w - cnt2;
int r = all - cnt2 - (i - 1 - cnt1) * a[i].w;
ans += (l + r) * a[i].v;
all += a[i].w;
add(a[i].w, 0);
add(a[i].w, 1);
}
cout << ans << endl;
return 0;
}
类似的题目:
这道题目就是根据坐标从大到小排序,然后剩余的思路和上面的题目几乎一样。
实现细节见代码:
#include <bits/stdc++.h>
using namespace std;
#define int long long
typedef long long ll;
const int MAXN = 1e5 + 10;
int n, sum[2][MAXN], num[MAXN];
struct Node {
int x, h, f, s;
}a[MAXN];
bool cmp(Node x, Node y) {
if (x.h == y.h) {
return x.x < y.x;
}
return x.h > y.h;
}
void init() {
sort(num + 1, num + 1 + n);
int cur = 1;
// 求出题目要求的对应f和s的值
for (int i = n; i >= 1; i--) {
if (i > 1 && a[i].h == a[i + 1].h) {
a[i].s = a[i + 1].s;
}
else {
a[i].s = cur;
}
cur++;
a[i].f = lower_bound(num + 1, num + 1 + n, a[i].x) - num;
}
}
int lowbit(int x) {
return x & -x;
}
void add(int x, int k) {
for (int i = x; i < 100005; i += lowbit(i)) {
sum[k][i] += k ? x : 1;
}
}
int getsum(int x, int k) {
int ans = 0;
for (int i = x; i; i -= lowbit(i)) {
ans += sum[k][i];
}
return ans;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
while (cin >> n) {
memset(sum, 0, sizeof sum);
for (int i = 1; i <= n; i++) {
cin >> a[i].x >> a[i].h;
num[i] = a[i].x;
}
sort(a + 1, a + 1 + n, cmp);
init();
int ans = 0, all = 0;
for (int i = 1; i <= n; i++) {
int s1 = getsum(a[i].f, 0); // 个数
int s2 = getsum(a[i].f, 1); // 距离
ans += a[i].s * (s1 * a[i].f - s2);
ans += a[i].s * (all - s2 - (i - 1 - s1) * a[i].f);
add(a[i].f, 0);
add(a[i].f, 1);
all += a[i].f;
}
cout << ans << endl;
}
return 0;
}