当前位置: 首页 > news >正文

SCAU:18063 圈中的游戏

18063 圈中的游戏

时间限制:1000MS  代码长度限制:10KB
提交次数:0 通过次数:0

题型: 编程题   语言: G++;GCC;VC

Description

有n个人围成一圈,从第1个人开始报数1、2、3,每报到3的人退出圈子。编程使用链表找出最后留下的人。

输入格式

输入一个数n,1000000>=n>0 

输出格式

输出最后留下的人的编号

输入样例

3

输出样例

2

若不使用链表的第一种方法

#include <stdio.h>
#define N 1000000int main()
{int a[N], n, m=0, i=0, count=0;scanf("%d", &n);for(i=0; i<n; i++)a[i] = 0;//数组初始化0,表示在圈内的人while(count < n-1)//出去n-1个人,此循环才会结束{if(a[i] == 0){m++; //从1开始报数if(m==3){a[i] = 1;//表示此人已经出圈count++;m=0;//重置,再从1开始报数}}i++;//遍历数组元素if(i==n)//数了一圈,从头来过i=0;}i=0;while(a[i])//找到a[i]==0 的下标。 while(a[i]) 是一个条件判断语句。它的作用是检查数组 a 中索引 i 处的元素是否为真(非零)。在C语言中,数组中的元素为0被视为假,非零元素被视为真。i++;printf("%d", i+1);//注意要+1,才是圈子里的序号return 0;
}

不使用链表的第二种

#include <stdio.h>int lastRemaining(int n) 
{int i, last = 0; // 最后剩下的人的初始编号为0// 对于每一轮,i 从 2 开始,每次循环只剩下一个人时结束for (i = 2; i <= n; i++)last = (last + 3) % i; // 根据规则计算下一个要被删除的人的编号return last + 1; // 返回最后剩下的人的编号
}int main() 
{int n;scanf("%d", &n);printf("%d\n", lastRemaining(n));return 0;
}

使用链表的方法

#include <stdio.h>
#include <stdlib.h>struct Node {int data;struct Node *next;
};struct Node *createList(int n) {struct Node *head = NULL, *temp = NULL, *current = NULL;int i;for (i = 1; i <= n; i++) {temp = (struct Node *)malloc(sizeof(struct Node));temp->data = i;temp->next = NULL;if (head == NULL) {head = temp;current = temp;} else {current->next = temp;current = temp;}}current->next = head; // 将最后一个节点指向头节点,形成循环链表return head;
}int findLast(struct Node *head, int n) {struct Node *prev = NULL, *current = head;int count = 1;while (current->next != current) {if (count == 3) {prev->next = current->next;free(current);current = prev->next;count = 1;} else {prev = current;current = current->next;count++;}}int lastRemaining = current->data;free(current); // 释放最后一个节点的内存return lastRemaining;
}int main() {int n;scanf("%d", &n);struct Node *head = createList(n);int lastRemaining = findLast(head, n);printf("%d\n", lastRemaining);return 0;
}

http://www.lryc.cn/news/264560.html

相关文章:

  • .NET Core中鉴权 Authentication Authorization
  • PyTorch深度学习实战(26)——卷积自编码器(Convolutional Autoencoder)
  • Milvus实战:构建QA系统及推荐系统
  • 使用Docker部署Nexus Maven私有仓库并结合Cpolar实现远程访问
  • GEE-Sentinel-2月度时间序列数据合成并导出
  • 【深度学习】语言模型与注意力机制以及Bert实战指引之二
  • 计算机网络 网络层下 | IPv6 路由选择协议,P多播,虚拟专用网络VPN,MPLS多协议标签
  • 【MATLAB第83期】基于MATLAB的LSTM代理模型的SOBOL全局敏感性运用
  • 求奇数的和 C语言xdoj147
  • 全链路压力测试:解析其主要特点
  • 算法基础之约数个数
  • 【ECharts】折线图
  • java jdbc连接池
  • unity2d 关闭全局重力
  • 大数据时代,如何基于机密虚拟化技术构建数据安全的“基石”
  • 为你自己学laravel - 15 - model的更新和删除
  • 列举mfc140u.dll丢失的解决方法,常见的mfc140u.dll问题
  • 智能优化算法应用:基于野狗算法3D无线传感器网络(WSN)覆盖优化 - 附代码
  • DC-8靶场
  • SQL Server 安装教程
  • 快猫视频模板源码定制开发 苹果CMS 可打包成双端APP
  • 【C++】理解string类的核心理念(实现一个自己的string类)
  • conda 虚拟环境使用
  • C# 使用MSTest进行单元测试
  • 基于Java (spring-boot)的宠物管理系统
  • 基于博弈树的开源五子棋AI教程[1 位棋盘]
  • Java Catching and Handling Exceptions(二)
  • 【HarmonyOS开发】ArkTs关系型和非关系型数据库的存储封装
  • Latex编译出来的pdf文件缺少参考文献和交叉引用
  • sql_lab靶场搭建以及存在的一些问题