2 4 4 1 1 3 2 4 1 2 2 3 2 4 3 4 4 4 2 2 1 3 4 1 2 2 4 1 3 3 4
Case #1: 8 Case #2: 5
简单树型DP!
AC码:
#include<iostream> #include<cstdio> #include<vector> #include<cstring> using namespace std; #define MAX 1005 #define INF 9999999 vector<int> adj[MAX]; int dp[MAX],visit[MAX]; int weight[MAX]; int Min(int a,int b) { return a>b?b:a; } void DFS(int u) { if(visit[u]) return; int len=adj[u].size(),v; if(len==0) { dp[u]=weight[u]; return; } for(int i=0;i<len;i++) { v=adj[u][i]; DFS(v); visit[v]=1; dp[u]=Min(dp[u],dp[v]+weight[u]); } } int main() { int T,i,count=1; int n,m,p,a,b; scanf("%d",&T); while(T--) { scanf("%d%d%d",&n,&m,&p); for(i=0;i<=n;i++) adj[i].clear(); for(i=1;i<=n;i++) scanf("%d",&weight[i]); for(i=1;i<=m;i++) { scanf("%d%d",&a,&b); adj[a].push_back(b); } memset(visit,0,sizeof(visit)); for(i=0;i<=n;i++) dp[i]=INF; DFS(p); printf("Case #%d: %d\n",count++,dp[p]); } return 0; }
原文地址:http://blog.csdn.net/u012804490/article/details/25837381