Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P3216 [HNOI2011]数学作业

P3216 [HNOI2011]数学作业

考虑一位数的情况,可以得到 $f _ i = 10 f _ {i - 1} + i$ 。类似地,可以考虑更多位。

于是可以写作 $f _ i = 10 ^ k f _ {i - 1} + i$ 。发现可以矩阵加速,但是 $k$ 不好处理,注意到 $\log _ {10} n$ 较小,对每个 $k$ 都做一次。

实现时,$10 ^ {18}$ 不会炸 long long ,但是再乘 10 就炸了,所以用 unsigned long long

查看代码
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
81
82
83
84
#include <cstdio>
#include <algorithm>
using namespace std;
typedef unsigned long long LL;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
flag && (x = ~x + 1);
}
template <class Type>
void write(Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar(x % 10 + '0');
}
int p;
struct Matrix
{
int n, m, w[3][3];
Matrix()
{
}
Matrix(int x, int y)
{
n = x, m = y;
}
Matrix(int x, int y, int k)
{
n = x, m = y;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
w[i][j] = i == j ? k : 0;
}
void output ()
{
printf("%d %d\n", n, m);
for (int i = 0; i < n; i++, puts(""))
for (int j = 0; j < m; j++, putchar(' '))
write(w[i][j]);
}
friend Matrix operator*(Matrix x, Matrix y)
{
Matrix res(x.n, y.m, 0);
for (int i = 0; i < res.n; i++)
for (int k = 0; k < x.m; k++)
for (int j = 0, t = x.w[i][k]; j < res.m; j++)
(res.w[i][j] += (LL)t * y.w[k][j] % p) %= p;
return res;
}
friend Matrix operator^(Matrix b, LL k)
{
Matrix res(b.n, b.m, 1);
while (k)
{
k & 1 && (res = res * b, 0);
b = b * b;
k >>= 1;
}
return res;
}
};
int main ()
{
static Matrix A(1, 3), B(3, 3);
A.w[0][1] = 1, A.w[0][2] = 1;
LL n;
read(n), read(p);
for (LL i = 1; i <= n; i *= 10)
{
B.w[0][0] = i % p * 10 % p;
B.w[1][0] = B.w[1][1] = B.w[2][1] = B.w[2][2] = 1;
A = A * (B ^ min(n - i + 1, i * 10 - i));
}
write(A.w[0][0]);
return 0;
}