1. 程式人生 > 實用技巧 >【題解】[USACO17JAN]Balanced Photo G

【題解】[USACO17JAN]Balanced Photo G

題目連結:https://www.luogu.com.cn/problem/P3608

方法一

用樹狀陣列求逆序對先後掃兩遍,一次從前往後,一次從後往前,算出每頭奶牛左右兩邊比她高的數量。

最後統計一下。

#include <bits/stdc++.h>
using namespace std;
int sum[500010], l[100010], r[100010];
int n, m, u, v, a[500010], t[500010];
int ans; inline int read()
{
int x = 0;
int f = 1; char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}
while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
return x * f;
} int lowbit(int x)
{
return x & (-x);
} void add(int i, int v)
{
ㅤㅤㅤㅤ while (i <= n)
{
sum[i] += v;
i += lowbit(i);
}
} int query(int i)
{
int ans = 0;
ㅤㅤㅤㅤ while (i)
{
ans += sum[i];
i -= lowbit(i);
}
return ans;
} int main()
{
n = read();
for (int i = 1; i <= n; i++)
a[i] = read(), t[i] = a[i];
ㅤㅤㅤㅤ sort(t + 1, t + 1 + n);
m = unique(t + 1, t + 1 + n) - t - 1;
for (int i = 1; i <= n; i++)
a[i] = lower_bound(t + 1, t + 1 + m, a[i]) - t;
ㅤㅤㅤㅤ for (int i = 1; i <= n; i++)
{
add(a[i], 1);
l[i] = i - query(a[i]);
}
memset(sum, 0, sizeof sum);
ㅤㅤㅤㅤ for (int i = n; i >= 1; i--)
{
add(a[i], 1);
r[i] = n - i + 1 - query(a[i]);
}
ㅤㅤㅤㅤ for (int i = 1; i <= n; i++)
if (max(l[i], r[i]) > 2 * min(l[i], r[i]))
ans++;
printf("%d\n", ans);
return 0;
}