Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- DAA - IMPLEMENTATION PROJECT
- Done By: IMT2019525 VIJAY JAISANKAR, IMT2019049 MADDULA DHANUSH
- */
- #include<bits/stdc++.h>
- using namespace std;
- /*
- This is the dp table.
- At the end of the program,dp[i][j] will contain the minimum cost of merging the slimes in the segment i,...,j
- */
- long long int dp[401][401];
- /*
- This is the array containing partial sum/prefix sum values.
- After preprocessing, pfsum[i] = arr[0] + arr[1] + ... + arr[i],
- (where i is the input array)
- */
- long long int pfsum[401];
- /*
- This is the input array containing the slime values.
- */
- long long int arr[401];
- /*
- A dummy variable used to store the theoretical maximum value possible in this context
- */
- long long int INF = 1LL<<60;
- int main(){
- /*
- n is the size of the input.
- */
- int n;
- cin>>n;
- /*
- Constructing the prefix sum array while taking the input:
- We have desctibed this process in the paper - note that this whole process is O(n)
- */
- for(int i=0;i<n;i++){
- cin>>arr[i];
- if(i==0) pfsum[i] = arr[i];
- else pfsum[i] = pfsum[i-1] + arr[i];
- }
- /*
- Setting up base cases and initialising the dp[][] array:
- Base cases: dp[i][i] = 0 - this is to facilitate the vacuous step of the recurrence
- Otherwise, as we are going to minimize the dp values, we set them to the aforementioned INF
- */
- for(int i=0;i<n;i++){
- for(int j=0;j<n;j++){
- if(i==j) dp[i][j] = 0;
- else dp[i][j] = INF;
- }
- }
- /*
- Implementing the recurrence in a bottom-up fashion:
- From the dependency graph, this is a way to build the DP in a bottom-up way.
- We can clearly see the recurrence in action while setting dp[l][r]
- Note that, as we need the non-recurisive merging work while considering every eligible value of k, we pre-store it.
- */
- for(int l=n-1;l>=0;l--){
- for(int r=l+1;r<n;r++){
- long long int pfdiff = pfsum[r] - pfsum[l-1];
- for(int k=l;k<r;k++){
- dp[l][r] = min(dp[l][r],dp[l][k] + dp[k+1][r] + pfdiff); // Testing out candidate values of k
- }
- }
- }
- /*
- Outputting the value:
- From the definition of dp[i][j], we need to print out dp[0][n-1] as we follow 0-based indexing.
- */
- cout<<dp[0][n-1]<<"\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement