标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5102 Accepted Submission(s):
1696
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #define M 105 5 #define inf 0x3f3f3f3f 6 using namespace std; 7 int map[M][M],dis[M],vis[M]; 8 int dp[10005]; 9 int mins(int a,int b) 10 { 11 return a>b?b:a; 12 } 13 int main() 14 { 15 int i,j,n,m,T; 16 scanf("%d",&T); 17 while(T--) 18 { 19 scanf("%d%d",&n,&m); 20 memset(dis,0,sizeof(dis)); 21 memset(vis,0,sizeof(vis)); 22 for(i=0; i<=n; i++) 23 for(j=0; j<=n; j++) 24 if(i==j) map[i][j]=0; 25 else map[i][j]=inf; 26 int a,b,c; 27 while(m--) 28 { 29 scanf("%d%d%d",&a,&b,&c); 30 if(map[a][b]>c) 31 map[a][b]=map[b][a]=c; 32 } 33 vis[0]=1; 34 for(i=0; i<=n; i++) 35 dis[i]=map[0][i]; 36 int min,t; 37 for(i=0; i<=n; i++) //迪杰斯特拉 38 { 39 min=inf; 40 for(j=0; j<=n; j++) 41 if(!vis[j]&&min>dis[j]) 42 { 43 min=dis[j]; 44 t=j; 45 } 46 vis[t]=1; 47 for(j=0; j<=n; j++) 48 if(!vis[j]&&map[t][j]<inf) 49 if(dis[j]>dis[t]+map[t][j]) 50 dis[j]=dis[t]+map[t][j]; 51 } 52 int s[M],sum=0; 53 for(i=1; i<=n; i++) 54 { 55 scanf("%d",&s[i]); 56 sum+=s[i]; 57 } 58 for(i=1; i<=sum; i++) 59 dp[i]=inf; 60 dp[0]=0; 61 for(i=1; i<=n; i++) //01背包 62 for(j=sum; j>=s[i]; j--) 63 dp[j]=mins(dp[j],dp[j-s[i]]+dis[i]); 64 int x=sum/2+1,mm=inf; 65 for(i=x; i<=sum; i++) //选出最小的距离 66 if(dp[i]<mm) 67 mm=dp[i]; 68 if(mm<inf) 69 printf("%d\n",mm); 70 else 71 printf("impossible\n"); 72 } 73 return 0; 74 }
hdu 3339 In Action(迪杰斯特拉+01背包)
标签:
原文地址:http://www.cnblogs.com/pshw/p/5463281.html