动态规划。其实一直都不知道动态规划是什么,看见什么状态转移方程就头疼,一直缺乏了解。但这道题比较简单,可见方程是:road[ I ][ J ][ L ] = ∑road[ I ][ K ][ L – 1 ],意思是在L天内,从I点到J点的方案等于所有在L-1天内,从I点到K点的方案数总和,其中从K点到J只需一天。当然也可以用递归来做,只不过前后顺序相反而已。
另:这道题q的数目好像不多,利用状态转移方程全部求出然后常数时间查找的效果反而不如记忆化递归求解更有效率。前者若用邻接矩阵,时间复杂度是O(Ln3),耗时0.48s左右;若用邻接表,时间复杂度是O(Lnm),耗时0.10s左右;至于后者,若没有记忆化操作会超时(因为这样就等同于递归形式的分层宽搜,更别说深搜了),记忆化后只需0.05s左右。
Run Time: 0.1sec
Run Memory: 4208KB
Code length: 852Bytes
SubmitTime: 2012-01-06 22:52:44
// Problem#: 1211
// Submission#: 1178284
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cstdio>
#include <vector>
using namespace std;
int main()
{
int n, m, L;
int q, A, B;
int i, j, k, l;
vector<int> v[ 101 ];
int road[ 101 ][ 101 ][ 101 ] = { };
scanf( "%d%d%d", &n, &m, &L );
while ( m-- ) {
scanf( "%d%d", &i, &j );
road[ i ][ j ][ 1 ] = 1;
v[ i ].push_back( j );
}
for ( l = 2; l <= L; l++ ) {
for ( i = 1; i <= n; i++ ) {
for ( j = 1; j <= n; j++ ) {
if ( road[ i ][ j ][ l - 1 ] != 0 ) {
for ( k = 0; k < v[ j ].size(); k++ )
road[ i ][ v[ j ][ k ] ][ l ] += road[ i ][ j ][ l - 1 ];
}
}
}
}
scanf( "%d", &q );
while ( q-- ) {
scanf( "%d%d", &A, &B );
printf( "%d\n", road[ A ][ B ][ L ] );
}
return 0;
}