这题的状态不难理解,状态表示为,如果上一个城市剩下的钱不为负,也就是没有被赶回杭电,则再考虑它对下一个城市的影响;如果上一个城市剩下的前加上当前城市的前大于当前城市的生活费,那么Dp[i]=Dp[i-1]+1;
值得注意的而是这题的数据为100000;不可能以每个城市为起点来一次Dp,时间复杂度为n^2;足已超时;
值得注意的而是这题的数据为100000;不可能以每个城市为起点来一次Dp,时间复杂度为n^2;足已超时;
我是这样处理的,在保存的数据后面再接上1…n的数据,这样扫描一遍的复杂度为n;再加一个优化,当Dp[i]==n时,也就是能全部游完所有城市的时候,直接break;
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
const int MAXN = 100005;
int a[MAXN * 2];
int main()
{
int n; int i; int w, l;
while (scanf("%d", &n) != EOF)
{
for (i = 0; i < n; i++)
{
scanf("%d%d", &w, &l);
a[i] = w - l;
a[i + n] = w - l;
}
int sum = 0; int ans = 0; int cnt = 0;
for (i = 0; i < 2 * n;i++)
{
sum += a[i];
if (sum < 0)
{
ans = ans > cnt ? ans : cnt;
sum = 0; cnt = 0;
}
else
cnt++;
if(cnt >= n)
break;
}
ans = ans > cnt ? ans : cnt;
if (ans > n) ans = n;
printf("%d\n", ans);
}
return 0;
}

本文介绍了一个基于DP算法的城市游览问题解决方法,通过优化避免了时间复杂度过高的问题,并提供了具体的实现代码。
1045

被折叠的 条评论
为什么被折叠?



