codeforces 1140D(區間dp/思維題)
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.
Calculate the minimum weight among all triangulations of the polygon.
InputThe first line contains single integer nn (3≤n≤5003≤n≤500) — the number of vertices in the regular polygon.
OutputPrint one integer — the minimum weight among all triangulations of the given polygon.
3output Copy
6input Copy
4output Copy
18Note
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
In the first example the polygon is a triangle, so we don‘t need to cut it further, so the answer is 1⋅2⋅3=61⋅2⋅3=6.
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 1−31−3 so answer is 1⋅2⋅3+1⋅3⋅4=6+12=181⋅2⋅3+1⋅3⋅4=6+12=18.
題意:給你一個有n個頂點的正多邊形,頂點編號從1-n,現在你要把這個正多邊形劃分為三角形,而且每個三角形的面積都不相交,三角形的花費定義為三角形頂點編號的乘積,問花費的最少代價。
思路:簡單的區間dp,對於dp[i][j]的求解,我們只要以i,j為底邊,枚舉頂點k(i<k<j),劃分出三角形(i,j,k),然後我們就將要求的值分為dp[i][k]+dp[k][j]+三角形(i,j,k)的花費,找到花費最小的值就可以了。
如果敏感的話應該可以發現對於正多邊形的劃分,就是劃分為(1,2 ,3),(1,3,4),(1,4,5)。。。。,(1,n-1,n)時它的花費是最小的,那麽最後的答案就是2*3+3*4+4*5+.......+(n-1)*n。
#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
codeforces 1140D(區間dp/思維題)