约瑟夫环的线段树解法

 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 }



posted @ 2011-12-27 08:53  Richard Zhong  阅读(444)  评论(0编辑  收藏  举报