L3-004. 肿瘤诊断
题目链接:https://www.patest.cn/contests/gplt/L3-004
BFS
之前尝试使用递归dfs,提交后发现有两个段错误,发现递归层数太多,然后改用bfs解决。
代码如下:
1 #include<cstdio> 2 #include<stack> 3 #define N 505 4 #define MAX 5000 5 using namespace std; 6 int n,m,s,d; 7 int pro[N]; 8 int Map[N][N]; 9 bool mark[N]; 10 int sum[N]; 11 int path[N]; 12 int Distance[N]; 13 int person[N]; 14 int i,j; 15 stack<int>st; 16 int main(void){ 17 freopen("in.txt","r",stdin); 18 scanf("%d%d%d%d",&n,&m,&s,&d); 19 for(i=0;i<n;++i)scanf("%d",&pro[i]); 20 for(i=0;i<n;++i) 21 for(j=0;j<n;++j)Map[i][j]=MAX; 22 while(m--){ 23 int len; 24 scanf("%d%d%d",&i,&j,&len); 25 if(Map[i][j]>len)Map[i][j]=Map[j][i]=len; 26 } 27 for(i=0;i<n;++i){ 28 Distance[i]=MAX; 29 sum[i]=1; 30 person[i]=pro[s]; 31 if(Map[s][i]<MAX){ 32 Distance[i]=Map[s][i]; 33 path[i]=s; 34 person[i]+=pro[i]; 35 } 36 } 37 mark[s]=1,Distance[s]=0; 38 while(1){ 39 int k,m=MAX; 40 for(i=0;i<n;++i){ 41 if(!mark[i]&&m>Distance[i]){ 42 m=Distance[i]; 43 k=i; 44 } 45 } 46 if(m==MAX)break; 47 mark[k]=1; 48 for(i=0;i<n;++i){ 49 if(!mark[i]){ 50 if(Distance[i]>Distance[k]+Map[k][i]){ 51 Distance[i]=Distance[k]+Map[k][i]; 52 person[i]=person[k]+pro[i]; 53 path[i]=k; 54 sum[i]=sum[k];/**not 1**/ 55 }else if(Distance[i]==Distance[k]+Map[k][i]){ 56 sum[i]+=sum[k];/**not ++**/ 57 if(person[i]<person[k]+pro[i]){ 58 person[i]=person[k]+pro[i]; 59 path[i]=k; 60 } 61 } 62 } 63 } 64 } 65 int temp=pro[d]; 66 int k=d; 67 while(k!=s){ 68 st.push(k); 69 k=path[k]; 70 temp+=pro[k]; 71 } 72 printf("%d %d ",sum[d],temp); 73 printf("%d",s); 74 while(!st.empty()){ 75 printf(" %d",st.top()); 76 st.pop(); 77 } 78 printf(" "); 79 return 0; 80 }