码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 3517 And Then There Was One(约瑟夫环-递推or模拟)

时间:2014-08-20 10:29:36      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:http   os   io   for   ar   amp   size   ef   

POJ 3517


题目: n  k m

            数字1到n成环,先叉数字m,往下数k个,直到最后只有一个数字,输出它。



链表模拟:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#define MAXN 200001
#define MOD  1000000007
#define INF  0x7fffffff
#define EPS  1e-8
#define PI acos(-1.0)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define bug(a) cout<<"bug---->"<<a<<endl;
#define FIN             freopen("datain.txt","r",stdin);
#define FOUT            freopen("dataout.txt","w",stdout);
#define mem(a,b)        memset(a,b,sizeof(a))
//#pragma comment         (linker,"/STACK:102400000,102400000")

typedef long long LL;
typedef unsigned long long ULL;
using namespace std;

struct Link{
    int data;
    Link* next;
    Link* pre;
}node[10001];

int main()
{
    int n,k,m;
    while(scanf("%d%d%d",&n,&k,&m),n||k||m)
    {
        for(int i=1;i<=n;i++)                            //构建双向循环链表
        {
            node[i].data=i;
            node[i].next=(i==n)?&node[1]:&node[i+1];
            node[i].pre=(i==1)?&node[n]:&node[i-1];
        }
        Link* p=&node[m];
        p->pre->next=p->next;
        p->next->pre=p->pre;
        p=p->next;
        int loop=k;
        int t=1;
        while(p->next!=p)
        {
            if(k%(n-t)==0)            //优化,若无会TLE
                loop=k;
            else
                loop=k%(n-t);
            for(int i=1;i<loop;i++)
                p=p->next;
            p->pre->next=p->next;
            p->next->pre=p->pre;
            p=p->next;
            t++;
        }
        printf("%d\n",p->data);

    }
    return 0;
}

递推:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<string>
#include<queue>
#define N
#define INF
#define ll __int64
#define eps 1e-12
#define PI 4.0*atan(1.0)
using namespace std;

int main()
{
    int n,m,k;
    while(~scanf("%d%d%d",&n,&k,&m))
    {
        if(n==0 && m==0 && k==0)
            break;
        int s=0;
        for(int i=2;i<=n-1;i++)
            s=(s+k)%i;
        printf("%d\n",(s+m)%n+1);
    }
    return 0;
}


POJ 3517 And Then There Was One(约瑟夫环-递推or模拟),布布扣,bubuko.com

POJ 3517 And Then There Was One(约瑟夫环-递推or模拟)

标签:http   os   io   for   ar   amp   size   ef   

原文地址:http://blog.csdn.net/code_or_code/article/details/38702275

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!