-
Notifications
You must be signed in to change notification settings - Fork 153
/
aggregate_cyclic_function.cpp
80 lines (72 loc) · 2 KB
/
aggregate_cyclic_function.cpp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Description: Calculate aggregate of k terms in a cyclic function
* Note: cycle length must be small.
* getNext and getCyclicFuncfion must be overridden accordingly.
* Assumption: seed is considered as the 0th element of the sequence
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
long long getNext(long long x) {
return x + 1;
}
long long getCyclic(long long x) {
return x % 5;
}
long long getSum(long long seed, long long k) {
const int INF = 1e9;
long long cycleLength = INF, cycleStart = -1;
map<int,int> index;
index[getCyclic(seed)] = 0;
{
long long x = seed;
for (int i = 1; i <= k; i++) {
x = getNext(x);
long long c = getCyclic(x);
if (index.count(c)) {
cycleStart = index[c];
cycleLength = i-cycleStart;
break;
} else {
index[c] = i;
}
}
}
long long sum = 0;
{
if (cycleLength == INF) {
sum += getCyclic(seed);
long long x = seed;
for (int i = 1; i <= k; i++) {
x = getNext(x);
sum += getCyclic(x);
}
} else {
k++;
long long x = seed;
for (int i = 1; i <= cycleStart; i++) {
sum += getCyclic(x);
x = getNext(x);
k--;
}
long long turns = k/cycleLength;
long long rem = k%cycleLength;
long long cycleSum = 0, remSum = 0;
for (int i = 0; i < cycleLength; i++) {
long long c = getCyclic(x);
cycleSum += c;// modify here
if (i < rem) {
remSum += c; // modify here
}
x = getNext(x);
}
sum += turns * cycleSum + remSum;
}
}
return sum;
}
int main() {
cout << getSum(1, 6) << endl;
}