To do a question, by the way to summarize LIS LCS
first give a n2 DP practice to find
the original LIS link:
Gym 101653 O Diamonds
To the effect:
Given a sequence, each point represents a necklace, there are two values w, c requires the longest ascending subsequence, but now we must consider both at the same time
Ideas:
The scope of the topic is very wide, and the direct n2 algorithm can be passed directly. I don't know why the nlogn algorithm is wrong at the beginning. It seems that lower_bound still cannot be used after overloading, which is different from the one-dimensional approach.
Direct n2 DP practice
DP equation:
Specific code:
//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
using namespace std;
#define INF 0x3f3f3f3f
#define M(a, b) memset(a, b, sizeof(a))
const int MAXN = 2000 + 5;
struct node {
double w, c;
} a[MAXN];
int dp[MAXN];
int main() {
int T;
cin >> T;
while(T--) {
int n;
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> a[i].w >> a[i].c;
dp[i]=1;
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j < i; j++) {
if(a[i].w>a[j].w && a[i].c<a[j].c) dp[i]=max(dp[j]+1,dp[i]);
}
}
int ans=0;
for(int i=1;i<=n;i++) ans=max(ans,dp[i]);
cout<<ans<<endl;
}
}
The one-dimensional DP method is the same as this, the difference is only the "overload of the size is greater than"
nlogn practice:
For details, see: http://blog.csdn.net/shuangde800/article/details/7474903
Definition d[k]: The last element of the ascending subsequence of length k, if there are multiple ascending subsequences of length k, record the smallest last element.
Note that the elements in d are monotonically increasing, and this property will be used below.
First len = 1, d[1] = a[1], then for a[i]: if a[i]>d[len], then len++, d[len] = a[i];
otherwise, we have to Find a j from d[1] to d[len-1] that satisfies d[j-1]
with the lower_bound function
key code:
for(int i=0;i<n;i++){
if(a[i]>=dp[len])
dp[++len]=a[i];
else {
int p=lower_bound(dp,dp+len,a[i])-dp;
dp[p]=a[i];
}
}
printf("%d\n",len);
The meaning of the update in else is to serve the following services.
There may be a sequence {1,3,7,9}. When 6 is encountered, it needs to be changed to {1,3,6,9}, then when 7,8 is encountered later, it can be changed to {1,3,6,7,8}
Another n2 method of sorting + LCS (Longest Commen Sequence) longest common subsequence
The complexity of LCS is
well understood by the M*N method.
The practice of LCS requires understanding of three transfer equations:
see:
http://blog.csdn.net/hrn1216/article/details/51534607
State transition equation:
Output LCS:
push it backwards, start outputting from the end, and choose a direction with a larger c to push it backwards.