zoukankan      html  css  js  c++  java
  • 洛谷——线性数据结构P1996 约瑟夫问题

    2019-11-24

    10:04:17

     解法1:

     O(N平方)复杂度

    #include<bits/stdc++.h>
    #include <stdlib.h>
    #include <stdio.h>
    using namespace std;
    int main(){
        int n,m,s=0;
        bool visited[201] = {0};
        cin>>n>>m;
        for(int k=0;k<n;++k){//总共要出队N次 
            for(int i=0;i<m;++i){//类似取余操作 
                if((++s)>n) s = 1;
                if(visited[s]) i--;//当访问已经出过队的元素时,此次访问无效,i--,要访问下一个元素 
            }
            printf("%d ",s);
            visited[s] = true;
        } 
        system("pause");
        return 0;
    } 

    解法2:利用queue队列

     同样是O(N平方)但是比上一个解法更快,因为这个算法是不访问已经出队了的元素的。而上个解法中是需要判断该元素是否已经出队

    #include<bits/stdc++.h>
    #include <stdlib.h>
    #include <stdio.h>
    using namespace std;
    int main(){
        int tot,outNum,nowNum = 1;
        queue<int> q;
        cin>>tot>>outNum;
        for(int i=1;i<=tot;++i) q.push(i);
        while(!q.empty()){
            if(nowNum == outNum){
                cout<< q.front() << " ";
                q.pop();
                nowNum = 1;
            }
            else{
                nowNum++;
                q.push(q.front());
                q.pop();
            }
        }
        cout << endl;
        system("pause");
        return 0;
    } 

     解法3:

     利用vector实现队列

    #include<bits/stdc++.h>
    #include <stdlib.h>
    #include <stdio.h>
    using namespace std;
    vector<int> v; 
    int main(){
        int n,m;
        scanf("%d%d",&n,&m);
        if(n==0&&m==0) return 0;
        for(int i=1;i<=n;++i) v.push_back(i);
        int vz = 1;
        while(!v.empty()){
            if(vz == m){
                cout<<v.front()<<" ";
                v.erase(v.begin());
                vz = 1;
            }
            else{
                vz++;
                v.push_back(v.front());
                v.erase(v.begin());
            }
        }
        cout<<endl;
        system("pause");
        return 0;
    } 

  • 相关阅读:
    第一阶段冲刺(第六天)
    第一阶段冲刺(第五天)
    第一阶段冲刺(第四天)
    第一阶段冲刺(第三天)
    第一阶段冲刺(第二天)
    个人学习进度(第十一周)
    第一阶段冲刺(第一天)
    个人学习进度(第十周)
    个人学习进度(第九周)
    php面向对象说明
  • 原文地址:https://www.cnblogs.com/JasonPeng1/p/11921490.html
Copyright © 2011-2022 走看看