您的位置:首页 > 理论基础 > 数据结构算法

数据结构和算法分析实验(一)

2008-11-05 22:28 495 查看
#include "stdafx.h"

// listttt.cpp : Defines the entry point for the console application.
//这就是击鼓传花游戏,输者出局,从下家续传。但传递次数确定

/*This is a standard programming project. The algorithm can be sped up by setting M =M mod N,
so that the hot potato never goes around the circle more than once. If M >N/2, the potato should
be passed in the reverse direction. This requires a doubly linked list. The worst case running time
is clearly O(N min(M, N)), although when the heuristics are used, and M and N are comparable,
the algorithm might be significantly faster. If M = 1, the algorithm is clearly linear.**/
#include <iostream>
#include <list>
using namespace std;
int main()
{

int i,j, n, m, mPrime, numLeft;
list <int > L;
list<int>::iterator iter;
//Initialization
cout<<"enter N (# of people) & M (# of passes before elimination):";
cin>>n>>m;
numLeft = n;//剩下的人数

mPrime = m % n;//有效的增进,例如三个人,前进5次,实际只前进了2次
for (i =1 ; i <= n; i++)
L.push_back(i);//向表中加人
iter = L.begin();
// Pass the potato//找输家,每次淘汰一个
for (i = 0; i < n; i++)
{
mPrime = mPrime % numLeft;//更新有效增进
if (mPrime <= numLeft/2) // 少于一半向前传pass forward
for (j = 0; j < mPrime; j++)
{
iter++;
if (iter == L.end())
iter = L.begin();//从头开始

}
else // pass backward 多于一半
for (j = 0; j < numLeft-mPrime; j++)
{
if (iter == L.begin())
iter = --L.end();//从头开始
else
iter--;
}
cout<<*iter<<" ";//淘汰者编号会逐个输出
iter= L.erase(iter);//删除拿花的人
if (iter == L.end())
iter = L.begin();
}
cout<<endl;
return 0;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: