CodeForces - 888G Xor-MST(贪心+字典树+最小生成树)
生活随笔
收集整理的這篇文章主要介紹了
CodeForces - 888G Xor-MST(贪心+字典树+最小生成树)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出 nnn 個點,任意兩個點之間的邊權為 ai⊕aja_i\oplus a_jai?⊕aj?,求最小生成樹
題目分析:去年多校寫過一樣的模型,再拿出來寫一遍回顧一下:牛客多校5 - Graph
時間復雜度 O(nlog2n)O(nlog^2n)O(nlog2n),一層 logloglog 是字典樹帶著的,第二層 logloglog 是需要在子樹中查詢異或值最小
有個小坑點是答案會爆 intintint,不要看到異或就太想當然了
代碼:
// Problem: Xor-MST // Contest: Virtual Judge - CodeForces // URL: https://vjudge.net/problem/CodeForces-888G // Memory Limit: 262 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=2e5+100; int trie[N*30][2],tot; vector<int>node[N*30]; int newnode() {tot++;trie[tot][0]=trie[tot][1]=0;return tot; } void insert(int x) {int pos=0;for(int i=29;i>=0;i--) {int to=x>>i&1;if(!trie[pos][to]) {trie[pos][to]=newnode();}pos=trie[pos][to];}if(node[pos].empty()) {node[pos].push_back(x);} } int search(int pos,int x,int dep) {int ans=0;for(int i=dep;i>=0;i--) {int to=x>>i&1;if(trie[pos][to]) {pos=trie[pos][to];} else {pos=trie[pos][!to];ans|=(1<<i);}}return ans; } LL solve(int rt,int dep) {LL ans=0;int ls=trie[rt][0],rs=trie[rt][1];if(ls) ans+=solve(ls,dep-1);if(rs) ans+=solve(rs,dep-1);if(ls&&rs) {int res=INT_MAX;for(auto it:node[ls]) {res=min(res,search(rs,it,dep-1));}ans+=res+(1<<dep);}node[rt].insert(node[rt].end(),node[ls].begin(),node[ls].end());node[rt].insert(node[rt].end(),node[rs].begin(),node[rs].end());return ans; } void init() {tot=-1;newnode(); } 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;scanf("%d",&n);for(int i=1,x;i<=n;i++) {read(x);insert(x);}cout<<solve(0,29)<<endl;return 0; } 超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的CodeForces - 888G Xor-MST(贪心+字典树+最小生成树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: UOJ - #117. 欧拉回路(模板)
- 下一篇: Gym - 101173H Hangar