猴子选王-链表水题

来源:互联网 发布:未来java的发展前景 编辑:程序博客网 时间:2024/05/05 19:03
#include<iostream>#include <fstream>using namespace std;struct NodeT{    int n;    NodeT *next,*front;};NodeT* kill(NodeT *p,int Kn){    //从给你的指针位置开始数1 ,一直数到 Kn    //把那个人杀掉,并且返回被杀掉的后一个人的指针。    NodeT *pre=p;    for(int i=2;i<=Kn;i++)    {        p=p->next;    }    pre= p->front;    pre->next=p->next;    (p->next)->front=pre;    //cout<<"who was killed :"<<p->n<<" ";    delete p;    return pre->next;}int main(){    int m,Kn,count;    cin>>m;    NodeT *head,*p,*pre;    head= new NodeT;    head->n=1;    p=head;    for(int i=2;i<=m;i++)    {        pre=p;        p->next=new NodeT;        p=p->next;        p->front=pre;        p->n=i;    }    p->next=head;    head->front=p;    p=head;    p=head;    count=m;    for(int i=1;i<=m-1;i++)    {        cin>>Kn;        if(Kn%count==0)Kn=count;        else{Kn=Kn%count;}        count--;        p= kill(p,Kn);    }    cout<<p->n<<endl;}
顺便来一发同学的代码
<pre name="code" class="cpp">#include <iostream>using namespace std;int main(){    int m;    cin >> m;    int a[m - 1];    for (int i = 0;i < m - 1;++i){        cin >> a[i];    }    int catch_,result = 1;    for (int i = 0;i < m - 1;++i){        catch_ = a[m - 2 - i] % (i + 2);        if (catch_ == 0){catch_ = i + 2;}        result = result + catch_;        if (result > i + 2){result -= i + 2;}    }    cout << result;    return 0;}



0 0