【USACO】 Balanced Photo

【题目链接】

           点击打开链接

【算法】

         树状数组

【代码】

        

#include

using namespace std;

int i,N,ans,l1,l2;
int c[100005],val[100005],id[100005];

template  void read(T &x) {
		int f=1; char c = getchar(); x=0;
		for (; !isdigit(c); c = getchar()) { if (c=='-') f=-1; }
		for (; isdigit(c); c = getchar()) x=x*10+c-'0';
		x*=f;
}

bool cmp(int a,int b) {
		return val[a] > val[b];
}

int lowbit(int x) {
		return x & -x;
}

int query(int x) {
		int sum=0;
		while (x >= 1) {
			  sum += c[x];
			  x -= lowbit(x);
		}	
		return sum;
}

void change(int x,int y) {
		while (x <= N) {
				c[x] += y;
				x += lowbit(x);
		}	
}

int main() {
		
		scanf("%d",&N);
		for (i = 1; i <= N; i++) {
				scanf("%d",&val[i]);
				id[i] = i;
		}
		sort(id+1,id+N+1,cmp);
		
		for (i = 1; i <= N; i++) {
				l1 = query(id[i]-1);
				l2 = i - l1 - 1;
				if (max(l1,l2) > min(l1,l2) * 2) ans++;
				change(id[i],1);	
		}
		
		printf("%d\n",ans);
		
		return 0;
	
}

你可能感兴趣的:(树状数组)