pat 1018

#include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<string.h>
using namespace std;

int C,N,p,M;
int v[505];//bike的容量 
int road[505][505];//两点之间的距离 
int vis[505];

int sum_road,shortest;
int avaliable;
int bring,back;
int res_bring,res_back;

vector<int> path;
vector<int> res;

void dfs(int x){
    if(x==p){
       back=avaliable;
       if(sum_road<shortest){
           shortest=sum_road;
           res_bring=bring;
           res_back=back;
           res.clear();
           for(int j=0;j<path.size();j++)
               res.push_back(path[j]);
       }
       else if(sum_road==shortest){
           if(bring<res_bring){
               res_bring=bring;
               res_back=back;//这一句没写,导致一个测试样例没过 
               res.clear();
               for(int j=0;j<path.size();j++)
                   res.push_back(path[j]);
           }else if(bring==res_bring){
               if(back<res_back){
                   res_back=back;
                   res.clear();
                   for(int j=0;j<path.size();j++)
                       res.push_back(path[j]);
               }
           }
       }
       return;
    }
    for(int i=1;i<=N;i++){
        if(road[x][i]!=-1&&vis[i]==false){
            sum_road+=road[x][i];
            path.push_back(i);
            vis[i]=true;
            if(v[i]>C/2){
                avaliable+=v[i]-C/2;
                dfs(i);
                avaliable-=v[i]-C/2;
            }else if(v[i]<C/2){
                if(avaliable>=C/2-v[i]){
                    avaliable-=C/2-v[i];
                    dfs(i);
                    avaliable+=C/2-v[i];
                }else{
                    bring+=C/2-v[i]-avaliable;
                    int tmp=avaliable;
                    avaliable=0;
                    dfs(i);
                    avaliable=tmp;
                    bring-=C/2-v[i]-avaliable;
                }
            }else dfs(i);
            vis[i]=false;
            path.pop_back();
            sum_road-=road[x][i];
        }
    }       
}
int main(){
    scanf("%d%d%d%d",&C,&N,&p,&M);
    for(int i=1;i<=N;i++)
        scanf("%d",&v[i]);
    int a,b,c;
    memset(road,-1,sizeof(road));
    memset(vis,false,sizeof(vis));
    for(int i=0;i<M;i++){
        scanf("%d%d%d",&a,&b,&c);
        road[a][b]=road[b][a]=c;
    }
    sum_road=0;
    avaliable=0;
    bring=back=0;
    path.push_back(0);
    shortest=res_bring=res_back=0x7fffffff;
    vis[0]=true;
    dfs(0);
    printf("%d ",res_bring);
    for(int i=0;i<res.size();i++){
        if(i==0)
            printf("0");
        else
            printf("->%d",res[i]);
    }
    printf(" %d",res_back);
    //system("pause");
    return 0;
}

你可能感兴趣的:(pat 1018)