C++ Josephus Problem: Fixing Index Error for Accurate Output
#include cpp\n#include <iostream>\n#include <vector>\nusing namespace std;\nint main(){\n int n,k;\n cin>>n>>k;\n vector<int> people(n);\n vector<int> res;\n int count=0;\n int index=0;\n for(int i=0;i<n;i++){\n people[i]=i+1;\n }\n while(!people.empty()){\n count++;\n index=(index+1)%people.size();\n if(count==k){\n res.push_back(people[index]);\n people.erase(people.begin()+index);\n count=0;\n index--;\n }\n\n }\n for(int i=0;i<res.size();i++){\n cout<<res[i]<<" ";\n }\n cout<< endl;\n return 0;\n}\n\nAfter this modification, the output will be correct when inputting 5 and 3, which is 3 1 5 2 4.
原文地址: https://www.cveoy.top/t/topic/pzvR 著作权归作者所有。请勿转载和采集!