杭电 1005 Number Sequence

网上找了不少答案,都不满意,算了还是自己做吧。

Problem Description
A number sequence is defined as follows:

f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

Given A, B, and n, you are to calculate the value of f(n).
Input
The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
Output
For each test case, print the value of f(n) on a single line.
Sample Input
1 1 3
1 2 10
0 0 0
Sample Output
2
5


明显是一个类似于Fibonacci数列的递推问题。由于n很大,需要找规律才行,否则肯定超时。

由于数列中每一个数字都小于7,那么经过7*7+1=50次迭代之后,肯定会出现连续两个数重复,于是出现规律。

故此,可以建立一个长度为51的数组,数组中共有51个元素,相邻两个元素建立一个关系,共有50个关系,那么根据抽屉原理,该50个关系必然会存在重复。

我们需要寻找循环的长度。

重点:从后面找,原因在于第一个关系不一定在循环中(网上很多的例子是A=7 B=7,则 1 1 0 0 0 ...,毫无疑问, 第一个关系不在循环中)。最后一个关系一定在循环中吗?答案是肯定的。

具体是因为如果前面49个关系,不存在循环,那么第50个关系一定可以和前面49个关系产生重复。如果前面49个关系存在循环,那么第50个也会在循环中。


代码如下:

#include<iostream>
#include<fstream>
#define debug
using namespace std;
int a, b, n;
int x[51];
int main()
{
#ifdef debug
	ifstream cin("in.txt");
#endif
	x[0] = x[1] = 1;
	while (1)
	{
		cin >> a >> b >> n;
		if (a == 0 && b == 0 && n == 0)
			break;
		for (int i = 2; i < 51; ++i)
		{
			x[i] = (a*x[i - 1] + b*x[i - 2]) % 7;
		}
		if (n < 51)
			cout << x[n - 1] << endl;
		else
		{
			int xunhuan = 0;
			for (int j = 0; j <= 48; j++)
			{
				if (x[j] == x[49] && x[j + 1] == x[50])
				{
					xunhuan = 50 - j-1;
					//cout << "xunhuan" << xunhuan << endl;
					break;
				}
			}
			int index = (n - 51) % xunhuan;
			cout << x[50 - xunhuan + index] << endl;
		}
	}
#ifdef debug
	system("pause");
#endif
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值