2017冬季24集训模拟-1.寻找幽灵

————————————————————————————————————————————题解

把最短路处理出来然后做背包

没有把head数组和all初始化qwq

 1 #include <iostream>
 2 #include <queue>
 3 #include <set>
 4 #include <cstdio>
 5 #include <cstring>
 6 #include <vector>
 7 #include <algorithm>
 8 #define siji(i,x,y) for(int i=x;i<=y;++i)
 9 #define gongzi(j,x,y) for(int j=x;j>=y;--j)
10 #define xiaosiji(i,x,y) for(int i=x;i<y;++i)
11 #define sigongzi(j,x,y) for(int j=x;j>y;--j)
12 #define ivorysi
13 #define inf 0x5f5f5f5f
14 #define mo 97797977
15 #define ha 974711
16 #define ba 47
17 #define fi first
18 #define se second
19 #define pii pair<int,int>
20 typedef long long ll;
21 using namespace std;
22 struct node {
23     int to,next,val;
24 }edge[20005];
25 int head[105],sumedge;
26 int n,m,num[105],all,T,ans;
27 int dist[105],f[20005],vis[105];
28 void add(int u,int v,int c) {
29     edge[++sumedge].to=v;
30     edge[sumedge].next=head[u];
31     edge[sumedge].val=c;
32     head[u]=sumedge;
33 }
34 void spfa(int u) {
35     vis[u]=1;
36     for(int i=head[u];i;i=edge[i].next) {
37         int v=edge[i].to,w=edge[i].val;
38         if(dist[u]+w < dist[v]) {
39             dist[v]=dist[u]+w;
40             if(!vis[v]) {
41                 spfa(v);
42             }
43         }
44     }
45     vis[u]=0;
46 }
47 void init() {
48     scanf("%d%d",&n,&m);
49     int u,v,w;
50     sumedge=0;
51     memset(head,0,sizeof(head));
52     all=0;
53     siji(i,1,m) {
54         scanf("%d%d%d",&u,&v,&w);
55         ++u,++v;
56         add(u,v,w);
57         add(v,u,w);
58     }
59     siji(i,2,n+1) {scanf("%d",&num[i]);all+=num[i];}
60     dist[1]=0;
61     siji(i,2,n+1) dist[i]=inf;
62     spfa(1);
63     f[0]=0;
64     siji(i,1,all) f[i]=inf;
65     ans=inf;
66 }
67 void solve() {
68     scanf("%d",&T);
69     while(T--) {
70         init();
71         siji(i,2,n+1) {
72             if(dist[i]>=inf) continue;
73             gongzi(j,all,num[i]) {
74                 if(f[j-num[i]] < f[j]-dist[i]) {
75                     f[j]=f[j-num[i]]+dist[i];
76                 }
77             }
78         }
79         int half=all/2+1;
80         siji(i,half,all) {
81             if(ans>f[i]) ans=f[i];
82         }
83         if(ans>=inf) puts("impossible");
84         else printf("%d\n",ans);
85     }
86 }
87 int main(int argc, char const *argv[])
88 {
89 #ifdef ivorysi
90     freopen("release.in","r",stdin);
91     freopen("release.out","w",stdout);
92 #else
93     freopen("f1.in","r",stdin);
94 #endif
95     solve();
96     return 0;
97 }

 

posted @ 2017-02-13 20:39  sigongzi  阅读(249)  评论(0编辑  收藏  举报