生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 892E Envy(可撤销并查集)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一張由 n 個點 m 條邊組成的連通圖,有 q 次詢問,每次詢問給出一個邊集,需要判斷這些邊是否可以同時出現在最小生成樹上
題目分析:需要用到的一個性質是,對于同一個詢問來說,不同權值的選擇是相互獨立的,但是相同權值之間會相互影響,所以我們可以對每個詢問的每條邊單獨拿出來討論
在進行正常的最小生成樹的操作時,對于每次操作的當前邊 i ,需要處理所有詢問中邊權與當前邊權相等的邊,因為當前處理的這些詢問的邊權都相等,所以我們按照詢問的 id 分組單獨討論,對于每個 id 來說,將這些邊權相等的邊都加入到并查集中 后如果發現有環的話,那就說明第 id 個詢問的答案是 NO ,如此處理即可
需要注意的是,上面的橙色的字,只是判斷每個詢問的可行性用的,并不屬于最小生成樹的過程,所以在進行上述插入過程后,需要及時撤銷
因為涉及到了并查集的撤銷,所以不能進行路徑壓縮,總的時間復雜度就是 mlogm 的
代碼: ?
#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<unordered_map>
using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=5e5+100;struct Edge
{int u,v,w,id;bool operator<(const Edge& t)const{if(w!=t.w)return w<t.w;return id<t.id;}
}edge[N],qu[N];struct revo
{int fax,fay;int rkx,rky;
};int f[N],rk[N],tot;bool ans[N];stack<revo>st;int find(int x)
{return f[x]==x?x:find(f[x]);
}bool merge(int x,int y)
{int xx=find(x),yy=find(y);if(xx==yy)return false;revo temp;temp.fax=xx,temp.fay=yy;temp.rkx=rk[xx],temp.rky=rk[yy];st.push(temp);if(rk[xx]>rk[yy])swap(xx,yy);f[xx]=yy;rk[yy]=max(rk[yy],rk[xx]+1);return true;
}void revocation(int k)
{while(k--){revo node=st.top();st.pop();f[node.fax]=node.fax;f[node.fay]=node.fay;rk[node.fax]=node.rkx;rk[node.fay]=node.rky;}
}void init()
{for(int i=1;i<N;i++){f[i]=i;rk[i]=1;}
}int main()
{
#ifndef ONLINE_JUDGE
// freopen("data.in.txt","r",stdin);
// freopen("data.out.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);init();int n,m;scanf("%d%d",&n,&m);for(int i=1;i<=m;i++)scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);int q;scanf("%d",&q);for(int i=1;i<=q;i++){ans[i]=true;int k;scanf("%d",&k);while(k--){int num;scanf("%d",&num);tot++;qu[tot]=edge[num];qu[tot].id=i;}}sort(edge+1,edge+1+m);sort(qu+1,qu+1+tot);int pos=1;//記錄qu數組的下標 for(int i=1;i<=m;i++){int cnt=0;//共需要撤銷多少條邊while(qu[pos].w==edge[i].w){if(qu[pos].id!=qu[pos-1].id)//如果相鄰兩個詢問的邊不屬于同一個組,則需要撤銷 {revocation(cnt);cnt=0;}if(!merge(qu[pos].u,qu[pos].v))//如果詢問的兩個點早已經合并,說明當前的邊不是必須的,更新答案 ans[qu[pos].id]=false;else//否則在需要撤銷的數量上加一 cnt++;pos++;}revocation(cnt);merge(edge[i].u,edge[i].v);}for(int i=1;i<=q;i++)if(ans[i])puts("YES");elseputs("NO");return 0;
}
?
總結
以上是生活随笔 為你收集整理的CodeForces - 892E Envy(可撤销并查集) 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。