如何用C#实现CCC 2018 J3城市间距离计算程序?
Fix for C# Code to Solve CCC 2018 J3 "Are We There Yet?"
Problem Overview
The task requires calculating pairwise distances between 5 cities, given consecutive distances between adjacent cities. The expected output is a 5x5 grid where each entry represents the distance from one city to another.
Issues with Your Original Code
- Return Type Mismatch: The method returns an
int, but we need a multi-line string for the distance grid output. - Incorrect List Initialization:
List<int> cities = new List<int> {5};creates a list with one element (5) instead of a list sized for 5 cities. - Early Returns: Multiple
returnstatements inside loops halt execution before completing all distance calculations. - Index Errors: Accessing
cities[i-1]wheni=0causes out-of-bounds errors, and references likecities[i+5]are invalid for a 5-city list. - Confused Logic: The code mixes cumulative distance building and pairwise computation, leading to incorrect results.
Corrected Code
/// GET/api/J3/DistanceCalculator/{distance1}/{distance2}/{distance3}/{distance4} /// api/J3/DistanceCalculator/3/10/12/5 /// Output: /// 0/3/13/25/30 /// 3/0/10/22/27 /// 13/10/0/12/17 /// 25/22/12/0/5 /// 30/27/17/5/0 /// </example> // GET api/J3/DistanceCalculator/{distance1}/{distance2}/{distance3}/{distance4}/ [HttpGet] [Route("api/J3/DistanceCalculator/{distance1}/{distance2}/{distance3}/{distance4}")] public string DistanceCalculator(int distance1, int distance2, int distance3, int distance4) { // Build cumulative distances from city 0 to each city int[] cityDistances = new int[5]; cityDistances[0] = 0; cityDistances[1] = distance1; cityDistances[2] = cityDistances[1] + distance2; cityDistances[3] = cityDistances[2] + distance3; cityDistances[4] = cityDistances[3] + distance4; List<string> resultLines = new List<string>(); // Generate each line of the distance grid for (int startCity = 0; startCity < 5; startCity++) { List<string> lineEntries = new List<string>(); for (int endCity = 0; endCity < 5; endCity++) { // Calculate distance between start and end city (absolute difference) int distance = Math.Abs(cityDistances[endCity] - cityDistances[startCity]); lineEntries.Add(distance.ToString()); } // Join entries with '/' and add to result resultLines.Add(string.Join("/", lineEntries)); } // Join all lines with newline characters return string.Join("\n", resultLines); }
Key Improvements
- Cumulative Distance Array: First compute total distances from city 0 to every other city. Pairwise distance becomes the absolute difference between two cumulative values.
- Proper Return Type: The method now returns a
stringmatching the required output format. - Clear Nested Loops: Outer loop iterates over starting cities, inner loop calculates distances to all other cities, building each output line.
- Correct Formatting: Uses
string.Jointo create/-separated entries per line and\nto separate lines in the final output.
内容的提问来源于stack exchange,提问作者Bea
相关产品推荐
相关产品推荐

