PAT甲级1072 Gas Station (30 分)题解

PAT甲级1072 Gas Station (30 分)题解_第1张图片PAT甲级1072 Gas Station (30 分)题解_第2张图片PAT甲级1072 Gas Station (30 分)题解_第3张图片
\quad 这个题要求每个加油站到所有居住地的最短距离,最长距离和平均距离。其中最长距离用于判断该加油站位置是否符合要求,最短距离和平均距离需要输出并保留一位小数。我用1到N表示居民居住地,N+1到N+M+1表示加油站,这样计算出某个加油站到其他地点的距离,保存在数组中,再进行处理。
\quad 在所有位置合法的加油站中,以最大化该加油站到居住地的最短距离为第一标准,最小化加油站到居住地的平均距离为第二标准输出即可,若没有合法的结果则输出"No Solution"。

#include 
#include 
#include 
#include 
#include 
using namespace std;

const int maxn = 1011;
vector<pair<int, int> > E[maxn];
int vis[maxn], dis[maxn];
int N, M, K, Ds;
struct Station
{
     
	int id, minDis;
	float avg;
	bool legal;
}station[maxn];
bool cmp(const Station &s1, const Station &s2)
{
     
	if(s1.minDis!=s2.minDis) return s1.minDis>s2.minDis;
	else if(s1.avg!=s2.avg) return s1.avg<s2.avg;
	else return s1.id<s2.id;
}
void Dijistra(int s)
{
     
	memset(vis, 0, sizeof(vis));
	fill(dis, dis+maxn, 0x3f3f3f3f);
	dis[s] = 0;
	priority_queue<pair<int, int> > q;
    q.push({
     0, s});
	while(!q.empty())
	{
     
		int u = q.top().second;
		q.pop();
		if(vis[u]==1) continue;
		vis[u] = 1;
		for (int i = 0; i < E[u].size(); ++i)
		{
     
		 	int v = E[u][i].first, w = E[u][i].second;
		 	if(dis[v]>dis[u]+w)
		 	{
     
		 		dis[v] = dis[u]+w;
		 		if(vis[v]==0) q.push({
     -dis[v], v});
		 	}
		}
	}
    station[s].id=s, station[s].minDis=0x3f3f3f3f, station[s].legal=true;
    int sum = 0;
    for (int i = 1; i <= N; ++i)
    {
     
    	if(dis[i]>Ds) station[s].legal = false;
    	sum += dis[i];
    	station[s].minDis = min(station[s].minDis, dis[i]);
    }
    station[s].avg = sum*1.0/N;
}
int main(int argc, char const *argv[])
{
     
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
	cin >> N >> M >> K >> Ds;
    while(K--)
    {
     
    	string a, b; int w;
    	cin >> a >> b >> w;
    	int u, v;
    	if(a[0]=='G'){
     
    		sscanf(a.c_str(), "G%d", &u);
    		u += N;
    	}
    	else sscanf(a.c_str(), "%d", &u);
    	if(b[0]=='G'){
     
    		sscanf(b.c_str(), "G%d", &v);
    		v += N;
    	}
    	else sscanf(b.c_str(), "%d", &v);
    	E[u].push_back({
     v, w});
    	E[v].push_back({
     u, w});
    }
    for (int i = N+1; i <= N+M; ++i) Dijistra(i);
    sort(station+N+1, station+N+M+1, cmp);
	bool flag = false;
	for(int i = N+1; i <= N+M; i++)
	{
     
		if(station[i].legal)
		{
     
			cout << "G" << station[i].id-N << endl;
			printf("%.1f %.1f\n", 1.0*station[i].minDis, station[i].avg);
			flag = true;
			break;
		}
	}
	if(!flag) cout << "No Solution" << endl;
	return 0;
}

你可能感兴趣的:(PAT甲级1072,Gas,Station,(30,分)题解,1072,Gas,Station,(30,分),最短路)