前向星+SPFA
定义状态DP[i][j]表示从起点开始,i点经过j条边后达到的最短路
那么答案就在DP[T][X>=K]中
在SPFA中不断更新这个最小值,二维队列中若点等于T,边数大于等于K,那么就确定找得到解。设置found=true同时在这里更新最小值
如果没有遍历过当前DP,或者可以松弛那么就更新DP,入队
定义状态DP[i][j]表示从起点开始,i点经过j条边后达到的最短路
那么答案就在DP[T][X>=K]中
在SPFA中不断更新这个最小值,二维队列中若点等于T,边数大于等于K,那么就确定找得到解。设置found=true同时在这里更新最小值
如果没有遍历过当前DP,或者可以松弛那么就更新DP,入队
转移就是第一维为新可以达到的点(边相连),num+1
#include <map>
#include <set>
#include <list>
#include <cmath>
#include<cctype>
#include <ctime>
#include <deque>
#include <stack>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define LL long long
#define PI 3.1415926535897932626
using namespace std;
int gcd(int a, int b)
{
return a % b == 0 ? b : gcd(b, a % b);
}
#define MAXN 5005
#define INF 100000000
struct node
{
int v;
int value,next;
}src[200005];
bool vis[MAXN][55];
int cnt;
bool found;
int Ans;
int S,T,K,N,M;
int head[MAXN],dp[MAXN][55];
void add(int u,int v,int value)
{
src[cnt].v=v;
src[cnt].value=value;
src[cnt].next=head[u];
head[u]=cnt++;
src[cnt].v=u;
src[cnt].value=value;
src[cnt].next=head[v];
head[v]=cnt++;
}
void init()
{
memset(head,-1,sizeof(head));
cnt=0;
int a,b,c;
for (int i=0;i<M;i++)
{
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
}
scanf("%d%d%d",&S,&T,&K);
}
struct ans
{
int edge,num;
};
bool spfa()
{
found=false;
Ans=INF;
memset(dp,-1,sizeof(dp));
memset(vis,false,sizeof(vis));
ans u,s;
queue<ans>q;
u.num=0;u.edge=S;
dp[u.edge][u.num]=0;
vis[u.edge][u.num]=true;
q.push(u);
while (!q.empty())
{
u=q.front();
q.pop();
vis[u.edge][u.num]=false;
if (u.edge==T && u.num>=K && dp[T][u.num]<Ans)
{
found=true;
Ans=dp[T][u.num];
}
for (int i=head[u.edge];i!=-1;i=src[i].next)
{
int v=src[i].v;
s.edge=v;s.num=u.num+1;
if (dp[s.edge][s.num]==-1 || dp[s.edge][s.num]>dp[u.edge][u.num]+src[i].value)
{
dp[s.edge][s.num]=dp[u.edge][u.num]+src[i].value;
if (!vis[s.edge][s.num])
{
vis[s.edge][s.num]=true;
q.push(s);
}
}
}
}
return found;
}
int main()
{
//freopen("sample.txt","r",stdin);
while (scanf("%d%d",&N,&M)!=EOF)
{
//printf("%d\n",INF);
init();
spfa();
//for (int i=K;i<=50;i++) printf("%d\n",dp[T][i]);
if (found) printf("%d\n",Ans);
else printf("-1\n");
}
return 0;
}