题目
题目描述
Farmer John is arranging his N cows in a line to take a photo (1≤N≤100,000). The height of the ith cow in sequence ishi, and the heights of all cows are distinct.
As with all photographs of his cows, FJ wants this one to come out looking as nice as possible. He decides that cow i looks “unbalanced” if Li and Ri differ by more than factor of 2, where Li and Ri are the number of cows taller than i on her left and right, respectively. That is, i is unbalanced if the larger of Li and Ri is strictly more than twice the smaller of these two numbers. FJ is hoping that not too many of his cows are unbalanced.
Please help FJ compute the total number of unbalanced cows.
输入
The first line of input contains N. The next N lines contain h1…hN, each a nonnegative integer at most 1,000,000,000.
输出
Please output a count of the number of cows that are unbalanced.
样例输入
7
34
6
23
0
5
99
2
样例输出
3
提示
In this example, the cows of heights 34, 5, and 2 are unbalanced.
题意
给n个数(输入第一行),设第i个位置左面和右面分别有x和y个数比第i个位置的数大,并且x>2*y 或者y>2*x时,这个数即是不平衡的。
最后结果输出不平衡的数的数量(每个数其实代表照片上每头牛的高度,所以题目叫 Balance Photo)。
思路
思路就是,树状数组,先用一个数组存下输入的数,再将该数组排序,然后再用另一个数组记录第i个输入的数是第几大,比如b[i]=j;
即输入的第i个数是第j大的数;再树状数组一下。关于树状数组,我是看得这篇文章。
http://blog.youkuaiyun.com/int64ago/article/details/7429868
这东西不好懂,所谓书读百遍,其义自见,我看SG函数的时候看了十几遍才顿悟了。
加油吧。
代码如下:
//Time:84 ms
//Memory:17324 kb
#include <iostream>
#include <cstdio>
#include<algorithm>
using namespace std;
int n,m,b[1000005],l,r,ans,t[1000005];
typedef struct
{
int v,id;
} PO;
PO a[1000005];
bool cmp(PO x,PO y)
{
return x.v>y.v;
}
int lowbit(int x)
{
return x&-x;
}
void update(int x,int v)
{
for(; x<n; x+=lowbit(x))t[x]+=v;
}
int findx(int x)
{
int ans=0;
for(; x; x-=lowbit(x))ans+=t[x];
return ans;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1.txt","r",stdin);
#endif // ONLINE_JUDGE
ios_base::sync_with_stdio(false);
cin.tie(0);
scanf("%d",&n);
for(int i=1; i<=n; i++)scanf("%d",&a[i].v),a[i].id=i;
sort(a+1,a+1+n,cmp);
for(int i=1; i<=n; i++)
b[a[i].id]=i;
for(int i=1; i<=n; i++)
{
l=findx(b[i]);
r=b[i]-l-1;
if((l*2<r)||(r*2<l))ans++;
update(b[i],1);
}
printf("%d\n",ans);
}