CodeForces - 1457E New Game Plus!(贪心)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 1457E New Game Plus!(贪心)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個長度為 n 的序列,需要自己定義一種順序去遍歷序列,每次需要維護答案:
有 k 次機會可以將 sum 清零,問如何遍歷可以使得最后的 ans 最大
題目分析:首先不難看出,k 次清零操作可以將整個序列拆分成相互獨立的 k + 1 個子段,而對于每個子段來說,假設其長度為 len,從頭到尾遍歷之后得到的貢獻將是:b[ 1 ] * ( len - 1 ) + b[ 2 ] * ( len - 2 ) + ... + b[ len - 1 ] * 1,所以對于 sum > 0 時的前綴,直接貪心從大到小維護就好,當 sum < 0 時,再將這個前綴與剩下的未被遍歷到的序列貪心去分組成 k + 1 組即可,比較顯然的是,對于上面提到的序列 b 來說,從 1 ~ len 遞減放置是最優的,所以可以選擇一層一層去貪心
對于負數區域的貪心思想的話用官方題解的圖示一眼就能看明白了:(從頂到底分別是 1 ~ len)
代碼:
//#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> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e6+100;int a[N];vector<int>node;int main() { #ifndef ONLINE_JUDGE // freopen("data.ans.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);int n,k;scanf("%d%d",&n,&k);k++;for(int i=1;i<=n;i++)scanf("%d",a+i);sort(a+1,a+1+n,greater<int>());LL ans=0,sum=0;for(int i=1;i<=n;i++){ans+=sum;sum+=a[i];if(sum<0){node.push_back(sum);for(int j=i+1;j<=n;j++)node.push_back(a[j]);reverse(node.begin(),node.end());break;}}for(int i=0;i<node.size();i++)ans+=1LL*node[i]*(i/k);printf("%lld\n",ans);return 0; }?
總結
以上是生活随笔為你收集整理的CodeForces - 1457E New Game Plus!(贪心)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1457D X
- 下一篇: CodeForces - 1455E F