数据范围
数字三角形:
#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int a[N][N],f[N][N];
int n;
int main() {
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin >> n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= i; j++) cin >> a[i][j];
}
//初始化最后一行
for(int i = 1; i <= n; i++) f[n][i] = a[n][i];
for(int i = n - 1; i >= 1; i--){
for(int j = 1; j <= i; j++){
f[i][j] = max(f[i + 1][j],f[i + 1][j + 1]) + a[i][j];
}
}
cout << f[1][1];
return 0;
}
最长上升子序列:
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int a[N],f[N];
int n;
int main() {
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin >> n;
for(int i = 1; i <= n; i++) cin >> a[i];
for(int i = 1; i <= n; i++){
f[i] = 1;// 初始化,只有a[i]一个数
for(int j = 0; j < i; j++){
if(a[j] < a[i]) f[i] = max(f[i],f[j] + 1);
}
}
int ans = 0;
for(int i = 1; i <= n; i++) ans = max(ans,f[i]);
cout << ans <<'\n';
return 0;
}
更多详细内容求最长上升子序列总结-CSDN博客
最长公共子序列 :
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int f[N][N];
int main() {
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int len1,len2; cin >> len1 >> len2;
string s1,s2; cin >> s1 >> s2;
for(int i = 1; i <= len1; i++){
for(int j = 1; j <= len2; j++){
f[i][j] = max(f[i - 1][j], f[i][j - 1]);
if(s1[i] == s2[j]) f[i][j] = max(f[i - 1][j - 1] + 1,f[i][j]);
}
}
cout << f[len1][len2];
return 0;
}
最短编辑距离:
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int f[N][N];
char a[N],b[N];
int n,m;
int main() {
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin >> n >> (a + 1) >> m >> (b + 1);
//初始化
for(int i = 0; i <= m; i++) f[0][i] = i;
for(int i = 0; i <= n; i++) f[i][0] = i;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
f[i][j] = min(f[i - 1][j],f[i][j - 1]) + 1;
if(a[i] == b[j]) f[i][j] = min(f[i][j],f[i - 1][j - 1]);
else f[i][j] = min(f[i][j],f[i - 1][j - 1] + 1);
}
}
cout << f[n][m];
return 0;
}
编辑距离:
最短编辑距离的一个应用
#include <bits/stdc++.h>
using namespace std;
const int N = 1010;
int f[N][N];
char str[N][N];
int n,m;
// 将a变为b
int solve(char a[],char b[])
{
int la = strlen(a + 1);
int lb = strlen(b + 1);
//初始化
for(int i = 0; i <= lb; i++) f[0][i] = i;// 全增
for(int i = 0; i <= la; i++) f[i][0] = i;// 全删
for(int i = 1; i <= la; i++){
for(int j = 1; j <= lb; j++){
f[i][j] = min(f[i - 1][j],f[i][j - 1]) + 1;
if(a[i] == b[j]) f[i][j] = min(f[i][j],f[i - 1][j - 1]);
else f[i][j] = min(f[i][j],f[i - 1][j - 1] + 1);
}
}
return f[la][lb];
}
int main() {
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin >> n >> m ;
for(int i = 0; i < n; i++) cin >> str[i] + 1;
while(m --){
char s[N];
int limit;
cin >> (s + 1) >> limit;
int ans = 0;
for(int i = 0; i < n; i++){
if(solve(str[i],s) <= limit) ans ++;
}
cout << ans <<'\n';
}
return 0;
}