向量表解决约瑟夫问题

向量表定义

vector.h

#ifndef VECTOR_H
#define VECTOR_H
#include<iostream>
using namespace std;
//向量表
template <class T>
class Vector
{
	private:
		T *elements;//数组
		int ArraySize,VectorLength;
		void GetArray();//分配空间用
	public:
		Vector(int Size=0);//构造函数
		~Vector(){delete []elements;}
		int GetLenght() const
		{
			return VectorLength;
		}
		T GetNode(int i)//取向量中第i个节点的值
		{
			return (i<0||i>=VectorLength)?NULL:elements[i];

		}
		int Find(T& x)//查找值为x的结点
		{
			for(int i=0;i<VectorLength;i++)
				if(elements[i]==x) return i;
				return -1;
		}

		bool Insert(T& x,int i);//插入
		bool Remove(int i);//删除

};
template <class T>
void Vector<T>::GetArray()
{
	elements=new T[ArraySize];
	if(elements==0)
		cerr<<"Memory Allocation Error!"<<endl;
}

template <class T>
Vector<T>::Vector(int sz)//构造函数
{
	if(sz<=0)
		cerr<<"Invaild Array Size!"<<endl;
	else
	{
		ArraySize=sz;
		VectorLength=0;
		GetArray();
	}
}

template <class T>
bool Vector<T>::Insert(T& x,int i)//实现结点插入
{
	if(VectorLength==ArraySize)
	{
		cerr<<"overflow"<<endl;
		return false;
	}
	else if(i<0||i>VectorLength)
	{
		cerr<<"Insert position error!"<<endl;
		return false;
	}
	else
	{
		for(int j=VectorLength-1;j>=i;j--)
			elements[j+1]=elements[j];//后移
		elements[i]=x;//插入
		VectorLength++;
		return true;
	}
}

template <class T>
bool Vector<T>::Remove(int i)//删除结点
{
	if(VectorLength==0)
	{
		cerr<<"Verctor is Empty!"<<endl;
		return false;
	}
	else if(i<0||i>VectorLength-1)
	{
		cerr<<"Remove position error!"<<endl;
		return false;
	}
	else
	{
		for(int j=i;j<VectorLength-1;j++)
			elements[j]=elements[j+1];//前移
		VectorLength--;
		return true;
	}

}

#endif

//向量(线性表)解决约瑟夫问题
#include<iostream>
#include"Vector.h"
using namespace std;

void Josephus(Vector<int> &P,int n,int s,int m)//n个人从第s个人报数,直到报数为m的出列
{

	int k=1;
	for(int i=0;i<n;i++)
	{P.Insert(k,i);k++;}
	int s1=s;
	for(int j=n;j>=1;j--)
	{
		s1=(s1+m-1)%j;
		if(s1==0)
			s1=j;
		int w=P.GetNode(s1-1);
		P.Remove(s1-1);//找到后先删除,再插入到尾部
		P.Insert(w,n-1);
	}
}
int main()
{
	Vector<int> a(13);
	Josephus(a,13,1,3);//13个人从1开始报数,报数到3的出列
	for(int i=0;i<13;i++)
		cout<<a.GetNode(i)<<endl;//输出的是每个人原来的序号
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值