To solve UVa problem 11364 (Parking), it would be beneficial to know that the minimal distance Michael has to walk is simply twice the distance from the farthest store to the nearest store. For example, consider the following setup:
A________B______________C_____D
X______________________________
A, B, C and D are the stores while X is Michael’s car. To get to all the stores and return to his car, Michael would have to walk:
A to B
B to C
C to D
D to C
C to B
B to A
In essense, the total distance he would have traveled would be just twice the distance from A to D.
Consider now the following setup:
A________B______________C_____D
__________________X____________
For Michael to get to all stores and return to his car, he would need to walk:
X to B
B to A
A to B
B to X
X to C
C to D
D to C
C to X
Again, analyzing this series of walks, it is simply twice the distance from A to D.
Hence to compute the minimal distance given a series of stores to walk to, simply find the nearest store and the farthest store, get their difference and then multiply the difference by 2.
Showing posts with label parking. Show all posts
Showing posts with label parking. Show all posts
Monday, December 29, 2008
UVa problem 11364: sample code
001 #include "stdio.h"
002 #include "stdlib.h"
003
004 int main() {
005 char line[100]
006 , ctmp[100]
007 ;
008 int num_tests
009 , num_stores
010 , stores[100]
011 , itmp
012 , max
013 , min
014 , diff
015 , i
016 , j
017 , k
018 , m
019 ;
020
021 fgets(line, 100, stdin);
022 sscanf(line, "%d\n", &num_tests);
023
024 for (i = 0; i < num_tests; i += 1) {
025 fgets(line, 100, stdin);
026 sscanf(line, "%d\n", &num_stores);
027
028 fgets(line, 100, stdin);
029 for (j = 0, m = 0; 1; j += 1) {
030 if (line[j] == '\n' || line[j] == 0) {
031 break;
032 }
033
034 if (line[j] == ' ' || line[j] == '\t') {
035 continue;
036 }
037
038 for (k = 0; 1 ; j += 1, k += 1) {
039 if (line[j] == ' ' || line[j] == '\t' || line[j] == '\n' || line[j] == 0) {
040 break;
041 }
042 ctmp[k] = line[j];
043 }
044 ctmp[k] = 0;
045
046 stores[m] = atoi(ctmp);
047 m += 1;
048 }
049
050 max = 0;
051 min = 99;
052 for (j = 0; j < num_stores; j += 1) {
053 if (stores[j] > max) {
054 max = stores[j];
055 }
056
057 if (stores[j] < min) {
058 min = stores[j];
059 }
060 }
061 diff = max - min;
062 diff *= 2;
063
064 printf("%d\n", diff);
065 }
066
067 return 0;
068 }
Labels:
11364,
code,
parking,
problem,
sample solution,
UVA Online Judge
Subscribe to:
Posts (Atom)