To solve the problem of finding the minimum cost Geek has to pay to reach each of the towns from town 1, we can break the problem down into a series of steps using dynamic programming and prime factorization.
Step-by-Step Reasoning:
-
Prime Factorization with Sieve of Eratosthenes:
- Objective: Precompute the smallest prime factor (SPF) for each number up to 100,000. This helps in efficiently finding the prime factors of any number in the towns.
- Implementation: Use the Sieve of Eratosthenes to populate the SPF array.
-
Precompute Prime Factors for Each Road:
- Objective: Determine the prime factors for each road in every town.
- Implementation: For each road in a town, divide the number repeatedly by its smallest prime factor until it reduces to 1, collecting all unique prime factors in the process.
-
Initialize Minimum Cost for the First Town:
- Objective: For town 1, set up a map where each prime factor maps to the minimum cost of taking any road in town 1 that includes that prime.
- Implementation: Iterate through each road in town 1 and update the
prime_min_prev array with the minimum cost for each prime factor.
-
Dynamic Programming Across Towns:
- Objective: For each subsequent town, determine the minimum cost to reach it by considering the minimum costs associated with its prime factors from the previous town.
- Implementation:
- For each town, collect all the unique prime factors from its roads.
- Calculate the minimum value from the
prime_min_prev corresponding to these prime factors.
- Update the
prime_min_prev for the next iteration by considering the current town's road costs.
-
Handling Edge Cases:
- If no valid connection exists between towns (i.e., no common prime factor between roads), set the cost to
-1 for that town.
-
Return the Results:
- After processing all towns, return the array of minimum costs to reach each town.
Final Implementation:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Function to compute sieve of smallest prime factors up to max_n
vector<int> sieve(int max_n) {
vector<int> SPF(max_n + 1, 0);
for(int i=2;i<=max_n;i++) SPF[i]=i;
for(int i=2;i*i <= max_n;i++) {
if(SPF[i] == i) {
for(int j=i*i;j<=max_n;j+=i) {
if(SPF[j] == j) SPF[j] = i;
}
}
}
return SPF;
}
// Function to get unique prime factors of x using SPF
vector<int> get_prime_factors(int x, const vector<int> &SPF) {
vector<int> factors;
if(x < 2) return factors;
while(x >1){
int p = SPF[x];
factors.push_back(p);
while(x % p ==0){
x /= p;
}
}
// Remove duplicates by sorting
// Already unique since we divided out all instances
return factors;
}
vector<int> minCost(int n, int m, vector<vector<int>> &town) {
const int MAX_P = 100000;
const long long INF = 1e18;
// Step1: sieve
vector<int> SPF = sieve(MAX_P);
// Step2: get prime factors for all roads
// road_factors[i][j] = vector of primes for town i, road j
vector<vector<vector<int>>> road_factors(n, vector<vector<int>>(m, vector<int>()));
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
road_factors[i][j] = get_prime_factors(town[i][j], SPF);
}
}
// Step3: initialize prime_min_prev
vector<long long> prime_min_prev(MAX_P +1, INF);
for(int j=0;j<m;j++) {
for(auto p: road_factors[0][j]) {
prime_min_prev[p] = min(prime_min_prev[p], (long long)town[0][j]);
}
}
// Step4: iterate over towns and compute answers
vector<int> answer(n-1, -1);
for(int i=1;i<n;i++) {
// Collect unique primes in town i
vector<int> primes_in_town;
for(int j=0;j<m;j++) {
for(auto p: road_factors[i][j]) {
primes_in_town.push_back(p);
}
}
// Remove duplicates
sort(primes_in_town.begin(), primes_in_town.end());
primes_in_town.erase(unique(primes_in_town.begin(), primes_in_town.end()), primes_in_town.end());
// Compute min_val
long long min_val = INF;
for(auto p: primes_in_town) {
if(prime_min_prev[p] < min_val){
min_val = prime_min_prev[p];
}
}
// Set answer
if(min_val < INF){
answer[i-1] = (int)min_val;
}
else{
answer[i-1] = -1;
}
// Build prime_min_new for next iteration
vector<long long> prime_min_new(MAX_P +1, INF);
for(int j=0;j<m;j++) {
for(auto p: road_factors[i][j]) {
if(prime_min_prev[p] < INF){
long long temp = prime_min_prev[p] + (long long)town[i][j];
if(temp < prime_min_new[p]){
prime_min_new[p] = temp;
}
}
}
}
// Update prime_min_prev
prime_min_prev = move(prime_min_new);
}
return answer;
}
};
Explanation of the Implementation:
-
Sieve of Eratosthenes (sieve function):
- Computes the smallest prime factor (SPF) for every number up to
100,000.
-
Prime Factor Extraction (get_prime_factors function):
- For each road value, it extracts all unique prime factors using the precomputed SPF array.
-
Initialization:
- For the first town, it initializes the
prime_min_prev array with the minimum costs associated with each prime factor.
-
Processing Each Town:
- For each subsequent town, it collects all unique prime factors from its roads.
- Computes the minimum value among the previously stored minimums for these primes.
- Updates the answer for the current town based on this minimum value.
- Prepares the
prime_min_new array for the next town by considering the current road costs.
-
Edge Handling:
- If there's no valid connection (i.e., no common prime factor), it assigns
-1 to indicate that the town is unreachable.
-
Final Output:
- After processing all towns, it returns the
answer array containing the minimum costs to reach each town from town 1.
Complexity Analysis:
-
Time Complexity:
- The sieve runs in
O(MAX_P log log MAX_P) where MAX_P = 100,000.
- The main loop runs in
O(n * m * log MAX_P) where n * m ≤ 100,000.
-
Space Complexity:
- The space required is mainly for the SPF array and the prime factors storage, which is
O(MAX_P + n * m).
Final Notes:
This approach efficiently calculates the minimum cost by leveraging the properties of prime factors and dynamic programming. It ensures that the solution is optimized for the given constraints, making it suitable for large inputs.