zoukankan      html  css  js  c++  java
  • 约瑟夫环的线段树解法

     1 #include <iostream>
    2
    3 using std::set;
    4 using std::cout;
    5 using std::endl;
    6 #define NODENUM 5000
    7
    8 struct Node{
    9 int low;
    10 int high;
    11 int subNodeNum;
    12 };
    13
    14 Node node_array[NODENUM];
    15
    16 void build(int l, int r, int root_index)
    17 {
    18 Node tmpNode;
    19 tmpNode.low = l;
    20 tmpNode.high = r;
    21 if(l == r){
    22 tmpNode.subNodeNum = 1;
    23 node_array[root_index] = tmpNode;
    24 return;
    25 }
    26 int m = (l+r)/2;
    27 build(l, m, root_index*2);
    28 build(m+1, r, root_index*2+1);
    29 tmpNode.subNodeNum = node_array[root_index*2].subNodeNum + node_array[root_index*2+1].subNodeNum;
    30 node_array[root_index] = tmpNode;
    31 }
    32
    33 int findPos(int pos, int root_index)
    34 {
    35 node_array[root_index].subNodeNum--;
    36 if(node_array[root_index].low == node_array[root_index].high){
    37 node_array[root_index].subNodeNum = 0;
    38 return node_array[root_index].low;
    39 }
    40 if(pos <= node_array[root_index*2].subNodeNum) return findPos(pos, root_index*2);
    41 else return findPos(pos-node_array[root_index*2].subNodeNum, root_index*2+1);
    42 }
    43
    44 int main()
    45 {
    46 build(1, 7, 1);
    47 int pos = 1;
    48 for(int i=1; i<=7; ++i){
    49 pos = (pos + 3-1) % node_array[1].subNodeNum;
    50 if(pos == 0) pos = node_array[1].subNodeNum;
    51 int ppos = findPos(pos, 1);
    52 cout<<ppos<<endl;
    53 }
    54 }



  • 相关阅读:
    django初识
    django前奏
    前端之bootstrap
    前端之jQuery
    前端基础之BOM和DOM操作
    前端之js
    前端之css(二)
    前端之css(一)
    html之form表单
    前端之html
  • 原文地址:https://www.cnblogs.com/zjfdlut/p/2302975.html
Copyright © 2011-2022 走看看