|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Gap Strategy Implementation for Minimum Score Triangulation |
| 4 | + int solve(vector<int>& v) { |
| 5 | + int n = v.size(); // Number of vertices in the polygon |
| 6 | + |
| 7 | + // DP table where dp[i][j] represents the minimum score for triangulating the segment [i, j] |
| 8 | + vector<vector<int>> dp(n, vector<int>(n, 0)); |
| 9 | + |
| 10 | + // Outer loop controls the gap between i and j |
| 11 | + // Gap of 2 means the segment [i, j] has at least 3 vertices, enough to form a triangle |
| 12 | + for (int gap = 2; gap < n; gap++) { |
| 13 | + // Inner loop iterates over all valid starting indices i for a given gap |
| 14 | + for (int i = 0; i + gap < n; i++) { |
| 15 | + int j = i + gap; // Calculate the ending index j based on the gap |
| 16 | + |
| 17 | + dp[i][j] = INT_MAX; // Initialize dp[i][j] to the maximum value |
| 18 | + |
| 19 | + // Iterate over all possible middle vertices (k) between i and j |
| 20 | + for (int k = i + 1; k < j; k++) { |
| 21 | + // Calculate the score of forming a triangle (i, k, j) |
| 22 | + // Add the scores of solving the two subproblems [i, k] and [k, j] |
| 23 | + dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + v[i] * v[k] * v[j]); |
| 24 | + } |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + // The final result is stored in dp[0][n-1], which represents the entire polygon |
| 29 | + return dp[0][n - 1]; |
| 30 | + } |
| 31 | + |
| 32 | + // Main function to calculate the minimum score triangulation |
| 33 | + int minScoreTriangulation(vector<int>& values) { |
| 34 | + int n = values.size(); // Number of vertices in the polygon |
| 35 | + return solve(values); // Call the gap strategy function |
| 36 | + } |
| 37 | +}; |
0 commit comments