Problem solving: the shortest path + 0-1 backpack, first finding the distance from 0 to each city, then carrying out a backpack in 1... n cities at the cost of distance.
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <climits> 7 #include <algorithm> 8 #include <cmath> 9 #include <queue>10 #define LL long long11 #define INF 0x3f3f3f3f12 using namespace std;13 const int maxn = 110;14 struct arc{15 int to,w;16 };17 vector<arc>g[maxn];18 queue<int>q;19 int s,n,m;20 int val[maxn],d[maxn],pre[maxn];21 int dp[1000010];22 bool in[maxn];23 void spfa(int src){24 int i,j,u,v;25 for(i = 0; i <= n; i++){26 d[i] = INF;27 in[i] = false;28 pre[i] = -1;29 }30 d[src] = 0;31 while(!q.empty()) q.pop();32 q.push(src);33 in[src] = true;34 while(!q.empty()){35 u = q.front();36 q.pop();37 in[u] = false;38 for(i = 0; i < g[u].size(); i++){39 v = g[u][i].to;40 if(d[v] > d[u]+g[u][i].w){41 d[v] = d[u]+g[u][i].w;42 pre[v] = u;43 if(!in[v]){44 q.push(v);45 in[v] = true;46 }47 }48 }49 }50 }51 int main(){52 int t,i,j,u,v,w;53 scanf("%d",&t);54 while(t--){55 scanf("%d%d%d",&s,&n,&m);56 for(i = 0; i <= n; i++)57 g[i].clear();58 for(i = 0; i < m; i++){59 scanf("%d%d%d",&u,&v,&w);60 g[u].push_back((arc){v,w});61 g[v].push_back((arc){u,w});62 }63 for(i = 1; i <= n; i++)64 scanf("%d",val+i);65 spfa(0);66 memset(dp,0,sizeof(dp));67 for(i = 1; i <= n; i++){68 for(j = s; j >= d[i]; j--){69 dp[j] = max(dp[j],dp[j-d[i]]+val[i]);70 }71 }72 printf("%d\n",dp[s]);73 }74 return 0;75 }
View code