You have been given a 2D array town of size n x m, where each town contains m roads, and…
- User
You have been given a 2D array town of size n x m, where each town contains m roads, and the cost to travel in town i from the jth road is town[i][jl. The jth road of town[i] is connected to the kth road of town[i+1] iff GCD(town[i|[jl, town[i+1][k]) > 1. Geek lives in town 1 and wants to find the minimum cost he has to pay to reach other n-1 towns. Help him to find the minimum cost. If it is not possible to reach any town, the cost is -1. You need to return an array of size n-1, where the ith element is the minimum cost to reach ith+1 town. Note: GCD(a, b) is the greatest common divisor of a and b. Note: 1-based indexing is used. Example 1: Input: n = 3 m = 3 town = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output: [2, 6] Explanation: Geek can reach town 2 from town 1 by paying 2 units of cost using path {town[1][2]}. He can reach town 3 from town 1 by paying 6 units of cost using paths {town[1][2] -> town[2][1]}.Example 2: Input: n = 2 m = 2 town = [[1, 2], [3, 5]] Output: [-1] Explanation: Geek can't reach town 2 from town 1, as there is no path which connects town 1 and town 2. Your Task: You don't need to read input or print anything. Your task is to complete the function minCost() which takes the 2D array town[] and its size n and m, as input parameters and returns the array which contains the minimum cost to reach other n-1 towns. Constraints: 2<=n, m <= 5 * 10^4 4<=n* m<= 10^5 1 <= town[i][j] <= 10^5. class Solution { public: vector minCost(int n, int m, vector<vector> &town) { // write code here } };
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.