UVa 997 - Show the Sequence

contents

  1. 1. Input
  2. 2. Output
  3. 3. Sample Input
  4. 4. Sample Output
  5. 5. Solution

The problem of finding the next term of a given sequence of numbers is usually proposed in QI tests. We want to generate the N terms of a sequence from a given codification of the sequence.

Let S = (Si)i $\scriptstyle \in$$\scriptstyle \mathbb {N}$ denote a sequence of real numbers whose i -order term is Si . We codify a constant sequence with the following operator:

S = [ n] meaning that Si = n $\displaystyle \forall$i$\displaystyle \in$$\displaystyle \mathbb {N}$,

where n$\in$$\mathbb {Z}$ . We also define the following operators on a given sequence of numbers S = (Si)i $\scriptstyle \in$$\scriptstyle \mathbb {N}$ :

V = [ m + S ] meaning that
$Vi = \displaystyle \cases{m & , <span>$i=1$</span><!-- Has MathJax --> \cr V<em>{i-1}+ S</em>{i-1} &amp; , <span>$i &gt; 1$</span><!-- Has MathJax --> \cr};<br>$

V = [ m * S ] meaning that
$Vi = \displaystyle \cases{m \ast S_{1} & , <span>$i=1$</span><!-- Has MathJax --> \cr V_{i-1} \ast S_i &amp; , <span>$i &gt; 1$</span><!-- Has MathJax --> \cr};<br>$

where m$\in$$\mathbb {N}$ . For example we have the following codifications:

1
2
3
4
[2 + [1]] = 2, 3, 4, 5, 6 ...
[1 + [2 + [1]]] = 1, 3, 6, 10, 15, 21, 28, 36 ...
[2 * [1 + [2 + [1]]]] = 2, 6, 36, 360, 5400, 113400 ...
[2 * [5 + [- 2]]] = 10, 30, 30, -30, 90, -450, 3150 ...

Given a codification, the problem is to write the first N terms of the sequence.

Input

The input file contains several test cases. For each of them, the program input is a single line containing the codification, without any space, followed by an integer N(2$\le$N$\le$50) .

Output

For each test case, the program output is a single line containing the list of first N terms of the sequence.

Sample Input

1
2
[2+[1]] 3
[2*[5+[-2]]] 7

Sample Output

1
2
2 3 4
10 30 30 -30 90 -450 3150

Solution

遞迴建造

1
2
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
#include <stdio.h>
#include <string.h>
long long a[128];
void parsing(char s[]) {
int sign = 1, i, m = 0;
char pos;
for(i = 1; s[i]; i++) {
if(s[i] == '-') sign = -1;
else if(s[i] >= '0' && s[i] <= '9')
m = m * 10 + s[i] - '0';
else {
pos = s[i];
break;
}
}
m = sign * m;
if(pos == '+') {
parsing(s + i + 1);
long long d = a[0];
a[0] = m;
for(int i = 1; i < 50; i++) {
long long t = a[i];
a[i] = a[i - 1] + d, d = t;
}
} else if(pos == '*') {
parsing(s + i + 1);
a[0] *= m;
for(int i = 1; i < 50; i++)
a[i] = a[i] * a[i-1];
} else {
for(int i = 0; i < 50; i++)
a[i] = m;
}
}
int main() {
char s[1024];
int n;
while(scanf("%s %d", s, &n) == 2) {
memset(a, 0, sizeof(a));
parsing(s);
for(int i = 0; i < n; i++)
printf("%lld%c", a[i], i == n - 1 ? '\n' : ' ');
}
return 0;
}
/*
[2+[1]] 3
[2*[5+[-2]]] 7
*/