F - Destroying Array-(并查集dsu)

总结

我想了一下,但是写一下吧,毕竟并查集的题,千年难遇。
这个题,很明显的连续区间不断的分开,其实就是把一堆东西,不断的切开,如果我们倒着想,其实就是把一个个东西有关系的不断的堆在一起,也就是并查集的题。模拟一下,没啥坑点!

#include<bits/stdc++.h>
//typedef long long ll;
//#define ull       unsigned long long
#define int       long long
#define F           first
#define S           second
#define endl        "\n"//<<flush
#define lowbit(x)   (x&(-x))
#define ferma(a,b)  pow(a,b-2)
#define pb          push_back
#define mp          make_pair
#define all(x)      x.begin(),x.end()
#define memset(a,b) memset(a,b,sizeof(a));
#define IOS         ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
using namespace std;
const double PI=acos(-1.0);
const int inf=0x3f3f3f3f;
const int MAXN=0x7fffffff;
const long long INF = 0x3f3f3f3f3f3f3f3fLL;
void file()
{
#ifdef ONLINE_JUDGE
#else
    freopen("cin.txt","r",stdin);
    //  freopen("cout.txt","w",stdout);
#endif
}
const int N=1e6+5;
int fat[N],vis[N],seg[N];
int father(int x)
{
    if(fat[x]==x)
        return x;
    fat[x]=father(fat[x]);
    return fat[x];
}
signed main()
{
    IOS;
    //file();
    int n;
    cin>>n;
    vector<int>a(n),b(n),ans;
    for(int i=0;i<n;i++)
        fat[i]=i;
    for(auto &it:a)
        cin>>it;
    for(auto &it:b)
        cin>>it;
    reverse(all(b));
    int maxn=0;
    for(int i=0;i<n;i++)
    {
        ans.pb(maxn);
        int index=b[i]-1;
        vis[index]=true;
        seg[index]=a[index];
        if(index&&vis[index-1])
        {
            int x=father(index-1);
            seg[index]+=seg[x];
            fat[x]=index;
        }
        if(vis[index+1])
        {
            int x=father(index+1);
            seg[index]+=seg[x];
            fat[x]=index;
        }
        maxn=max(maxn,seg[index]);
    }
    reverse(all(ans));
    for(auto it:ans)
        cout<<it<<endl;
    return 0;
}

发布了130 篇原创文章 · 获赞 5 · 访问量 5007

猜你喜欢

转载自blog.csdn.net/weixin_44224825/article/details/104096565