LA 3882 And Then There Was One

8 篇文章 0 订阅
4 篇文章 0 订阅

这道题是一道约瑟夫环问题,只不过数据加强了,因为

不需要求出删除序列,只需要求出删除的最后一个的数字,

所以有递推的方法和线段树

#include <stdio.h>
#include <string.h>
#define lson l, m, rt << 1
#define rson m+1, r, rt << 1 | 1
const int maxn = 1000005;
int cnt[maxn << 3];
void Build ( int l, int r, int rt )
{
    cnt[rt] = r-l+1;
    if ( l == r )
        return ;
    int m = ( l+r ) >> 1;
    Build ( lson );
    Build ( rson );
}
void PushUP ( int rt )
{
    cnt[rt] = cnt[rt << 1]+cnt[rt << 1 | 1];
}
void update ( int q, int l, int r, int rt )
{
    if ( l == r )
    {
        cnt[rt] = 0;
        return ;
    }
    int m = ( l+r ) >> 1;
    if ( q <= cnt[rt << 1] )
        update ( q, lson );
    else
        update ( q-cnt[rt << 1], rson );
    PushUP ( rt );  //注意更新
}
int query ( int q, int l, int r, int rt )
{
    if ( l == r )
        return l;
    int m = ( l+r ) >> 1;
    if ( q <= cnt[rt << 1] )
        return query ( q, lson );
    else
        return query ( q-cnt[rt << 1], rson );
}
int main ( )
{
    int n, k, m;
    while ( ~ scanf ( "%d%d%d", &n, &k, &m ) && n )
    {
        memset ( cnt, 0, sizeof ( cnt ) );
        Build ( 1, n, 1 );
        for ( int i = n-1; i >= 1; i -- )   //n-1次需要去掉的数
        {
            update ( m, 1, n, 1 );
            m = ( m+k-2+i )%i+1;    //算出当前排第几
            //printf ( "%d\n", m );
        }
        printf ( "%d\n", query ( 1, 1, n, 1 ) );    //查询留下来的数
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值