LIS
百练-2757



package 动态规划;
import java.util.Scanner;
public class 最长上升子序列 {
static int n;
static int[] data;
static int[] record;
public static void main(String[] args) {
init();
int max = record[0];
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (data[j] < data[i]) {
record[i] = Math.max(record[i], record[j] + 1);
}
}
max = Math.max(record[i], max);
}
System.out.println(max);
}
private static void init() {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
data = new int[n];
record = new int[n];
for (int i = 0; i < data.length; i++) {
data[i] = sc.nextInt();
record[i] = 1;
}
}
}
LIS相关题目1
计蒜客-T1722
package DP;
import java.util.Scanner;
public class 利润 {
static int n;
static int[] v;
static int[] dp;
static int Max;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
Max = Integer.MIN_VALUE;
n = sc.nextInt();
v = new int[n];
dp = new int[3];
for (int i = 0; i < n; i++) {
v[i] = sc.nextInt();
}
function();
System.out.println(Max);
}
}
private static void function() {
dp[0] = v[0];
int e = 1;
for (int i = 1; i < n; i++) {
if (dp[e ^ 1] < 0)
dp[e] = v[i];
else
dp[e] = dp[e ^ 1] + v[i];
Max = Math.max(Max, dp[e]);
e ^= 1;
}
}
}
LIS相关题目2
计蒜客-T1227
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int v[100000 + 5];
int main() {
int t;
cin >> t;
while (t--) {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> v[i];
}
for (int i = 3; i <= n; i++) {
int temp = v[1];
temp = max(v[i - 3], v[i - 2]);
v[i] = v[i] + temp;
}
int maxV = v[1];
if (n > 1)
maxV = max(v[n - 1], v[n]);
cout << maxV << endl;
}
return 0;
}
LCS
POJ-1458
视频讲解
package 动态规划;
import java.util.Scanner;
public class 最長公共子序列 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str1 = sc.next();
String str2 = sc.next();
int n = str1.length();
int m = str2.length();
int[][] dp = new int[n + 1][m + 1];
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[i].length; j++) {
if (str1.charAt(i - 1) == str2.charAt(j - 1))
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
System.out.println(dp[n][m]);
}
}
}