poj 1995:
题意:
给a,b,m,求:
(A1B1+A2B2+ ... +AHBH)mod M.
解析:
快速幂。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);
const int maxn = 30 + 10;
LL pow_mod(LL a, LL n, LL mod)
{
if (n == 0)
return 1;
LL x = pow_mod(a, n >> 1, mod);
LL res = x * x % mod;
if (n % 2)
res = res * a % mod;
return res;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
int ncase;
scanf("%d", &ncase);
while (ncase--)
{
LL m;
scanf("%lld", &m);
LL n;
scanf("%lld", &n);
LL ans = 0;
for (LL i = 0; i < n; i++)
{
LL a, b;
scanf("%lld%lld", &a, &b);
ans = (ans + pow_mod(a, b, m)) % m;
}
printf("%lld\n", ans);
}
return 0;
}
poj 3233:
题意:
给一个n×n的矩阵和一个整数k,求:
s = A + A ^ 2 + A ^ 3 + A ^ 4 ... + A ^ k.
解析:
矩阵快速幂。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);
const int maxn = 30 + 10;
struct Matrax
{
int num[maxn][maxn];
} a, per;
int n, k, mod;
Matrax add(Matrax a, Matrax b)
{
Matrax c;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
c.num[i][j] = (a.num[i][j] + b.num[i][j]) % mod;
}
}
return c;
}
Matrax multi(Matrax a, Matrax b)
{
Matrax c;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
c.num[i][j] = 0;
for (int k = 0; k < n; k++)
{
c.num[i][j] += a.num[i][k] * b.num[k][j];
}
c.num[i][j] %= mod;
}
}
return c;
}
Matrax power(int k)
{
Matrax c, t;
Matrax res = per;
t = a;
while (k)
{
if (k & 1)
{
res = multi(res, t);
k--;
}
else
{
k >>= 1;
t = multi(t, t);
}
}
return res;
}
Matrax sum(int k)
{
if (k == 1)
return a;
Matrax b, t;
t = sum(k >> 1);
if (k & 1)
{
b = power((k >> 1) + 1);
t = add(t, multi(t, b));
t = add(t, b);
}
else
{
b = power(k >> 1);
t = add(t, multi(t, b));
}
return t;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
while (scanf("%d%d%d", &n, &k, &mod) == 3)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d", &a.num[i][j]);
a.num[i][j] %= mod;
per.num[i][j] = (i == j);
}
}
Matrax ans = sum(k);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1; j++)
{
printf("%d ", ans.num[i][j]);
}
printf("%d\n", ans.num[i][n - 1]);
}
}
return 0;
}