CodeForces - 1486D Max Median(二分+最长连续子段和)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1486D Max Median(二分+最长连续子段和)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個長度為 nnn 的數列,現在從長度至少為 kkk 的連續子段中,找到最大的中位數
題目分析:做過平均數的模型:POJ - 2018 Best Cow Fences
將平均數換成中位數該如何去考慮呢,現在問題轉換為了,枚舉 xxx 作為中位數,該如何 checkcheckcheck 序列是否合法
考慮若一個數想要成為中位數,則至少有一半及以上的數比他小才行,那么我們如果將比 xxx 小的數視為 ?1-1?1 ,大于等于 xxx 的數視為 111 會怎么樣呢?不難發現,如果存在著一段連續子段和大于 000 ,則這個子段的中位數至少是大于等于 xxx 的
所以現在問題轉換為了,求長度至少為 kkk 的最大連續子段和,是否大于 000
上面的模型是一個經典的 dpdpdp 模型,只需要利用前綴和控制一下就可以了,不多贅述了
代碼:
// Problem: D. Max Median // Contest: Codeforces - Codeforces Round #703 (Div. 2) // URL: https://codeforces.com/contest/1486/problem/D // Memory Limit: 256 MB // Time Limit: 2000 ms // // Powered by CP Editor (https://cpeditor.org)// #pragma GCC optimize(2) // #pragma GCC optimize("Ofast","inline","-ffast-math") // #pragma GCC target("avx,sse2,sse3,sse4,mmx") #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> #include<list> #include<unordered_map> #define lowbit(x) x&-x using namespace std; typedef long long LL; typedef unsigned long long ull; template<typename T> inline void read(T &x) {T f=1;x=0;char ch=getchar();while(0==isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}while(0!=isdigit(ch)) x=(x<<1)+(x<<3)+ch-'0',ch=getchar();x*=f; } template<typename T> inline void write(T x) {if(x<0){x=~(x-1);putchar('-');}if(x>9)write(x/10);putchar(x%10+'0'); } const int inf=0x3f3f3f3f; const int N=1e6+100; int a[N],sum[N]; int n,m; bool check(int mid) {for(int i=1;i<=n;i++) {sum[i]=sum[i-1]+(a[i]>=mid?1:-1);}int ans=sum[m],mmin=0;for(int i=m+1;i<=n;i++) {mmin=min(mmin,sum[i-m]);ans=max(ans,sum[i]-mmin);}return ans>0; } int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);read(n),read(m);for(int i=1;i<=n;i++) {read(a[i]);}int l=1,r=n,ans=-1;;while(l<=r) {int mid=(l+r)>>1;if(check(mid)) {ans=mid;l=mid+1;} else {r=mid-1;}}cout<<ans<<endl;return 0; }總結
以上是生活随笔為你收集整理的CodeForces - 1486D Max Median(二分+最长连续子段和)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1486C2
- 下一篇: CodeForces - 1486E P