這道題目的題意就是使用題目中所給的Gate 函數,模擬出輸入的結果
當然我們分析的時候可以倒著來,就是拿輸入去減
每次Gate 函數都會有一個有效范圍
這道題目求的就是,找出一種模擬方法,使得最小的有效范圍最大化。
是一道【貪心】題
參考了https://github.com/boleynsu/acmicpc-codes 的做法
b 數組中存放是 Sequence 的下標
這是一個O(n)的算法if (a[i-1]<a[i]){int k=a[i]-a[i-1];while (k--) b[++bt]=i;
}
就是把 i 加進 b 數組,加 a[i] - a[i - 1]次
比如 a[i - 1] 為3 a[i] 為 5
那么在 b[ ] 中就會加兩次 3 else if (a[i-1]>a[i]){int k=a[i-1]-a[i];while (k--){++bh;}answer = min(answer,i - b[bh - 1]);
}
bh 指針右移 k 次, 由于b 數組為非遞減數組,故最后一位一定是最大的
取i - b[bh - 1] 與 answer比較,這個意思就是比較 Gate 函數的有效范圍
如果有更小的范圍,那么更新一遍
這里的 i 就是當前的位置, b[bh - 1]的意思……
?
//#pragma comment(linker, "/STACK:16777216") //for c++ Compiler #include <stdio.h> #include <iostream> #include <cstring> #include <cmath> #include <stack> #include <queue> #include <vector> #include <algorithm> #define ll long long #define Max(a,b) (((a) > (b)) ? (a) : (b)) #define Min(a,b) (((a) < (b)) ? (a) : (b)) #define Abs(x) (((x) > 0) ? (x) : (-(x))) using namespace std;const int MAXN = 2000000;int N; int a[MAXN]; int b[MAXN]; int bh,bt;int main(){int T;scanf("%d",&T);while (T--){scanf("%d",&N);for (int i=1;i<=N;i++)scanf("%d",a+i);bh=0,bt=-1;int answer=N;a[0]=a[N+1]=0;for (int i=1;i<=N+1;i++){if (a[i-1]<a[i]){int k=a[i]-a[i-1];while (k--) b[++bt]=i;}else if (a[i-1]>a[i]){int k=a[i-1]-a[i];while (k--){++bh;}answer = min(answer,i - b[bh - 1]);}}printf("%d\n",answer);} }
?當然在這里,也有一種更簡單的方法也能過,不知道是不是算是數據水呢
#include<stdio.h> int main(){int t, n, i, j, k, cnt;int a[10010], ans;scanf("%d",&t);while(t--){scanf("%d",&n);for(i = 1; i <= n; ++i){scanf("%d",&a[i]);}i = 1;ans = 0x3f3f3f3f;while(i <= n){j = i;while(a[j+1] >= a[j]){--a[j];++j;}--a[j];cnt = j - i + 1;if(cnt < ans)ans = cnt;while(a[i] == 0)++i;}printf("%d\n",ans);}return 0; }
?