POJ2182 Lost Cows 数状数组+二分 动态找一个序列第k打元素 算法竞赛进阶指南

描述

N (2 <= N <= 8,000) cows have unique brands in the range 1..N. In a spectacular display of poor judgment, they visited the neighborhood 'watering hole' and drank a few too many beers before dinner. When it was time to line up for their evening meal, they did not line up in the required ascending numerical order of their brands.

Regrettably, FJ does not have a way to sort them. Furthermore, he's not very good at observing problems. Instead of writing down each cow's brand, he determined a rather silly statistic: For each cow in line, he knows the number of cows that precede that cow in line that do, in fact, have smaller brands than that cow.

Given this data, tell FJ the exact ordering of the cows.

输入

* Line 1: A single integer, N

* Lines 2..N: These N-1 lines describe the number of cows that precede a given cow in line and have brands smaller than that cow. Of course, no cows precede the first cow in line, so she is not listed. Line 2 of the input describes the number of preceding cows whose brands are smaller than the cow in slot #2; line 3 describes the number of preceding cows whose brands are smaller than the cow in slot #3; and so on.

输出

* Lines 1..N: Each of the N lines of output tells the brand of a cow in line. Line #1 of the output tells the brand of the first cow in line; line 2 tells the brand of the second cow; and so on.

样例输入

5
1
2
1
0

样例输出

2
4
5
3
1

来源

USACO 2003 U S Open Orange

题意:已知第i头牛前面有ai头牛比它高,求每头牛的升高(1到n)

思路:如果最后头牛升高为a(n) 那么它的升高为an+1,就是1到n中第a(n)+1大的数  

然后去掉这个数,      第an-1头牛的 升高就是 1到n中第  a(n-1)  +1 大的数依次类推到第一头牛

建立一个全是1的数状数组    找第x大的数就去二分  sum(mid)==x的位置   那个位置就是第i头牛的升高

然后把mid那个位置更新为0  

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstdlib>
#include<deque>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int>P;
const int len=1e5+5;
const ll mod=1e9+7;
int n;
int c[len];
int a[len];
int ans[len];
int sum(int i)
{
	int ans=0;
	for(;i;i-=i&(-i))ans+=c[i];
	return ans;
}
void add(int i,int v)
{
	for(;i<=n;i+=i&(-i))c[i]+=v;
}
int solve(int x)//二分前缀和为x的位置 
{
	int l=1,r=n+1,mid;
	while(l<r) 
	{
		mid=(l+r)/2;
		if(sum(mid)>=x)r=mid;
		else l=mid+1;
	}
	return r;
}
int main()
{
	cin>>n;
	for(int i=1;i<=n;++i)add(i,1);
	for(int i=2;i<=n;++i)cin>>a[i];
	for(int i=n;i>=1;--i)
	{
		ans[i]=solve(a[i]+1);
		add(ans[i],-1);
	}
	for(int i=1;i<=n;++i)
		if(sum(i)-sum(i-1))ans[1]=i;
	for(int i=1;i<=n;++i)printf("%d\n",ans[i]);
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值