--------------------------------------------------------editorial---------------------------------
dp[i]= if we pic ith element than no of elements can be picked in future , means no of elements picked after picking ith element
next[i] in the best answer calculation next index which is picked after i th index
O(N^2) dynamic programming. DP state is index of last chosen envelope, and loop over for the next envelope.
main thing in this problem is that backtracking of best path while calculating maximum chain ,,,,,
this is a very good way to keep track of path of picked elements
------------------------------------------------------code--------------------------------------------------------------
#include<iostream>
using namespace std;
#include<bits/stdc++.h>
int n;
int next[1000000];
int dp[1000000];
vector<pair<int,int> > v;
int solve(int cur)
{
if(dp[cur]!=-1)
{
return dp[cur];
}
else
{
int cur_w=v[cur].first;
int cur_h=v[cur].second;
int ret=0;
int par=cur;
for(int j=0;j<=n;j++)
{
if(v[j].first>cur_w && v[j].second>cur_h)
{
int val=solve(j);
if(val>ret)
{
ret=val;
par=j;
}
}
}
dp[cur]=ret+1;
next[cur]=par;
return dp[cur];
}
}
int main()
{
cin>>n;
for(int i=0;i<=n;i++)
{
dp[i]=-1;
int a,b;
cin>>a>>b;
v.push_back(make_pair(a,b));
}
int ans=solve(0);
cout<<ans-1<<endl;
int start=next[0];
for(int i=0 ;i<ans-1;i++)
{
cout<<start<<" ";
start=next[start];
}
}
------------------------------------------------another editorial-----------------------------------------------------
Mysterious Present
Problem can be solved by dynamic programming approach for O(n2) by time and O(n) by memory.- Sort all envelopes by pairs (wi, hi) or by product wi*hi in nondecreasing order. Because of it envelope i can be put in envelope j only ifi < j. That is for any chain {a1, a2, ..., an} is true that a1 < a2 < ... < an.
- Just delete all envelopes in which card can't be put in.
- Add to sorted envelopes array a0 - Peter's card.
- Introduce DP function: dp[i] maximum chain length which ends in i-th envelope.
- dp[0] = 0, dp[i] = max(dp[j]) + 1, where i ≥ 1, 0 ≤ j < i and j can be put in i. This function can be easily got by previously computed values of it.
For each dp[i] one can remember index p[i] = j with which maximum reached in formula p5. If one knows s - envelope index in which maximal chain ends he can restore all answer sequence (i0 = s, ik+1 = p[ik]).
No comments:
Post a Comment