[CCF CSP]201712-2 游戏

约瑟夫环问题,问最后一个剩下的是谁。
由于末位是4也要淘汰,所以只可模拟得到结果

#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
const int INF=0x3f3f3f3f;
int a[N];
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int n,k,ans;
    cin>>n>>k;
    int cnt=n,x=1,num=0;
    while(1)
    {
        while(a[x]) {
            x++;
            if(x==n+1) x=1;
        }
        if(cnt==1) {
            ans=x;break;
        }
        num++;
        //cout<<num<<' '<<x<<endl;
        if(num%10==k || num%k==0)
        {
            //cout<<"Y"<<endl;
            a[x]=1;
            cnt--;
        }
        x++;
        if(x==n+1) x=1;
    }
    cout<<ans<<endl;
    return 0;
}

还有一个直接计算结果的方法,只用于数到k时淘汰的游戏:

#include<bits/stdc++.h>
using namespace std;
const int N = 1005;
const int INF=0x3f3f3f3f;
int a[N];
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int n,k;
    cin>>n>>k;
    a[1]=0;
    for(int i=2;i<=n;i++)
    {
        a[i]=(a[i-1]+k)%i;
        //cout<<i<<' '<<a[i]<<endl;
    }
    int ans=a[n]+1;
    cout<<ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/Andrew-aq/p/12518444.html