洛谷B3637 最长上升子序列
思路:
板子题,双重循环枚举即可。
代码:
#include <iostream>
using namespace std;
const int N = 5010;
int a[N], f[N], 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 j = i - 1; j > 0; j -- )
{
if (a[j] < a[i]) f[i] = max (f[i], f[j] + 1);
}
}
int res = 0;
for (int i = 1; i <= n; i ++ )
res = max (res, f[i]);
cout << res;
return 0;
}
洛谷P1115 最大子段和
思路:
这题一开始不会,通过看题解,然后知道了思路。可以枚举每一个数,如果以前一个数结尾的字段和
大于0,那么以当前数结尾的字段和
就加上以前一个数结尾的字段和
,否则以当前数结尾的字段和
就是当前数的大小
。
代码:
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
LL a[N], f[N], n;
int main()
{
cin >> n;
for (int i = 1; i <= n; i ++ )
cin >> a[i];
for (int i = 1; i <= n; i ++ )
{
if (f[i-1] + a[i] < a[i]) f[i] = a[i];
else f[i] = f[i-1] + a[i];
}
LL res = -2e9;
for (int i = 1; i <= n; i ++ )
res = max (res, f[i]);
cout << res << endl;
return 0;
}
洛谷P8707 [蓝桥杯 2020 省 AB1] 走方格
思路:
枚举每一个方格,如果能走,那么就分为两种:1、从右边过来,如果右边可以走,那么当前方案数加上从右边走过来的方案数。2、从上边过来,如果上边可以走,那么当前方案数加上从上边走过来的方案数。
代码:
#include <iostream>
using namespace std;
const int N = 40;
int a[N][N], f[N][N], n, m;
int main()
{
cin >> n >> m;
// for (int i = 1; i <= n; i ++ )
// for (int j = 1; j <= m; j ++ )
// a[i][j] = i + j;
f[1][1] = 1;
for (int i = 1; i <= n; i ++ )
{
for (int j = 1; j <= m; j ++ )
{
if (i % 2 == 0 && j % 2 == 0) continue;
if ((i-1) > 0 && (i-1) % 2 == 0 && j % 2 == 0) ;
else if (i -1 > 0)
{
//cout << i << ' ' << j << endl;
f[i][j] += f[i-1][j];
//cout << f[i][j] << endl;
}
if ((j-1) > 0 && i % 2 == 0 && (j-1) % 2 == 0) ;
else if (j - 1 > 0)
{
//cout << i << ' ' << j << endl;
f[i][j] += f[i][j-1];
//cout << f[i][j] << endl;
}
}
}
cout << f[n][m];
return 0;
}
洛谷P1216 [USACO1.5] [IOI1994]数字三角形
思路:
每一个数的最大和,要么是加上右上,要么加上左上,所以选右上或者左上最大值即可。
代码:
#include <iostream>
using namespace std;
const int N = 1010;
int a[N][N], f[N][N], n;
int main()
{
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 ++ )
{
for (int j = 1; j <= n; j ++ )
{
f[i][j] = a[i][j] + max (f[i-1][j-1], f[i-1][j]);
}
}
int res = 0;
for (int i = 1; i <= n; i ++ )
res = max(res, f[n][i]);
cout << res << endl;
return 0;
}
洛谷P1020 [NOIP1999 普及组] 导弹拦截
思路:
先是求出了最长子序列,然后用贪心的方法求需要几个子系统(但是这个方法只能过掉50%的数据,打算下次再学过掉100%数据的方法)。
代码:
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
int h[N], f[N], g[N], n = 0;
int main()
{
while (cin >> h[n]) n++;
for (int i = 0; i < n; i ++ )
{
f[i] = 1;
for (int j = i - 1; j >= 0; j -- )
{
if (h[j] >= h[i]) f[i] = max (f[i], f[j] + 1);
}
}
int res = 0;
for (int i = 0; i < n; i ++ )
res = max (res, f[i]);
cout << res << endl;
int cnt = 0;
for (int i = 0; i < n; i ++ )
{
int q = 0;
while (q < cnt && h[i] > g[q]) q ++;
g[q] = h[i];
if (q >= cnt) cnt++;
}
cout << cnt << endl;
return 0;
}