【题解】[USACO17JAN]Balanced Photo G

题目链接:https://www.luogu.com.cn/problem/P3608

方法一

用树状数组求逆序对先后扫两遍,一次从前往后,一次从后往前,算出每头奶牛左右两边比她高的数量。

最后统计一下。

#include 
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;
}

你可能感兴趣的:(【题解】[USACO17JAN]Balanced Photo G)