#include \n#include \nusing namespace std;\nint main(){\n\tint n,k;\n\tcin>>n>>k;\n\tvector people(n);\n\tvector res;\n\tint count=0;\n\tint index=0;\n\tfor(int i=0;i<n;i++){\n\t people[i]=i+1;\n\t}\n\twhile(!people.empty()){\n\t count++;\n\t index=(index+1)%people.size();\n\t if(count==k){\n\t res.push_back(people[index-1]);\n\t people.erase(people.begin()+index-1);\n\t count=0;\n\t index--;\n\t }\n\n\t}\n\tfor(int i=0;i<res.size();i++){\n\t cout<<res[i]<<" ";\n\t}\n\tcout<< endl;\n\treturn 0;\n}\nThis code, when input 5, 3, will output 3 1 201352398 2 4. This is because after deleting the element, the value of index is not updated. After deleting an element, the elements originally after it move forward one position, but the value of index does not update accordingly, causing the next loop to point to the wrong position. To solve this problem, you can update the value of index to index-1 after deleting the element. The modified code is as follows:\n\ncpp\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.

C++ Josephus Problem: Fixing Index Error for Accurate Output

原文地址: https://www.cveoy.top/t/topic/pzvR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录