codeforces 1140D(區間dp/思惟題)

D. Minimum Triangulation
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a regular polygon with nn vertices labeled from 11 to nn in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the total area of all triangles is equal to the area of the given polygon. The weight of a triangulation is the sum of weigths of triangles it consists of, where the weight of a triagle is denoted as the product of labels of its vertices.ide

Calculate the minimum weight among all triangulations of the polygon.spa

Input

The first line contains single integer nn (3n5003≤n≤500) — the number of vertices in the regular polygon.code

Output

Print one integer — the minimum weight among all triangulations of the given polygon.blog

Examples
input
Copy
3
output
Copy
6
input
Copy
4
output
Copy
18
Note

According to Wiki: polygon triangulation is the decomposition of a polygonal area (simple polygon) PP into a set of triangles, i. e., finding a set of triangles with pairwise non-intersecting interiors whose union is PP.ci

In the first example the polygon is a triangle, so we don't need to cut it further, so the answer is 123=61⋅2⋅3=6.input

In the second example the polygon is a rectangle, so it should be divided into two triangles. It's optimal to cut it using diagonal 131−3 so answer is 123+134=6+12=181⋅2⋅3+1⋅3⋅4=6+12=18.it

 題意:給你一個有n個頂點的正多邊形,頂點編號從1-n,如今你要把這個正多邊形劃分爲三角形,並且每一個三角形的面積都不相交,三角形的花費定義爲三角形頂點編號的乘積,問花費的最少代價。io

 

思路:簡單的區間dp,對於dp[i][j]的求解,咱們只要以i,j爲底邊,枚舉頂點k(i<k<j),劃分出三角形(i,j,k),而後咱們就將要求的值分爲dp[i][k]+dp[k][j]+三角形(i,j,k)的花費,找到花費最小的值就能夠了。class

若是敏感的話應該能夠發現對於正多邊形的劃分,就是劃分爲(1,2 ,3),(1,3,4),(1,4,5)。。。。,(1,n-1,n)時它的花費是最小的,那麼最後的答案就是2*3+3*4+4*5+.......+(n-1)*n。test

 

#include<cstdio> #include<algorithm>
using namespace std; const int INF=1e9; int dp[510][510]; int main(){ int n; scanf("%d",&n); for(int j=2;j<=n-1;j++){ for(int i=1;i+j<=n;i++){ dp[i][i+j]=INF;//找最小值,先初始化爲無窮大 
            for(int k=i+1;k<i+j;k++){ dp[i][i+j]=min(dp[i][i+j],dp[i][k]+dp[k][i+j]+i*(i+j)*k); } } } printf("%d\n",dp[1][n]); return 0; } 
View Code
#include<cstdio> #include<algorithm>
using namespace std; const int INF=1e9; int main(){ int n; scanf("%d",&n); int ans=0; for(int i=3;i<=n;i++) ans+=i*(i-1); printf("%d\n",ans); return 0; }
View Code
相關文章
相關標籤/搜索