Last Switched Off
National Olympiad — Municipal round (2009 season)
Submission name: last.cpp
Problem summary
Visit regions cyclically starting at 1 and adding a fixed positive step m modulo N. Every region must eventually be visited. Choose the smallest m that makes the given special region appear as late as possible in the first cycle.
Input
N and the special region number s.
Output
The smallest suitable positive step m.
Constraints
1 < N < 1000; 1 ≤ s ≤ N.
Worked example
An independently prepared example for this explanation.
Input
5 4
Output
2
Solution analysis
- A step visits all regions exactly when gcd(m,N)=1. Steps with the same residue modulo N have the same order, so it is sufficient to inspect 1 through N−1.
- For each valid step simulate the N visits, starting at position 0 (region 1). Record the index at which position s−1 is reached. Maximize that index and keep the first step on ties.
- For N=5 and s=4, step 2 visits 1,3,5,2,4. The special region is last, so no step can improve its time, and 2 is the smallest step achieving it.
Why it works
The order generated by addition modulo N has length N/gcd(m,N). Thus exactly the coprime steps are eligible. Enumeration examines every distinct eligible order and compares the exact visit time, selecting the maximum and then its smallest step.
Watch out. This is a fixed cyclic traversal: regions are not removed as in the Josephus problem. Region 1 always appears first.
Commented C++17 solution
An independently written complete program with standard headers.
#include<iostream>
#include<numeric>
using namespace std;
int main(){
// Compute the exact archive answer using the method explained above.
int n,special;
cin>>n>>special;
int answer=1;
int latest=-1;
for(int step=1;step<n;step++){
if(gcd(step,n)!=1){
continue;
}
int position=0;
for(int time=0;time<n;time++){
if(position==special-1&&time>latest){
latest=time;
answer=step;
}
position=(position+step)%n;
}
}
cout<<answer<<'\n';
}