【PAT A1072】Gas Station
程序员文章站
2022-06-07 11:44:46
...
思路
这题当时看题看的一脸懵,说实话也不知道是我英语水平有问题还是他这题目语法有问题。其实题目就是让你给加油站选址,加油站尽量距离最近的人家尽可能远,否则就选择平均距离最小的,不多说直接上代码。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define INF 1000000000
#define MAX 1020
int N, M, K, range;
int dist[MAX], G[MAX][MAX] = {0}, visited[MAX];
int str2int(char *str){
int output = 0, begin = 0;
if(str[0] == 'G')
begin = 1;
while(begin < strlen(str)){
output = output * 10 + (str[begin] - '0');
begin++;
}
if(str[0] == 'G')
output += N;
return output;
}
void init(){
fill(dist, dist + MAX, INF);
fill(visited, visited + MAX, 0);
}
int main(){
scanf("%d%d%d%d", &N, &M, &K, &range);
for(int i = 0; i < K; i++){
getchar();
char a[10], b[10];int d;
scanf("%s %s %d", a, b, &d);
int from = str2int(a), to = str2int(b);
G[from][to] = G[to][from] = d;
}
double minDist = 0, meanDist = INF;
int bestLoc;
for(int i = 1; i <= M; i++){
init();//重置数组
dist[N + i] = 0;//station到自己的距离为0
double tmpMin = -1, tmpMean = 0.0;//记录如果在当前节点建站的最小距离和平均距离
int farest = 0;//存放距离加油站最远的距离
for(int j = 1; j <= N + M; j++){
int min = INF, minIndex = -1;
//找未访问的距离最近者
for(int l = 1; l <= N + M; l++){
if(visited[l] == 0 && dist[l] < min){
min = dist[l];
minIndex = l;
}
}
if(minIndex == -1)
break;
//minIndex <= N是只记录到house的平均距离和最小距离和最远距离
if(tmpMin == -1 && minIndex <= N){
tmpMin = min;
}
visited[minIndex] = 1;
if(minIndex <= N)
tmpMean += min;
if(min > farest && minIndex <= N)
farest = min;
//更新距离
for(int l = 1; l <= N + M; l++){
if(G[minIndex][l] != 0 && visited[l] == 0){
if(G[minIndex][l] + dist[minIndex] < dist[l])
dist[l] = G[minIndex][l] + dist[minIndex];
}
}
}
//不能cover到所有的house
if(farest > range)
continue;
tmpMean /= N;
//最小距离小于记录的最小距离,则更新结果
if(minDist < tmpMin){
minDist = tmpMin;
meanDist = tmpMean;
bestLoc = i;
}
//如果最小距离相等则比较平均距离,由于测试顺序是按index的,所以不用管index
else if(minDist == tmpMin && meanDist > tmpMean){
meanDist = tmpMean;
bestLoc = i;
}
//printf("number %d station, min %lf, mean %.1lf\n", i, tmpMin, tmpMean);
}
if(meanDist == INF)
{
printf("No Solution\n");
return 0;
}
printf("G%d\n", bestLoc);
printf("%.1lf %.1lf\n", minDist, meanDist);
return 0;
}
上一篇: ceshi解决方案
下一篇: 习题2.3-数列求和-加强版-编程题