CodeForces - 722C Destroying Array(倒着并查集+离线处理)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 722C Destroying Array(倒着并查集+离线处理)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個數列a,現在給出操作b,每次操作都會刪除掉數列a中指定位置的數,問每次刪除后,最大連續字段和是多少
題目分析:一開始看到最大連續字段和,以為是要用dp,又看了一下題發現a數組都是非負數,這樣一來最大連續字段和就取決于在經過數組b的操作后是否連續了,判斷連續一開始我想用set集合維護斷點的,感覺太麻煩,又想用線段樹試試能不能維護區間,還是比較麻煩,想不出比較利索的方法實現這個題目,又一看這是div2的一個C題,不敢想的太麻煩,就去看了一下題解,發現是要用并查集,就突然恍然大悟,正難則反,既然刪除操作比較難實現,那么我們直接離線處理,倒著一步一步把刪除掉的數添加回去不就好了,每次添加之后維護一下最大值更新答案,最后在輸出就好了
不過這里的并查集要注意合并順序,順便再維護一個sum數組用來維護每個集合父節點的字段和就能實時維護答案了
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cstring> #include<algorithm> #include<stack> #include<queue> #include<map> #include<set> #include<cmath> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e5+100;int a[N],b[N],f[N];LL ans[N],sum[N];bool vis[N];int find(int x) {return x==f[x]?x:f[x]=find(f[x]); }void merge(int x,int y)//y->x {int xx=find(x);int yy=find(y);f[yy]=xx;sum[xx]+=sum[yy]; }void init() {for(int i=1;i<N;i++)f[i]=i; }int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);init();int n;scanf("%d",&n);for(int i=1;i<=n;i++)scanf("%d",a+i);for(int i=1;i<=n;i++)scanf("%d",b+i);LL mmax=0;for(int i=n;i>=1;i--){ans[i]=mmax;int pos=b[i];sum[pos]=a[pos];vis[pos]=true;if(vis[pos+1])//如果pos+1存在,則將pos+1的集合合并到pos上merge(pos,pos+1);if(vis[pos-1])//如果pos-1存在,則將pos-1的集合合并到pos上merge(pos,pos-1);mmax=max(mmax,sum[pos]);//更新最大值}for(int i=1;i<=n;i++)printf("%lld\n",ans[i]);return 0; }?
總結
以上是生活随笔為你收集整理的CodeForces - 722C Destroying Array(倒着并查集+离线处理)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 798D Mi
- 下一篇: CodeForces - 125C Ho