今晚重新过了一遍线性dp,打卡记录一下
AcWing 898. 数字三角形
#include<iostream>
using namespace std;
const int N = 1e3;
int f[N][N], n;
int main()
{
cin >> n;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= i;j++)
cin >> f[i][j];
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]);
cout << f[1][1] << endl;
return 0;
}
AcWing 895. 最长上升子序列
#include<iostream>
const int N = 1e3 + 5;
using namespace std;
int f[N], n, a[N];
int main()
{
cin >> n;
for(int i = 1;i <= n;i++)
cin >> a[i];
for(int i = 1;i <= n;i++) f[i] = 1;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= i;j++)
if(a[i] > a[j]) 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 << endl;
return 0;
}
AcWing 896. 最长上升子序列 Ⅱ
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e5 + 10;
int f[N], n, a[N], cnt;
int main()
{
cin >> n;
memset(f, 0x3f, sizeof f);
for(int i = 1;i <= n;i++) cin >> a[i];
for(int i = 1;i <= n;i++)
{
if(!cnt) f[++cnt] = a[i];
else if(f[cnt] < a[i]) f[++cnt] = a[i];
else {
int l = 1, r = n+1;
while(l < r)
{
int mid = l + r >> 1;
if(f[mid] >= a[i]) r = mid;
else l = mid + 1;
}
f[l] = min(f[l], a[i]);
}
}
cout << cnt << endl;
return 0;
}
AcWing 897. 最长公共子序列
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e3 + 10;
int n, m;
char a[N],b[N];
int f[N][N];
int main()
{
cin >> n >> m;
scanf("%s", a + 1);
scanf("%s", b + 1);
for(int i = 1;i <= n;i++)
for(int j = 1;j <= m;j++)
if(a[i] == b[j]) f[i][j] = f[i - 1][j - 1] + 1;
else f[i][j] = max(f[i - 1][j], f[i][j - 1]);
cout << f[n][m] << endl;
return 0;
}
AcWing 902. 最短编辑距离
#include<iostream>
using namespace std;
const int N = 1e3 + 10;
int n, m;
char a[N], b[N];
int f[N][N];
int main()
{
cin >> n;
scanf("%s", a + 1);
cin >> m;
scanf("%s", b + 1);
for(int i = 1;i <= m;i++)
f[0][i] = i;
for(int i = 1;i <= n;i++)
f[i][0] = i;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= m;j++)
if(a[i] == b[j]) f[i][j] = f[i - 1][j - 1];
else f[i][j] = min(min(f[i - 1][j], f[i][j - 1]), f[i - 1][j - 1]) + 1;
cout << f[n][m] << endl;
return 0;
}
AcWing 899. 编辑距离
#include<iostream>
#include<cstring>
using namespace std;
const int N = 1e3 + 10;
int n, m;
string a[N];
string s;
int t;
int f[N][N];
int main()
{
ios::sync_with_stdio(false);//这个加不加感觉没啥效果
cin >> n >> m;
for(int i = 1;i <= n;i++)
{
cin >> a[i];
a[i] = " " + a[i];
}
while(m--)
{
cin >> s >> t;
int cnt = 0;
s = " " + s;
int length = s.size() - 1;
for(int i = 1;i <= n;i++)
{
int len = a[i].size() - 1;
for(int i = 1;i <= len;i++) f[i][0] = i;
for(int i = 1;i <= length;i++) f[0][i] = i;
for(int j = 1;j <= len;j++)
for(int k = 1;k <= length;k++)
if(a[i][j] == s[k]) f[j][k] = f[j - 1][k - 1];
else f[j][k] = min(min(f[j - 1][k], f[j][k - 1]), f[j - 1][k - 1]) + 1;
if(f[len][length] <= t) cnt++;
}
cout << cnt << endl;
}
return 0;
}