求助!!!求教动态转移时第二层for循环的优化方法
  • 板块学术版
  • 楼主_shy
  • 当前回复3
  • 已保存回复3
  • 发布时间2020/10/28 21:07
  • 上次更新2023/11/5 09:38:29
查看原帖
求助!!!求教动态转移时第二层for循环的优化方法
183881
_shy楼主2020/10/28 21:07

以下是蒟蒻代码(想不出来怎么优化了):

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
using namespace std;
/*inline int read () // inline long long
{
	int s = 0, w = 1; char ch = getchar (); // long long s
	while (ch < '0' || ch > '9') {if (ch == '-') w = -1; ch = getchar ();} while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar ();
	return s * w;
}*/
const int maxn = 2010;
int dp[maxn][2], a[maxn], n, k, ans;
// 1 偶数, 0 奇数. 
int main ()
{
	//freopen (".in", "r", stdin); freopen (".out", "w", stdout);
	scanf ("%d %d", &n, &k);
	for (int i = 1; i <= n; i++)
		scanf ("%d", &a[i]);
	dp[1][1] = 0; dp[1][0] = 1;
	for (int i = 2; i <= n; i++)
		for (int j = 1; j < i; j++)
		{
			if (a[i] > a[j] && (a[i] - a[j]) >= k) 
			dp[i][1] = max (dp[i][1], dp[j][0] + 1);
			else if (a[i] < a[j] && (a[j] - a[i]) >= k)
			dp[i][0] = max (dp[i][0], dp[j][1] + 1);
			else if (a[i] == a[j] && k <= 0)
			dp[i][1] = max (dp[i][1], dp[j][0] + 1),
			dp[i][0] = max (dp[i][0], dp[j][1] + 1);
		}
	for (int i = 0; i <= 1; i++)
		for (int j = 1; j <= n; j++)
			ans = max (ans, dp[j][i]);
	printf ("%d", ans);
	return 0;
}

2020/10/28 21:07
加载中...