zoukankan      html  css  js  c++  java
  • hdu 4841 用stl::vector解决约瑟夫问题

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4841

    约瑟夫问题,确定一个数m,共有n个人,循环报数,数到m就出队,后面的数跟在其后,这是一个典型的链表删除操作的应用,我先用vector写了一中操作方案,vector对于随机访问元素的时间复杂度是O(1),所以便于查询,而链表对于插入和删除的时间复杂度都是O(1),用vector进行删除操作的时间复杂度是O(n)的,用于后续元素的移位。

    代码如下:

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 typedef unsigned int ui;
     4 typedef long long ll;
     5 typedef unsigned long long ull;
     6 #define pf printf
     7 #define mem(a,b) memset(a,b,sizeof(a))
     8 #define prime1 1e9+7
     9 #define prime2 1e9+9
    10 #define pi 3.14159265
    11 #define lson l,mid,rt<<1
    12 #define rson mid+1,r,rt<<1|1
    13 #define scand(x) scanf("%llf",&x) 
    14 #define f(i,a,b) for(int i=a;i<=b;i++)
    15 #define scan(a) scanf("%d",&a)
    16 #define mp(a,b) make_pair((a),(b))
    17 #define P pair<int,int>
    18 #define dbg(args) cout<<#args<<":"<<args<<endl;
    19 #define inf 0x7ffffff
    20 inline int read(){
    21     int ans=0,w=1;
    22     char ch=getchar();
    23     while(!isdigit(ch)){if(ch=='-')w=-1;ch=getchar();}
    24     while(isdigit(ch))ans=(ans<<3)+(ans<<1)+ch-'0',ch=getchar();
    25     return ans*w;
    26 }
    27 int n,m,t;
    28 const int maxn=1e4+10;
    29 vector<int>v ;
    30 int main()
    31 {
    32     //freopen("input.txt","r",stdin);
    33     //freopen("output.txt","w",stdout);
    34     std::ios::sync_with_stdio(false);
    35     int t=0; 
    36     while(scanf("%d%d",&n,&m)!=EOF)
    37     {
    38         t++;
    39         v.clear();
    40         f(i,0,2*n-1)v.push_back(i);//保存的是位置信息,最终将确定剩余的n个位置 
    41         int pos=0;
    42         f(i,1,n)//删除n次 
    43         {
    44             pos=(pos+m-1)%((int)v.size());// 从当前位置(pos+0)位置开始,直到pos+m-1位置
    45             v.erase(v.begin()+pos); 
    46         }
    47         int j=0;
    48         f(i,0,2*n-1)
    49         {
    50             if(!(i%50)&&i)pf("
    ");//每五十个字符一行 
    51                 if(j<v.size()&&v[j]==i)
    52                 {
    53                     pf("G");
    54                     j++;
    55                 }
    56                 else pf("B");    
    57         }
    58         pf("
    
    ");
    59     }
    60 } 
    每一个不曾起舞的日子,都是对生命的辜负。
  • 相关阅读:
    密码由6-12位数字或字母组成,密码哈希加密
    获得一个字符串的汉语拼音码
    WPF中ComboBox绑定数据库自动读取产生数据
    SQL存储过程生成顺序编码
    SQL 语句调用这个存储过程,生成顺序编码
    restful(1):序列化
    Django的CBV和FBV
    权限管理组件:rbac
    ModelForm组件和forms组件补充
    BBS+Blog项目代码
  • 原文地址:https://www.cnblogs.com/randy-lo/p/12609097.html
Copyright © 2011-2022 走看看