Test Instructions:
Given a weighted graph, ask to answer the shortest path from S S to T T, under the condition that the number of nodes does not exceed S S.
Data range:
N (2≤n≤100), M (0≤m≤1000), Q (1≤q≤10) N (2≤n≤100), M (0≤m≤1000), Q (1≤q≤10) idea:
Because there is a limit to the number of nodes that pass through, you have to record this information.
Directly to the diagram of Dfs Dfs, Dp[u][i] dp[u][i] represents the current node u, has gone through I I city, to u−>v u->v side, transfer is:
for (int j=1;j<=n;j++) {
if (dp[u][j]! =-1) {
if (dp[v][j+1] = = 1) dp[v][j+1] = Dp[u][j] + e[i].w;
else dp[v][j+1] = min (dp[v][j+1],dp[u][j] + E[I].W);
}
}
However, the complexity of Dfs Dfs is O (n∗m) O (n*m), this Nima incredibly t, the positive solution is SPFA, the complexity is close to O (M) O (m), compared to the original solution is to join the queue optimization, with the current optimal most slack other points. Code:
#include <cstdio> #include <cstring> #include <queue> #include <algorithm> #include < iostream> #include <cmath> #include <map> #include <vector> #include <set> #include < string> #define PB push_back #define FT First #define SD second #define MP make_pair #define INF 0x3f3f3f3f using names
Pace std;
typedef long Long LL;
typedef unsigned long long ULL;
typedef pair<int,int> P;
const int N=5+1E2,MOD=7+1E9;
int n,dp[n][n];
Char city[25],s1[25],s2[25];
Map<string,int> MP;
int tot,head[n]; struct Edge {int to,w,next;}
E[1005];
BOOL Vis[n][n];
void Init () {tot=0;
Mp.clear ();
memset (head,-1,sizeof (head));
Memset (Dp,inf,sizeof (DP)); } void Addedge (int u,int v,int c) {e[tot].to = V,E[TOT].W = C,e[tot].next = Head[u],head[u] = tot++;} void Dfs (int u
) {for (int i=head[u];i!=-1;i=e[i].next) {int v=e[i].to;
for (int j=1;j<=n;j++) {if (dp[u][j]! =-1) { if (dp[v][j+1] = =-1) dp[v][j+1] = Dp[u][j] + e[i].w;
else dp[v][j+1] = min (dp[v][j+1],dp[u][j] + E[I].W);
}} dfs (v);
}} void Spfa () {dp[1][1]=0;
memset (vis,0,sizeof (VIS));
Queue<p> Q;
Q.push (MP);
Vis[1][1]=1; while (!q.empty ()) {int u = Q.front (). FT, cnt = Q.front ().
SD; Q.pop ();
vis[u][cnt]=0;
for (int i=head[u];i!=-1;i=e[i].next) {int v=e[i].to;
if (dp[v][cnt+1] > dp[u][cnt] + e[i].w) {dp[v][cnt+1] = dp[u][cnt] + e[i].w;
if (!vis[v][cnt+1]) {vis[v][cnt+1]=1;
Q.push (MP (v,cnt+1));
}}}}} int main () {//freopen ("In.txt", "R", stdin);
Freopen ("OUT.txt", "w", stdout);
int t,ca=0;
scanf ("%d", &t);
while (t--) {scanf ("%d", &n);
Init ();
for (int i=1;i<=n;i++) {scanf ('%s ', city); Mp[city]=i; } int c,m;
scanf ("%d", &m);
for (int i=0;i<m;i++) {scanf ("%s%s%d", s1,s2,&c);
Addedge (MP[S1],MP[S2],C);
} SPFA ();
for (int i=1;i<=n;i++) {dp[n][i]=min (dp[n][i-1],dp[n][i]);
} printf ("Scenario #%d\n", ++CA);
int Q;
scanf ("%d", &q);
while (q--) {int Q;
scanf ("%d", &q);
q = min (n,q+2);
if (dp[n][q] = = INF) {printf ("No satisfactory flights\n");
} else printf ("Total cost of flight (s) is $%d\n", dp[n][q]);
} if (T) puts ("");
}//system ("pause");
return 0; }