现在的位置: 首页 > 综合 > 正文

poj 2182 Lost Cows

2018年04月23日 ⁄ 综合 ⁄ 共 1990字 ⁄ 字号 评论关闭

用数组a[]记录第i头牛之前有多少头序号比它小的牛,则最后一头牛n的序号肯定是a[n]+1(因为所有的牛都在它前面);

倒数第二头牛的编号肯定是把倒数第一的牛的编号删去后排在第a[n-1]+1的位置上;依次类推

样例分析一下:

编号 1
2 3 45;

数据 0
1 2 10;

最后一头编号肯定是   1;然后把 1 删除掉

编号 2
3 4 5;

倒数第二头的编号 就是排在剩余编号第 a[4]+1的位置上 ,即第二位,编号为3,删掉;

编号 2
4 5;

倒数第三头一次 排在第3位,编号为 5,删掉;

编号 2
4;

倒数第四头  排在第2位 编号为4
删掉;

编号  2;

最后一头 排在第一位
编号为2;

所以ans: 2
4 5 31;

数据比较大,所以线段树求解;每一个子树的root保存的是当前子树下还有多少个叶子可用(用len表示,比如说你查到第一头牛的编号为1,那么叶子线段(1,1)在下次查询时就不可用了),所以我们找的就是第几大的叶子这个问题,很轻松就可以解决了,设我们查询的是第k大的:

1.如果左子树的len大于等于k,那么优先进入左子树;

2.否则进入右子树,但同时别忘记k= k  -  left . len(即减去左子树的len,因为左子树里面有len个数是比你要查询的数小的)

code:

#include <iostream>
#include <fstream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <string.h>
#include <vector>
#include <bitset>
#include <cmath>
#include <queue>
#include <stack>
#include <set>
#include <ctime>
#include <map>
#include <limits>
#define LL long long
#define Vi vector<int>
#define Si set<int>
#define readf freopen("input.txt","r",stdin)
#define writef freopen("output.txt","w",stdout)
#define FF(i,a) for(int i(0); i < (a); i++)
#define FD(i,a) for(int i(a); i >= (1); i--)
#define FOR(i,a,b) for(int i(a);i <= (b); i++)
#define FOD(i,a,b) for(int i(a);i >= (b); i--)
#define PD(a) printf("%d",a)
#define SET(a,b) memset(a,b,sizeof(a))
#define SD(a) scanf("%d",&(a))
#define LN printf("\n")
#define PS printf(" ")
#define pb push_back
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
const double pi = acos(-1.0);
const int maxn = 8001;
const int INF = 99999999;
const int dx[]={0,1,0,-1};
const int dy[]={1,0,-1,0};
using namespace std;
int a[maxn],ans[maxn];
int len[maxn<<2];
void PushUP(int rt){
    len[rt]=len[rt<<1]+len[rt<<1|1];
}
void build(int l,int r,int rt){
    if(l==r){
        len[rt]=1;
        return ;
    }
    int m=(l+r)>>1;
    build(lson);
    build(rson);
    PushUP(rt);
}
int query(int l,int r,int rt,int x){
    if(l==r){
        len[rt]=0;
        return r;
    }
    int m=(l+r)>>1;
    int ret;
    if(x<=len[rt<<1])   ret=query(lson,x);
    else    ret=query(rson,x-len[rt<<1]);
    PushUP(rt);
    return ret;
}
void print(int l,int r,int rt){
    printf("l:%d  r:%d   len:%d \n",l,r,len[rt]);
    if(l==r)
        return ;
    int m=(l+r)>>1;
    print(lson);
    print(rson);
}
int main()
{
    int N;
    SD(N);
    build(1,N,1);
    FOR(i,2,N)  SD(a[i]);
    FOD(i,N,1){
        ans[i]=query(1,N,1,a[i]+1);
    }

    FOR(i,1,N)
        printf("%d\n",ans[i]);
    return 0;
}




【上篇】
【下篇】

抱歉!评论已关闭.