題意(Codeforces 965D)
分析
我是激情看題解的,很慚愧。因爲自己的算法喜提TLE了w
我參考的題解在這兒。官方題解用了二分的思想。
這個算法是怎麼貪心的呢?就在while(p<i && frog[p]+frog[i]<=a[i])
這一句。當第i
處已經滿了的時候,我們就不考慮 到i的跳躍了。後面那句if是減去多餘的。
其他地方結合註釋和原題解的講解來看。注意維護p指針始終和i的距離 。
代碼
#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
#define PB push_back
#define MP make_pair
#define fi first
#define se second
#define lowbit(x) (x&(-x))
#define rep(i, a, b) for(int i = (a); i <= (b); i++)
#define per(i, a, b) for(int i = (a); i >= (b); i--)
#define pr(x) cout << #x << " = " << x << " ";
#define prl(x) cout << #x << " = " << x << endl;
#define ZERO(X) memset((X),0,sizeof(X))
#define ALL(X) (X).begin(),(X).end()
#define SZ(x) (int)x.size()
using namespace std;
typedef pair<int, int> PI;
typedef pair<pair<int, int>, int> PII;
typedef pair<pair<pair<int, int>, int>, int> PIII;
using ull= unsigned long long;
using ll = long long;
using ld = long double;
#define quickio ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define debug(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
/* debug("Precalc: %.3f\n", (double)(clock()) / CLOCKS_PER_SEC);
clock_t z = clock();
solve();
//debug("Test: %.3f\n", (double)(clock() - z) / CLOCKS_PER_SEC);
*/
template<typename T = int>
inline T read() {
T val=0, sign=1;
char ch;
for (ch=getchar();ch<'0'||ch>'9';ch=getchar())
if (ch=='-') sign=-1;
for (;ch>='0'&&ch<='9';ch=getchar())
val=val*10+ch-'0';
return sign*val;
}
int main()
{
int w,l; cin>>w>>l;
int a[100005]; ZERO(a);
int frog[100005]; ZERO(frog);
a[w]=0x3f3f3f3f; // INF
rep(i,1,w-1)
{
cin>>a[i];
if(i<=l) frog[i]=a[i];
}
int p=1;
rep(i,l+1,w)
{
while(i-p>l) ++p;
while(p<i && frog[p]+frog[i]<=a[i])
frog[i]+=frog[p++];
if(p<i&&frog[i]!=a[i]) // greedy here. It's impossible for p+1~i-1 to jmp to a[i]. here, imply that frog[p]+frog[i]>a[i]
{
frog[p]-=(a[i]-frog[i]); // the a[i]-frog[i] frogs cannot jmp from p, because it's full already.
frog[i]=a[i];
}
}
cout<<frog[w]<<endl;
return 0;
}