zoukankan      html  css  js  c++  java
  • 约瑟夫环的两种实现

     

    方法一:用一个数组存放每个元素,再用一个bool数组存放每个元素是否还在那个队列中。每次出列一个元素,将其对应的那个bool值置为false。循环输出第m个元素直到只剩下一个元素在队列中。不过这个时间复杂度比较高。

     

    #include<iostream>
    using namespace std;
    //时间复杂度高的方法
    #define MAX_LENGTH 50
    int data[MAX_LENGTH];
    bool isInQueue[MAX_LENGTH];
    void main()
    {
    	int num;  //每次数的个数
    	cin>>num;
    
    	int temp;
    	int currentCount=0;
    	while(cin>>temp)//初始化队列
    	{
    		if(currentCount<MAX_LENGTH)
    		{
    			data[currentCount]=temp;
    			isInQueue[currentCount++]=true;
    		}
    		else
    			break;
    	}
    	
    
    
    	int count=currentCount;//记录当前队列中的元素个数
    	int start=0;//每次开始数数的第一个位置
    	while(count>1)
    	{
    		int i=start;//每次数数的迭代
    		int j=0;
    		int out=0;
    		for(i;i<currentCount;i=(i+1)%currentCount)
    		{
    			if(isInQueue[i])
    				++j;
    			if(j==num)
    			{
    				out=i;
    				cout<<data[out]<<" ";
    				isInQueue[out]=false;
    				--count;
    				while(!isInQueue[out])
    					out=(out+1)%currentCount;// 找到下个开始数数的位置
    				start=out;
    				break;
    			}
    
    		}
    	}
    	cout<<data[start]<<endl;//数出剩下的那个数
    }


     

    方法二:空间换时间,每个元素封装成一个结构体。因为链表的特殊性,方便我们删除操作和逐个快速遍历。

     

    #include<iostream>
    using namespace std;
    //空间换时间的方法
    struct Node
    {
    	Node(int v,Node* n=NULL):value(v),next(n){}
    	int value;
    	Node* next;
    };
    
    Node* initList()//建立链表,记录每个元素
    {
    	Node* head=NULL;
    	Node* rear=NULL;
    	int temp;
    	while(cin>>temp)
    	{
    		if(!head)
    		{
    			head=new Node(temp);
    			rear=head;
    		}
    		else
    		{
    			Node* node=new Node(temp,head);
    			rear->next=node;
    			node->next=head;
    			rear=node;
    		}		
    	}
    	return head;
    }
    
    void outQueue(Node* head,int num)//出队列
    {
    	int i=0;
    	Node* last=NULL;
    	Node* temp=head;
    	while(temp!=temp->next)
    	{
    		++i;
    		if(i==num)
    		{
    			cout<<temp->value<<" ";
    			i=0;
    			last->next=temp->next;
    			delete temp;
    			temp=last->next;
    		}
    		else
    		{
    			last=temp;
    			temp=temp->next;
    		}
    		
    	}
    	cout<<temp->value<<endl;
    	if(temp==head)
    		cout<<"yiyang";
    }
    void main()
    {
    	int num;
    	cin>>num;
    	Node* pHead=initList();
    	outQueue(pHead,num);
    }
    


  • 相关阅读:
    Mac 终端命令使用自动补全时忽略大小写设置
    Android App专项测试
    评估产品机会
    如何快速获取ListView的打气筒对象
    js处理日期格式yyyy-MM-dd hh:mm:ss
    websocket聊天时,图片压缩处理(url或者input-file)
    canvas图片压缩,局部放大,像素处理
    vscode 右键文件或者文件夹显示菜单
    HTML5-SQLLite连接
    ie下div模拟的表格,表头表体无法对齐
  • 原文地址:https://www.cnblogs.com/pangblog/p/3327321.html
Copyright © 2011-2022 走看看