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][j]. The jth road of town [i] is connected to the kth road of town[i+1] iff GCD (town[i][j], 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 * 104 4 <= n * m <= 105 1 <= town[i][j] <= 105//{ Driver Code Starts #include <bits/stdc++.h> using namespace std;
class Matrix { public: template static void input(vector<vector> &A, int n, int m) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d ", &A[i][j]); } } }
template <class T> static void print(vector<vector<T>> &A) { for (int i = 0; i < A.size(); i++) { for (int j = 0; j < A[i].size(); j++) { cout << A[i][j] << " "; } cout << endl; } }};
class Array { public: template static void input(vector &A, int n) { for (int i = 0; i < n; i++) { scanf("%d ", &A[i]); } }
template <class T> static void print(vector<T> &A) { for (int i = 0; i < A.size(); i++) { cout << A[i] << " "; } cout << endl; }};
// } Driver Code Ends
class Solution { public: vector minCost(int n, int m, vector<vector> &town) { // code here } };
//{ Driver Code Starts.
int main() { int t; scanf("%d ", &t); while (t--) {
int n; scanf("%d", &n); int m; scanf("%d", &m); vector<vector<int>> town(n, vector<int>(m)); Matrix::input(town, n, m); Solution obj; vector<long long> res = obj.minCost(n, m, town); Array::print(res); } - Assistant