Tree Construction
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1708 Accepted Submission(s): 964
Problem Description
Consider a two-dimensional space with a set of points (xi, yi) that satisfy xi < xj and yi > yj for all i < j. We want to have them all connected by a directed tree whose edges go toward either right (x positive) or upward (y positive). The figure below shows an example tree.
Write a program that finds a tree connecting all given points with the shortest total length of edges.
Write a program that finds a tree connecting all given points with the shortest total length of edges.
Input
The input begins with a line that contains an integer n (1 <= n <= 1000), the number of points. Then n lines follow. The i-th line contains two integers xi and yi (0 <= xi, yi <= 10000), which give the coordinates of the i-th point.
Output
Print the total length of edges in a line.
Sample Input
5 1 5 2 4 3 3 4 2 5 1 1 10000 0
Sample Output
12 0
题意:有n个点,满足(i > j & xi > xj & yi < yj),现在要把这n个点连接起来,规定只能用直线,且直线只能向上或向右延伸,求最短长度。
题解:设dp[i][j]为将i和j所有点连接起来的最小费用,则dp[i][j] = min{dp[i][k] + dp[k + 1][j] + a[k].y - a[j].y + a[k + 1].x - a[i].x};
这种题目见多了直接就想到使用四边形优化成O(n^2)了。。不知道以后见到题目会不会在四边形优化上还要再套个优化??
AC代码
#include <stdio.h> #include <iostream> #include <string> #include <queue> #include <map> #include <vector> #include <algorithm> #include <string.h> #include <cmath> using namespace std; const int maxn = 1111; int s[maxn][maxn], dp[maxn][maxn], inf = 1 << 29; struct node{ int x, y; }p[maxn]; int main(){ int n; while(scanf("%d", &n) != EOF){ for(int i = 1; i <= n; i++) scanf("%d %d", &p[i].x, &p[i].y); memset(s, 0, sizeof(s)); for(int i = 1; i <= n + 1; i++){ for(int j = 1; j <= n + 1; j++){ dp[i][j] = inf; s[i][j] = 0; } s[i][i] = i; dp[i][i] = 0; } for(int i = n; i >= 1; i--){ for(int j = i + 1; j <= n; j++){ for(int k = s[i][j - 1]; k <= s[i + 1][j]; k++){ if(dp[i][j] > dp[i][k] + dp[k + 1][j] + p[k].y - p[j].y + p[k + 1].x - p[i].x){ s[i][j] = k; dp[i][j] = dp[i][k] + dp[k + 1][j] + p[k].y - p[j].y + p[k + 1].x - p[i].x; } } } } printf("%d\n", dp[1][n]); } return 0; }