[SCOI2009]迷路

嘟嘟嘟


预备知识:对于不带权的图的邻接矩阵(G)(G ^ T)表示两点间长度为(T)的路径的方案数。
这个其实挺好理解的,想一下开始的邻接矩阵,(G[i][j])就表示的是(i)走1步到(j)的方案数。然后自己模拟一下两个矩阵相乘,(G[i][j])就表示走两步的方案数。以此类推。


但是这道题边上带权,可是边权小于10。
于是就能想到(我没想到)拆点:把每一个点拆成9个,然后一次连上。如果(i)(j)有一条长度为(k)的边,就从(i)的第(k - 1)个点向(j)的第一个点连边(因为这条边还有1的边权)。
然后矩阵快速幂即可。
答案就是(G)[1号结点的第1个点][(n)号节点的第一个点]。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int mod = 2009;
//const int maxn = ;
inline ll read()
{
  ll ans = 0;
  char ch = getchar(), last = ' ';
  while(!isdigit(ch)) last = ch, ch = getchar();
  while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
  if(last == '-') ans = -ans;
  return ans;
}
inline void write(ll x)
{
  if(x < 0) x = -x, putchar('-');
  if(x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}

int n;
char a[50][50];

const int N = 205;
struct Mat
{
  int a[N][N];
  Mat operator * (const Mat& oth)const
  {
    Mat ret; Mem(ret.a, 0);
    for(int i = 1; i <= n; ++i)
      for(int j = 1; j <= n; ++j)
	for(int k = 1; k <= n; ++k)
	  ret.a[i][j] += a[i][k] * oth.a[k][j], ret.a[i][j] %= mod;
    return ret;
  }
}F;

int calc(int i, int j)
{
  return (i - 1) * 9 + j;
}
void init()
{
  Mem(F.a, 0);
  for(int i = 1; i <= n; ++i)
    {
      for(int j = 1; j < 9; ++j)
	F.a[calc(i, j)][calc(i, j + 1)] = 1;
      for(int j = 1; j <= n; ++j)
	if(a[i][j] > '0') F.a[calc(i, a[i][j] - '0')][calc(j, 1)] = 1;
    }
  n *= 9;
}

Mat quickpow(Mat A, ll b)
{
  Mat ret; Mem(ret.a, 0);
  for(int i = 1; i <= n; ++i) ret.a[i][i] = 1;
  for(; b; b >>= 1, A = A * A)
    if(b & 1) ret = ret * A;
  return ret;
}

int main()
{
  n = read(); ll t = read();
  for(int i = 1; i <= n; ++i) scanf("%s", a[i] + 1);
  init();
  Mat A = quickpow(F, t);
  write(A.a[1][n - 8]), enter;
  return 0;
}
原文地址:https://www.cnblogs.com/mrclr/p/10118757.html