PAT 甲级 1018 Public Bike Management
作者:互联网
先用迪杰斯特拉剪枝,再dfs确定最佳方案
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N = 4010,INF = 0x3f3f3f3f;
int n,m,c,t;
int nums[N];
int head[N],dis[N],vis[N],cnt;
int send=INF,bring=INF;
struct BIAN{
int to,next;
int len;
}bian[N];
priority_queue<pii,vector<pii>,greater<pii> > q;
void add(int x,int y,int z){
bian[++cnt].to=y;
bian[cnt].next=head[x];
bian[cnt].len=z;
head[x]=cnt;
}
void dij(){
int x,y;
memset(vis,0,sizeof vis);
memset(dis,0x3f,sizeof dis);
dis[0]=0;
q.push({0,0});
while(!q.empty()){
x=q.top().second;
q.pop();
if(vis[x]) continue;
vis[x]=1;
for(int i=head[x];i!=-1;i=bian[i].next){
y=bian[i].to;
if(dis[y]>dis[x]+bian[i].len){
dis[y]=dis[x]+bian[i].len;
q.push({dis[y],y});
}
}
}
}
int tot=0;
vector<int> path,tmp;
void dfs(int x,int cur,int mincur){
if(x!=0){
cur-=c-nums[x];
mincur=min(cur,mincur);
}
if(x==t){
int sd=abs(mincur);
int bg=sd+cur;
if(sd<send){
path=tmp;
send=sd;
bring=bg;
}
else if(sd==send && bg<bring){
path=tmp;
bring=bg;
}
return;
}
int y;
for(int i=head[x];i!=-1;i=bian[i].next){
y=bian[i].to;
if(dis[x]+bian[i].len==dis[y]){
tmp.push_back(y);
dfs(y,cur,mincur);
tmp.pop_back();
}
}
}
int main(){
memset(head,-1,sizeof head);
int x,y,z;
cin>>c>>n>>t>>m;
c/=2;
for(int i=1;i<=n;i++) cin>>nums[i];
for(int i=1;i<=m;i++){
cin>>x>>y>>z;
add(x,y,z);
add(y,x,z);
}
dij();
//cout<<dis[t]<<endl;
tmp.push_back(0);
dfs(0,0,0);
cout<<send<<" ";
cout<<"0";
for(int i=1;i<path.size();i++) cout<<"->"<<path[i];
cout<<" "<<bring;
return 0;
}
标签:cnt,Management,PAT,int,bian,vis,Bike,mincur,dis 来源: https://www.cnblogs.com/xhy666/p/16245328.html