码迷,mamicode.com
首页 > 其他好文 > 详细

poj2182-Lost Cow

时间:2016-09-21 00:08:20      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:

题目链接 http://vjudge.net/problem/POJ-2182

 

解题思路

用最朴素的想法,从尾到头扫描,再开两个循环找空位,时间复杂度O(n3),容易超时。

正确的做法是建立线段树。维护每个区间的长度。长度足够排下就往左子树走,否则往右子树。

直到叶子节点,此时叶子节点的区间(点)为此奶牛的编号。

 

代码

#include<stdio.h>
#define MAX_SIZE 10010
struct Node {
    int l, r;
    int len;
}tree[4*MAX_SIZE];
int small[MAX_SIZE], q[MAX_SIZE];
void BuildTree(int root, int left, int right)
{
    if(left == right) {
        tree[root].l = tree[root].r = right;
        tree[root].len = 1;
        return ;
    }
    tree[root].l = left; tree[root].r = right;
    tree[root].len = right - left + 1;
    int mid = (left + right) / 2;
    BuildTree(root*2, left, mid);
    BuildTree(root*2+1, mid+1, right);
}
int query(int root, int s)
{
    tree[root].len--;
    if(tree[root].l == tree[root].r) return tree[root].l;
    if(tree[root*2].len >= s) return query(root*2, s);
    else return query(root*2+1, s - tree[root*2].len);
}
int main()
{
    int n;
    scanf("%d", &n);
    for(int i=2; i<=n; i++) scanf("%d", &small[i]);
    small[1] = 0;
    BuildTree(1, 1, n);
    for(int i=n; i>=1; i--) q[i] = query(1, small[i]+1);
    for(int i=1; i<=n; i++) printf("%d\n", q[i]);
    return 0;
}
    

 

poj2182-Lost Cow

标签:

原文地址:http://www.cnblogs.com/ZengWangli/p/5890941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!