POJ1995 Raising Modulo Numbers
Description
People are different. Some secretly read magazines full of interesting girls’ pictures, others create an A-bomb in their cellar, others like using Windows, and some like difficult mathematical games. Latest marketing research shows, that this market segment was so far underestimated and that there is lack of such games. This kind of game was thus included into the KOKODáKH. The rules follow:
Each player chooses two numbers
You should write a program that calculates the result and is able to find out who won the game.
每个人都是不同的。有人偷偷阅读那些满是漂亮女孩照片的杂志,有人则在地下室制造原子弹,还有人喜欢使用 Windows 系统,而有些人则热衷于解复杂的数学游戏。最新的市场调查显示,这一细分市场至今一直被低估,且此类游戏十分匮乏。因此,这类游戏被纳入了 KOKODáKH 之中。游戏规则如下:
每位玩家选择两个数字和 ,并将它们写在一张纸上。其他玩家无法看到这些数字。在指定时间点,所有玩家同时将自己的数字展示给其他人。目标是要算出包括自己在内的所有玩家所对应的表达式 之和,并求出该总和除以某个固定数 M 后的余数。最先算出正确结果的人即为胜者。根据玩家的体验,通过选择更大的数字可以提高游戏的难度。
你需要编写一个程序来计算结果,并判断谁是游戏的赢家。
Input
The input consists of Z assignments. The number of them is given by the single positive integer Z appearing on the first line of input. Then the assignements follow. Each assignement begins with line containing an integer M (
输入包含 Z 个分配任务。其数量由输入第一行给出的正整数 Z 决定。随后便是这些分配任务的具体内容。每个任务的第一行会给出一个整数 M(
),总和需要被这个数除。下一行会给出玩家数量 H( )。紧接着会有 H 行数据,每行包含两个用空格分隔的数字 和 ,且这两个数字不能同时为零。
Output
For each assingnement there is the only one line of output. On this line, there is a number, the result of expression
对于每个任务,仅输出一行结果。这一行包含一个数字,即表达式的计算结果。
Sample Input
1 | 3 |
Sample Output
1 | 2 |
Limit
| Time Limit | Memory Limit |
|---|---|
| 1000MS | 30000K |
Analysis
朴素地,按照题目描述实现计算:
1 |
|
会发现 TLE 了,如何优化运行时间呢?分析核心代码:
1 | while(h--) { |
时间复杂度为
故总的时间复杂度为
Algorithm
快速幂可从二进制展开理解,若:
则:
每个
那么算法实现从指数的最低位开始处理:
1 | while(b) { |
这里,t 表示当前对应的幂b & 1 检查当前最低位是否为t 乘入 res。之后将 t 平方以得到下一位对应的幂,再右移 b,处理下一位。每次乘法后取模不会改变最终余数,因此可以避免中间结果不断变大。
指数每轮右移一位,循环次数等于
那本题可以这样实现:
1 |
|
res = 1ll % p是为了在时,初值为 ,并能正确处理 。
Template
1 | template <class T> |
power()要求、 。
Ref
- Title: POJ1995 Raising Modulo Numbers
- Author: Neurocoda
- Created at : 2026-09-26 11:05:27
- Updated at : 2026-09-26 13:34:06
- Link: https://neurocoda.com/p/dbf08e00.html
- License: This work is licensed under CC BY-ND 4.0.