Written by Josephus just learning stl

Just learned of c ++ STL, by traversing the vector of the elements that were removed, write implementation Josephus

First title and code stickers out, and then we slowly analysis

Title Description

Descriptionn child sitting in a circle, clockwise press numbered 1,2, ..., n, the number p of the number of packets sequentially in the clockwise children, the report 1 m, when the report m, the child out of the circle and then the next message from a number, and then go out when the report m. So again, until all the children are out of the circle. Press out the order output child number.
Input lines are each an integer of three separated by spaces, the first one is n, the second is p, the third is m (0 <m, n < 300). The last line is:

0 0 0
the Output the sequence number of the output circle, the interval between a number comma

The Input the Sample
8 4 3
0 0 0
the Sample the Output
6,2,7,4,3,5,1,8
error code (to be further studied the wrong reasons)

#include<vector>
#include<iostream>
using namespace std;
int main() {

 int I = 1;//信标
 vector<int>v;
 int n, m;
 cin >> n >> m;
 for (int i = 0; i <= n; i++) {
  v.push_back(i);//把环做出来,0是为了占用一个空间,以便于size运算不加一
 }
 cout << "被删除的元素是: " << v[I] << endl;//调试
  v.erase(v.begin() + I);
 }
 cout << "The last one is " << v[1] << endl;
 return 0;

AC code is as follows

#include<vector>
#include<iostream>
#include<cstdio>
using namespace std;
int main() {
	int I ;//信标
	vector<int>v;
	int n, m;
	while (cin >> n >> I >> m) {
		if (n == m && m == I && m == 0)
			break;
		for (int i = 0; i <= n; i++) {
			v.push_back(i);//用0堵住0号元素
		}
		int N = n;
		while (N--) {//删除n个元素
			int i;
			int temp = v.size() - 1;//时刻在变
			//cout << "temp:" << temp << endl;
			I %= temp;//完善一下,保证I的取值是【1,temp】
			if (!I)
				I = temp;
			for (i = 0; i < (m - 1); i++) {//如果起点不是1,这里还是需要完善
				I++;
				if (I > temp) {
					I -= temp;
				}
			}
			/*cout << "当前的I值为" << I << endl;
			cout << "当前size为" << v.size() << endl;
			cout << "被删除的元素是: " << v[I] << endl;*/
			if (v.size() - 1 == n)
				cout << v[I];
			else
				cout << "," << v[I];
			v.erase(v.begin() + I);
		}
		cout << endl;
		v.clear();
	}
	return 0;

}
Published an original article · won praise 0 · Views 21

Guess you like

Origin blog.csdn.net/sdibt_xhx/article/details/104737754