PAT (Advanced Level) Practice 1003 Emergency

思路:用深搜遍历出所有可达路径,每找到一条新路径时,对最大救援人数和最短路径数进行更新。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 const int N=600;
 6 int tu[N][N],city[N],vis[N];//tu存道路,city存各城市救援人数,vis为标记数组
 7 int n,m,start,dis,path=0,shortest=1e8,allpeople=0;//path为最短路径数,allpeople为最大救援人数
 8 void read()
 9 {
10     memset(vis,0,sizeof(vis));
11     fill(tu[0],tu[0]+N*N,0);
12     cin>>n>>m>>start>>dis;
13     for (int i=0;i<n;i++)
14         cin>>city[i];
15     int a,b,c;
16     for (int i=0;i<m;i++)
17     {
18         cin>>a>>b>>c;
19         tu[a][b]+=c;//注意题目,是无向图!!
20         tu[b][a]+=c;
21     }
22 }
23 void dfs(int step,int now,int people)
24 {
25     people+=city[now];//要先加上该城市救援人数!
26     if (now==dis)
27     {
28         if (step<shortest)
29         {
30             shortest=step;
31             allpeople=people;
32             path=1;
33         }
34         else if (step==shortest)//这里要用else if不能用if!!如果用if会在第一次更新时满足这两个if判断,导致path多加了一次!!
35         {
36             path++;
37             allpeople=max(allpeople,people);
38         }
39         return;
40     }
41     vis[now]=1;
42     for (int i=0;i<n;i++)
43     {
44         if (tu[now][i]>0&&vis[i]==0)
45         {
46             step+=tu[now][i];
47             dfs(step,i,people);
48             step-=tu[now][i];
49         }
50     }
51     vis[now]=0;
52 }
53 int main()
54 {
55 //    freopen("in.txt","r",stdin);
56     read();//输入函数
57     dfs(0,start,0);//深搜遍历所有路径
58     cout<<path<<" "<<allpeople<<endl;
59 
60     return 0;
61 }

 

posted @ 2019-04-02 00:41  hemeiwolong  阅读(144)  评论(0编辑  收藏  举报