NOJ 1190 约瑟夫问题 线段树OR树状数组

本文介绍约瑟夫问题的经典解法,利用线段树和树状数组等数据结构实现人员出列顺序的高效计算。通过具体代码展示如何逐步求解并输出最终结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接


约瑟夫问题
时间限制(普通/Java) : 1000 MS/ 3000 MS          运行内存限制 : 65536 KByte
总提交 : 607            测试通过 : 57 
比赛描述
约瑟夫问题是一个非常经典的问题,它的问题描述是:有 n 个人围成一圈,从第 1 个人开始,每次按顺时针方向向后选择第 m 个人,并将这个人出列。那么你能高效的算出出列的顺序吗?

输入
输入数据有多组,每组输入数据为一行,两个正整数 n和m (1<=n,m<=30000)

输出
每组输出只有一行,表示出列的顺序。每两个数字之间用一个空格分开。

样例输入
4 2
5 3

样例输出
2 4 3 1
3 1 5 2 4

很不错的一个题目,常用方法时数组或者链表模拟,会TLE,如果求最后剩下一个人的编号可以用数学方法计算。

思路

将每次出列的人拿掉,从左往右形成一个新的序列,每次从上一个出列的人所处为的位置考虑,找出下一个出列的人在新序列中的位置。

使用线段树或者树状树组可以很好的找到新序列中的第k个人的位置。

树状数组

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <stack>
#include <string>
#include <math.h>
#include <bitset>
#include <ctype.h>
#include <set>
using namespace std;
typedef pair<int,int> P;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-9;
const int N = 3e4 + 5;
const int mod = 1e9 + 7;
int n, c[N];
inline int lowbit(int x)
{
    return x&(-x);
}
void add(int x, int val)
{
    while(x <= n)
    {
        c[x] += val;
        x += lowbit(x);
    }
}
int sum(int x)
{
    int ans = 0;
    while(x)
    {
        ans += c[x];
        x -= lowbit(x);
    }
    return ans;
}
int m;
int main()
{
    while(scanf("%d%d", &n, &m) != EOF)
    {
        memset(c, 0, sizeof(c));
        for(int i = 1; i <= n; i++)
            add(i,1);
        int num = n, i = 0;
        while(num > 1)
        {
            int j = (i+m-1)%num;
            int p = j+1;
            int l = 1, r = n, mid;
            while(l <= r)
            {
                mid = (l+r) >> 1;
                if(sum(mid) >= p) r = mid - 1;
                else l = mid + 1;
            }
            printf("%d ",r+1);
            add(r+1, -1);
            i = j % (num-1);
            num--;
        }
        int l = 1, r = n;
        while(l <= r)
        {
            int mid = (l+r) >> 1;
            if(sum(mid) >= 1) r = mid - 1;
            else l = mid + 1;
        }
        printf("%d\n", r+1);
    }
    return 0;
}

线段树

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <stack>
#include <string>
#include <math.h>
#include <bitset>
#include <ctype.h>
#include <set>
using namespace std;
typedef pair<int,int> P;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-9;
const int N = 3e4 + 5;
const int mod = 1e9 + 7;
int sum[N<<2];
int n,m;
int ans[N];
void build(int rt, int l, int r)
{
    if(l == r)
    {
        sum[rt] = 1;
        return;
    }
    int m = (l+r) >> 1;
    build(rt << 1 , l, m);
    build(rt << 1|1, m+1, r);
    sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}

void update(int pos, int val, int rt, int l, int r)
{
    if(l == r)
    {
        sum[rt] = 0;
        return ;
    }
    int m = (l+r) >> 1;
    if(pos <= m) update(pos, val, rt<<1, l, m);
    else update(pos, val, rt<<1|1, m+1, r);
    sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}

int query(int pos, int rt, int l, int r)
{
    if(l == r)
        return l;
    int m = (l+r) >> 1;
    if(pos > sum[rt<<1]) return query(pos - sum[rt<<1], rt<<1|1, m+1, r);
    else
        return query(pos, rt<<1, l, m);
}

int main()
{
    while(EOF != scanf("%d%d", &n,&m))
    {
        build(1,1,n);
        int len = n;
        int i = 0;
        int pos = 0;
        while(len > 1)
        {
            int p = (i + m-1)%len;
            ans[pos++] = query(p+1, 1, 1, n);
            update(ans[pos-1], 0, 1, 1, n);
            i = p%(len - 1);
            len--;
        }
        ans[pos++] = query(1,1,1,n);
        for(int i = 0; i < pos; i++)
        {
            if(i) printf(" ");
            printf("%d", ans[i]);
        }
        printf("\n");
    }
    return 0;
}

转载于:https://www.cnblogs.com/Alruddy/p/7416300.html

### NOJ树相关的题目及解法 #### 树的概念及其重要性 树是一种重要的数据结构,在计算机科学中有广泛的应用。它由节点和边组成,具有层次化的特性。常见的树有二叉树、平衡二叉树(AVL)、红黑树以及堆等变体[^1]。 #### 常见的树操作 对于树的操作通常包括但不限于以下几个方面: - **构建树**:通过输入的数据建立一棵树。 - **遍历树**:前序、中序、后序以及层序遍历是基本的四种方式[^2]。 - **查找节点**:在给定条件下寻找特定节点。 - **更新或删除节点**:修改或者移除某些节点并保持树的整体性质不变。 下面是一些可能涉及这些操作的具体例子: --- #### 题目一:二叉搜索树 (Binary Search Tree) 的构造查询 ##### 描述 给出一组整数序列,按照顺序依次插入到初始为空的一棵二叉搜索树中,并完成如下任务: 1. 构建该二叉搜索树; 2. 查询某个值是否存在; 3. 输出按某种次序遍历的结果。 ##### 解决方案 可以采用递归方法实现二叉搜索树的插入功能。以下是 Python 实现的一个简单版本: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def insert_into_bst(root, val): if not root: return TreeNode(val) if val < root.val: root.left = insert_into_bst(root.left, val) elif val > root.val: root.right = insert_into_bst(root.right, val) return root def inorder_traversal(root): result = [] stack = [(root, False)] while stack: node, visited = stack.pop() if node: if visited: result.append(node.val) else: stack.append((node.right, False)) stack.append((node, True)) stack.append((node.left, False)) return result ``` 上述代码实现了二叉搜索树的插入函数 `insert_into_bst` 和基于栈的中序遍历算法 `inorder_traversal`[^3]。 --- #### 题目二:最小生成树 (Minimum Spanning Tree) ##### 描述 在一个无向加权图中,求连接所有顶点且总权重最小的子集边集合。 ##### 解决方案 常用的两种算法分别是 Kruscal 算法和 Prim 算法。这里展示 Kruscal 算法的一种 C++ 实现: ```cpp #include <bits/stdc++.h> using namespace std; struct Edge { int u, v, w; }; bool cmp(const Edge &a, const Edge &b) { return a.w < b.w; } int find_set(int parent[], int x) { if(parent[x] != x){ parent[x] = find_set(parent,parent[x]); } return parent[x]; } void union_set(int parent[], int rank[], int x, int y) { int fx = find_set(parent,x); int fy = find_set(parent,y); if(fx == fy) return ; if(rank[fx]>rank[fy]){ parent[fy] = fx; }else{ parent[fx] = fy; if(rank[fx]==rank[fy]) rank[fy]++; } } int kruskal(vector<Edge> edges,int n){ sort(edges.begin(),edges.end(),cmp); int res = 0,cnt = 0; int parent[n],rank_arr[n]; for(int i=0;i<n;i++){ parent[i] = i; rank_arr[i] = 0; } for(auto e : edges){ if(find_set(parent,e.u)!=find_set(parent,e.v)){ cnt++; res +=e.w; union_set(parent,rank_arr,e.u,e.v); if(cnt==n-1) break ; } } return res; } ``` 此程序利用了并查集的思想来解决连通性和环检测问题[^4]。 --- #### 题目三:最近公共祖先 (Lowest Common Ancestor) ##### 描述 在一棵树上找到两个指定结点之间的最低共同祖先。 ##### 解决方案 可以通过深度优先搜索的方式自底向上回溯得到 LCA 结果。下面是伪代码描述过程的一部分逻辑框架: ```pseudo function lca(node, p, q): if node is null or node equals either p or q then return node let left be the recursive call to this function on the left child of 'node' let right be the same but with respect to its right subtree instead if both are non-null it means one lies in each branch so our current position must indeed represent their lowest common ancestor hence we should output that fact immediately otherwise propagate whichever answer was found upwards accordingly. ``` 实际编码时需注意边界条件处理以及性能调优等问题[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值