题意:
horse被困在小岛上了,现在想要回去,到第N号小岛上。有N个岛屿,M条河流。你有一艘小船,能无视上下流的走K条河流。或者可以飘着走任意一条下流河(随机的)。每走一条河流花费1min,求从第1~n个小岛到第n个岛的最坏情况下的最短时间。
思路:
bfs + dp(当时我人傻了啊)
状态转移:设dp[u][j]表示到u点时已经划了j步,则dp[v][0]表示飘着的过程。
主动划 dp[u][j] = min(dp[u][j], dp[v][j+1] + 1);
顺水漂 dp[u][j] = max(dp[u][j], dp[v][0] + 1);
这里有一个非常坑的点:顺水漂取最大值,主动划取最小值!
想要原题点这里
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
typedef long long int ll;
const int N = 1e5+7;
const int inf = 0x3f3f3f3f;
struct waterful
{
int v,next,d;//d记录水流方向
}tu[N*2];
int head[N], top, n, m, k;
int dp[N][55], ot[N];//ot记录出度
bool jud[N];
void build(int u,int v,int d)
{
top++;
tu[top] = {v, head[u], d};
head[u] = top;
}
queue< pair <int,int> > q;
void bfs()//反向bfs
{
for(int i = 0; i <= k; i++)//到达点N的时候,j可能是任何值
static_cast<void>(dp[n][i] = 0), q.push({n, i});
while(!q.empty())
{
int u = q.front().first;
int t = q.front().second;
// printf("%d %d\n",u,t);
q.pop();
if(t > 0)
{
for(int i = head[u]; i; i = tu[i].next)
{
int v = tu[i].v;
if(dp[v][t-1] > dp[u][t] + 1)
{
dp[v][t-1] = dp[u][t] + 1;
q.push({v,t-1});
}
}
}
else
{
for(int i = head[u]; i; i = tu[i].next)
{
int v = tu[i].v, d = tu[i].d;
if(d) continue;
ot[v] --;
if(!ot[v])
{
for(int j = 0; j <= k ;j++)
{
if(dp[v][j] > dp[u][t] + 1)
{
dp[v][j] = dp[u][t] + 1;
q.push({v,j});
}
}
}
}
if(jud[u])
{
for(int j = 0; j <= k ;j++)
{
if(dp[u][j] > dp[u][t] + 1)
{
dp[u][j] = dp[u][t] + 1;
q.push({u,j});
}
}
}
}
}
}
int main()
{
int T;scanf("%d",&T);
for(int t = 1; t <= T; t++)
{
scanf("%d%d%d",&n,&m,&k);
top = 0;//初始化
memset(jud, false, sizeof(jud));
memset(ot, 0, sizeof(ot));
memset(head, 0, sizeof(head));
for(int i = 0; i <= n; i++)
{
for(int j = 0; j <= k; j++)
dp[i][j] = inf;
}
for(int i = 0; i < m; i++)
{
int u,v;scanf("%d%d",&u,&v);
build(u, v, 1);//水流顺向
build(v, u, 0);//水流逆向
ot[u]++;//记录出度
}
for(int i = 0; i <= n; i++)
if(ot[i] == 0) jud[i] = true;//判断出度为0的点
bfs();
printf("Case #%d:\n",t);
for(int i = 1; i <= n; i++)
{
if(dp[i][0] != inf) printf("%d\n",dp[i][0]);
else printf("-1\n");
}
}
return 0;
}