Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : 10304 - Optimal Binary Search Tree
Source : UVA Online Judge
Category : Dynamic Programing
Algorithm : Optimal Binary Search Tree
Verdict : Accepted
- #include <bits/stdc++.h>
-
- using namespace std;
-
- #define ll long long
-
- static const int maxn = 250 + 5;
-
- ll dp[maxn][maxn];
- bool vis[maxn][maxn];
- int tfre;
- ll fre[maxn];
- int cumsum[maxn];
-
- void preCalc()
- {
- cumsum[0] = fre[0];
- for (int i = 1; i < tfre; i++) cumsum[i] = cumsum[i-1] + fre[i];
- }
-
- ll getCum(int i, int j)
- {
- ll sum = cumsum[j];
- if (i-1 >= 0) sum -= cumsum[i-1];
- return sum;
- }
-
- ll solve(int start, int endd)
- {
- if (start >= endd) return 0;
- ll &ret = dp[start][endd];
- bool &v = vis[start][endd];
- if (v == 1) return ret;
- v = 1;
- ll mini = 1e17 + 10;
- for (int i = start; i <= endd; i++)
- {
- ll go = getCum(start, i-1) + getCum(i+1, endd) + solve(start, i-1) + solve(i+1, endd);
- if (go < mini) mini = go;
- }
- return ret = mini;
- }
-
- int main()
- {
- while (scanf("%d", &tfre) == 1)
- {
- for (int i = 0; i < tfre; i++) scanf("%lld", fre+i);
- preCalc();
- memset(vis, 0, sizeof vis);
- ll ans = solve(0, tfre-1);
- printf("%lld\n", ans);
- }
- }
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.