https://vjudge.csgrandeur.cn/contest/529643#problem/C
此题运用拓扑排序的思想,重新定义入度出度,x周围等于x-1的点作为入度++,同理将x+1的点作为出度++。
根据题意描述,数字路径需要最长的长度,所以只能将起始点放在入度为0的点,结束点放在出度为0的点。
对于每次的拓扑排序,都要更新dp数组
借鉴(19条消息) 2019ICPC亚洲区域赛(南京) C-Digital Path 题解_Notorin的博客-优快云博客_icpc南京c
初始时将每一个起始点的dp[i][j][1]都赋1,此后再更新点时将入度不为0的点dp[i][j][1]=0,代表虽然更新此点,但不作为起始点。
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
const int mod = 1e9 + 7;
struct node
{
int x, y;
};
int mp[N][N];
int st[N][N];
int stt[N][N];
int dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1};
int dp[N][N][5];
queue<node> q;
int n, m;
void topsort()
{
while (!q.empty())
{
int x = q.front().x, y = q.front().y;
q.pop();
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 1 || xx > n || yy < 1 || yy > m)
continue;
if (mp[xx][yy] != mp[x][y] + 1)
continue;
if (st[xx][yy] != 0) // 若入度等于0,则说明已经将其更新完
{
dp[xx][yy][1] = 0;
dp[xx][yy][2] = (dp[xx][yy][2] + dp[x][y][1]) % mod;
dp[xx][yy][3] = (dp[xx][yy][3] + dp[x][y][2]) % mod;
dp[xx][yy][4] = (dp[xx][yy][4] + dp[x][y][3] + dp[x][y][4]) % mod;
st[xx][yy]--;
if (st[xx][yy] == 0)
q.push({xx, yy});
}
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
scanf("%d", &mp[i][j]);
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
for (int k = 0; k < 4; k++)
{
int nowi = i + dx[k];
int nowj = j + dy[k];
if (nowi < 1 || nowi > n || nowj < 1 || nowj > m)
continue;
if (mp[i][j] == mp[nowi][nowj] - 1)
stt[i][j]++;
if (mp[i][j] == mp[nowi][nowj] + 1)
st[i][j]++;
}
if (st[i][j] == 0)
{
dp[i][j][1]++;
q.push({i, j});
}
}
}
topsort();
int ans = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
if (stt[i][j] == 0)
ans = (ans + dp[i][j][4]) % mod;
}
cout << ans << endl;
return 0;
}