
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Score Triangulation of Polygon in C++
Suppose we have a value N, consider a convex N-sided polygon with vertices labelled A[0], A[i], ..., A[N-1] are in clockwise order. Now suppose we want to triangulate the polygon into N-2 triangles. For each triangle, the value of that triangle is the product of the labels of the vertices, and the total score of the triangulation will be the sum of these values over all N-2 triangles in the triangulation. We have to find the smallest possible total score that we can achieve with some triangulation of the polygon. So if the input is [1,2,3], then the output will be 6, as the polygon is already triangulated, and the score of the only triangle is 6.
To solve this, we will follow these steps −
Create a matrix dp of size 50 x 50, fill this with 0
n := size of the given array
-
for l in range n to n
-
for i := 0, j := l – 1, when j < n, increase i and j by 1
-
for k in range i + 1 to j – 1
-
if of dp[i, j] = 0, then
dp[i, j] := minimum of inf and dp[i, k] + dp[k, j] + A[i] * A[j] * A[k]
otherwise dp[i, j] := minimum of dp[i,j] and dp[i, k] + dp[k, j] + A[i] * A[j] * A[k]
-
-
-
return dp[0, n – 1]
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int minScoreTriangulation(vector<int>& A) { lli dp[50][50]; for(int i = 0; i < 50; i++){ for(int j = 0; j < 50; j++){ dp[i][j] = 0; } } int n = A.size(); for(int l = 3; l <= n; l++){ for(int i = 0, j = l - 1; j < n;i++, j++){ for(int k = i + 1; k < j; k++){ dp[i][j] = min(dp[i][j] == 0?INT_MAX : dp[i][j], dp[i][k] + dp[k][j] + A[i] * A[k] * A[j]); } } } return dp[0][n - 1]; } }; main(){ vector<int> v1 = {1,2,3}; Solution ob; cout << (ob.minScoreTriangulation(v1)); }
Input
[1,2,3]
Output
6