• 【洛谷P1996】约瑟夫问题


    约瑟夫问题

    链表模拟大概是正解

     1 #include<iostream>
     2 using namespace std;
     3 struct node{      //单链表
     4     int d;
     5     node *next;
     6 };
     7 int n,m;
     8 node *head,*p,*r;
     9 int main()
    10 {
    11     int i,j;
    12     cin>>n>>m;
    13     head=new node;
    14     head->next=NULL;
    15     head->d=1;
    16     r=head;
    17     for(i=2;i<=n;i++)  //插入1~n
    18     {
    19         p=new node;
    20         p->d=i;
    21         p->next=NULL;
    22         r->next=p;
    23         r=p;
    24     }
    25     r->next=head;    //循环链表
    26     p=r;
    27     for(i=1;i<=n;i++)  //模拟
    28     {
    29         for(j=1;j<m;j++) p=p->next;
    30         cout<<p->next->d<<' ';
    31         p->next=p->next->next;  //删去节点p->next
    32     }
    33     cout<<endl;
    34     return 0;
    35 }

    用数组乱搞:

     1 #include<iostream>
     2 #include<cstdio>
     3 using namespace std;
     4 int n,m,a[105],s,t=0,p;
     5 int main()
     6 {
     7     scanf("%d%d",&n,&m);
     8     while(s!=n)  //s记录已经删去的人数
     9     {
    10         if(p==m)  //数到m个人
    11         {
    12             a[t]=1;  //记录已经删去
    13             p=0;    //清空已经数的人数
    14             cout<<t<<' ';
    15             s++;
    16         }
    17         t=t%n+1;  
    18         if(!a[t]) p++;
    19     }
    20     return 0;
    21 }     
    22         
  • 相关阅读:
    2017-12 CDQZ集训(已完结)
    BZOJ1492 货币兑换 CDQ分治优化DP
    BZOJ2001 [Hnoi2010]City 城市建设 CDQ分治
    树套树小结
    跑路了
    NOI2020 游记
    半平面交模板
    Luogu 3245 大数
    Luogu 3246 序列
    test20190408(十二省联考)
  • 原文地址:https://www.cnblogs.com/yjkhhh/p/8496270.html
Copyright © 2020-2023  润新知