URAL 1205 By the Underground or by Foot (建图 + Dijkstra迪杰斯特拉算法)

#include <stdio.h>
#include <math.h>
#define INF (1 << 30)

double footSpeed, undergroundSpeed;
int numOfStations;
int start, end;
typedef struct Coordinates{
	double x;
	double y;
}Cooridnates;
Coordinates CoordinatesArray[300];
double timeArray[300][300];
double minTimeArray[300];
int isMinTimeFound[300];
int stack[300];
int top;
int pre[300];

double getDistance(Coordinates one, Coordinates another){
	double deltaX = one.x - another.x;
	double deltaY = one.y - another.y;
	return sqrt(deltaX * deltaX + deltaY * deltaY);
}

void Dijkstra(){
	int to;
	for (to = 1; to <= end; to++)
		minTimeArray[to] = timeArray[start][to];

	isMinTimeFound[start] = 1;

	int numOfMinTimesFound;
	for (numOfMinTimesFound = 2; numOfMinTimesFound <= end; numOfMinTimesFound){
		double minTime = INF;
		int location;
		for (to = 1; to <= end; to++)
			if (isMinTimeFound[to] == 0 && minTimeArray[to] < minTime){
				minTime = minTimeArray[to];
				location = to;
			}
		if (location == end)
			return;
		isMinTimeFound[location] = 1;
		for (to = 1; to <= end; to++)
			if (isMinTimeFound[to] == 0 && minTime + timeArray[location][to] < minTimeArray[to]){
				minTimeArray[to] = minTime + timeArray[location][to];
				pre[to] = location;
			}
	}
}

int main(){
	freopen("input.txt", "r", stdin);

	scanf("%lf%lf", &footSpeed, &undergroundSpeed);

	scanf("%d", &numOfStations);
	int station;
	for (station = 1; station <= numOfStations; station++){
		Coordinates tempCoordinates;
		scanf("%lf%lf", &tempCoordinates.x, &tempCoordinates.y);
		CoordinatesArray[station] = tempCoordinates;
	}

	int from, to;
	for (from = 1; from <= numOfStations; from++)
		for (to = from + 1; to <= numOfStations; to++)
			//默认可以从一个车站步行到另一个车站
			timeArray[from][to] = timeArray[to][from] = getDistance(CoordinatesArray[from], CoordinatesArray[to]) / footSpeed;

	while (scanf("%d%d", &from, &to) != EOF && (from != 0 && to != 0) )
		timeArray[from][to] = timeArray[to][from] = getDistance(CoordinatesArray[from], CoordinatesArray[to]) / undergroundSpeed;
	
	start = numOfStations + 1;
	end = numOfStations + 2;
	scanf("%lf%lf", &CoordinatesArray[start].x, &CoordinatesArray[start].y);
	scanf("%lf%lf", &CoordinatesArray[end].x, &CoordinatesArray[end].y);
	int location;
	for (location = 1; location <= end; location++){
		timeArray[start][location] = timeArray[location][start] = getDistance(CoordinatesArray[start], CoordinatesArray[location]) / footSpeed;
		timeArray[end][location] = timeArray[location][end] = getDistance(CoordinatesArray[end], CoordinatesArray[location]) / footSpeed;
	}

	Dijkstra();
	printf("%.10lf\n", minTimeArray[end]);

	int preLocation = pre[end];
	while (preLocation != 0){
		stack[++top] = preLocation;
		preLocation = pre[preLocation];
	}

	printf("%d", top);
	while (top > 0)
		printf(" %d", stack[top--]);
	printf("\n");

	return 0;
}


 

你可能感兴趣的:(by,dijkstra,the,迪杰斯特拉,o,ural,1205,Underground)