PAT 甲级 1072 Gas Station
结点 string
转成 int
建图,对每个可能点SPFA。
#include <bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=1020;
int n,m,k,ds;
int to_num(string s){
int ret=0;size_t idx=0;
if(s[0]=='G') ++idx;
for(;idx<s.size();++idx){
ret=ret*10+s[idx]-'0';
}
if(s[0]=='G') ret+=n;
return ret;
}
struct Edge{
int to,cost;
Edge(int _to=0,int _cost=INF):to(_to),cost(_cost) {}
};
vector<Edge> graph[MAXN];
int dis[MAXN],in_q[MAXN];
void SPFA(int s)
{
memset(dis,INF,sizeof(dis));
memset(in_q,false,sizeof(in_q));
dis[s]=0;
queue<int> q;
q.push(s),in_q[s]=true;
while(!q.empty()){
int now=q.front();
q.pop(),in_q[now]=false;
for(auto edge:graph[now]){
int to=edge.to,cost=edge.cost;
if(dis[to]>dis[now]+cost){
dis[to]=dis[now]+cost;
if(!in_q[to]) q.push(to),in_q[to]=true;
}
}
}
}
int main() {
cin>>n>>m>>k>>ds;
string x,y;int z;
for(int i=0;i<k;++i){
cin>>x>>y>>z;
graph[to_num(x)].emplace_back(to_num(y),z);
graph[to_num(y)].emplace_back(to_num(x),z);
}
int ans_total_dis=0,ans_id=0,ans_min_dis=0;
for(int i=1;i<=m;++i){
SPFA(i+n);
bool is_ok=true;int total_dis=0,min_dis=INF;
for(int j=1;j<=n;++j){
if(dis[j]>ds) {is_ok=false;break;}
if(dis[j]<min_dis) min_dis=dis[j];
total_dis+=dis[j];
}
if(is_ok&&(min_dis>ans_min_dis||
(min_dis==ans_min_dis&&ans_total_dis>total_dis))){
ans_total_dis=total_dis;
ans_id=i;
ans_min_dis=min_dis;
}
}
if(ans_id==0) cout<<"No Solution";
else{
printf("G%d\n%.1lf %.1lf",
ans_id,ans_min_dis*1.0,ans_total_dis*1.0/n);
}
}