Accept: 209 Submit: 427
Time Limit: 5000 mSec Memory Limit : 32768 KB
Problem Description
Oaiei is idle, and recently he wants to travel around the country. In his country there are N cities, they are numbered from 1 to N. There are roads between some cities, but some are not directly connected with each other. Oaiei lives in the city 1, and he wants to go to city N. Now, he has a question. In k steps, he would like to know there are how many ways from city 1 to city N. You should note that althought there is a road between city A and city B, there is not necessarily a road between city B and city A.
Input
There are multiple tests. For each test, the first line contains three integers N、M and k(2<=N<=100,1<=M<=N*N,1<=k<=10^9), N denotes the number of cities, M denotes the number of roads between the N cities. Following M lines, each line contains two integers A and B, denoting there is a road between city A and city B.
Output
There are how many ways from city 1 to city N. Becase the answer can be very large, you should output the answer MOD 10000.
Sample Input
Sample Output
Source
Summer Training Qualification II
直接矩阵快速幂,没什么说的。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int n, m, k;
struct matrix
{
int num[111][111];
}mp,res;
const int mod = 10000;
matrix mul_matrix(matrix a,matrix b)
{
matrix cmp;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cmp.num[i][j] = 0;
for (int k = 1; k <= n; k++)
{
(cmp.num[i][j] += a.num[i][k] * b.num[k][j])%=mod;
}
}
}
return cmp;
}
void quick()
{
while (k)
{
if (k & 1)
{
res = mul_matrix(res, mp);
}
k >>= 1;
mp = mul_matrix(mp, mp);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cout << mp.num[i][j] << " ";
}
cout << endl;
}
}
}
int main()
{
int x, y;
while (~scanf("%d%d%d",&n, &m, &k))
{
memset(mp.num, 0, sizeof(mp.num));
memset(res.num, 0, sizeof(res.num));
for (int i = 0; i <= n; i++)
{
mp.num[i][i] = 1;
res.num[i][i] = 1;
}
for (int i = 0; i < m; i++)
{
scanf("%d%d", &x, &y);
mp.num[x][y] = 1;
}
quick();
cout << res.num[1][n] << endl;
}
return 0;
}