Description
火车从始发站(称为第1站)开出,在始发站上车的人数为a,然后到达第2站,在第2站有人上、下车,但上、下车的人数相同,因此在第2站开出时(即在到达第3站之前)车上的人数保持为a人。从第3站起(包括第3站)上、下车的人数有一定规律:上车的人数都是前两站上车人数之和,而下车人数等于上一站上车人数,一直到终点站的前一站(第n-1站),都满足此规律。
现给出的条件是:共有N个车站,始发站上车的人数为a,最后一站下车的人数是m(全部下车)。试问x站开出时车上的人数是多少?
若无解则输出“No answer.”
包含多组测试数据,每组测试数据占一行,包括a,n,m和x四个数,其中0<=a,m<=100000<n,x<=20
Output
每组测试数据占一行,输出一个数x,即站开出时车上的人数。
Sample Output
Solution
本质其实就是斐波那契数列,由于每次上下车人数的计算方式不同,我选择开两个数组stops_up和stops_down,前者用来存上车人数,后者用来存下车人数;
上车人数的递推式为 stops_up[j] = stops_up[j - 1] + stops_up[j - 2];
下车人数的递推式为stops_down[j] = stops_up[j-1];
由于这道题是只知道最后的下车人数但是不知道第二次的上下车人数,我决定用暴力一个个搜,即把每一种第二次上车人数的情况都给枚举出来,然后把第n-1站的人数与m比对(第m站是所有人都下车,所以m == 第n-1站开出时车上的人数),如果相等则输出第x站开出时车上人数,否则无解;
下面是代码:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 
 | #include <iostream>#include <cstdio>
 #include <cmath>
 #include <cstring>
 #include <string>
 #include <algorithm>
 #include <stack>
 #include <queue>
 #include <map>
 
 #define MAX 10001
 #define ll long long int
 #define scf(a) scanf("%d", &a)
 #define mms(a) memset(a, 0, sizeof(a))
 
 using namespace std;
 
 int start, n, m, x;
 int stops_up[MAX], stops_down[MAX];
 
 int main()
 {
 while (cin >> start >> n >> m >> x)
 {
 int judge = 0;
 
 stops_up[0] = start;
 stops_down[0] = 0;
 for (int i = 0; i < MAX; i++)
 {
 int summ = start, sumx = start;
 
 stops_up[1] = i;
 stops_down[1] = i;
 for (int j = 2; j < n - 1; j++)
 {
 stops_up[j] = stops_up[j - 1] + stops_up[j - 2];
 stops_down[j] = stops_up[j - 1];
 summ += stops_up[j] - stops_down[j];
 
 if (j == x - 1)
 sumx = summ;
 }
 
 if (summ == m)
 {
 judge = 1;
 cout << sumx << endl;
 break;
 }
 }
 
 if (!judge)
 cout << "No answer." << endl;
 }
 
 return 0;
 }
 
 |