向量表解决约瑟夫问题
来源:互联网 发布:数据库分布式 编辑:程序博客网 时间:2024/05/16 05:22
向量表定义
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;}
- 向量表解决约瑟夫问题
- arm 异常向量表(中断向量表)问题的扩展
- java 解决约瑟夫问题
- 约瑟夫问题Java解决
- 解决约瑟夫问题
- php解决约瑟夫问题
- JAVA解决约瑟夫问题
- 约瑟夫问题的解决
- 三星cpu s3c2440 的中断向量表问题
- STM32L4xx下bootloader重设中断向量表的一个问题
- 浅析中断向量表
- 中断向量表
- 中断向量表
- 中断向量表
- 中断向量表
- 中断向量表
- 中断向量表
- 中断向量表
- Android布局文件中的各种属性
- 任务计划运行失败,显示“登录失败”
- HFileInputFormat实现
- Qt学习之路(43): QDirModel
- Extjs GridPanel使用攻略简单教程
- 向量表解决约瑟夫问题
- JS操作COOKIE
- shell学习1
- linux命令之cat
- fsockopen与pfsockopen的区别
- Flash Player 11 Stage3D学习大杂烩
- 编写安全代码——不要用memcmp比较structure
- 应用程序Framework源码级别调试
- 【转】单例模式完全剖析