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

本文介绍了一个基于C++的击鼓传花游戏程序实现。通过双向链表模拟玩家的圈形排列,并采用高效的算法来确定每轮出局的玩家。程序能够根据玩家数量和传递次数动态调整游戏流程,确保游戏过程的公平性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值