1. 程式人生 > 其它 >I - Vitya and Strange Lesson CodeForces - 842D

I - Vitya and Strange Lesson CodeForces - 842D

 

【題目意思】:

  找出修改後的序列中,沒出現的最小正整數。

  修改操作是 將x與序列中所有數異或。(每次異或之後替代原序列的值)。

【解題思路】:

  題目要求是找出不在序列裡的的最小值。而字典樹正好是解決異或最值問題的,所以我們將不在序列裡的所有數放進字典樹裡面,進行異或操作,求出其中的最小值。

  字典樹求最小值 是 從最高位開始,判斷每一位(2進位制)上的值是否與自身在這一位上的值相等(異或是相等為0,不相等為1),如果相等,則走下去,如果不相等,只能走那一條路。

  如何儲存異或後的序列:

    根據異或的性質。 a⊕b = c => a = b⊕c => b = a ⊕ c ;

    所以記錄異或後的序列,只要將每次的x異或起來,在與序列異或。

【程式碼】:

 

#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <bitset>
#include <cstdlib>
#include 
<cmath> #include <set> #define ms(a, b) memset(a,b,sizeof(a)) #define fast ios::sync_with_stdio(false); cin.tie(0); cout.tie(0) #define ll long long #define ull unsigned long long #define rep(i, a, b) for(ll i=a;i<=b;i++) #define lep(i, a, b) for(ll i=a;i>=b;i--) #define endl '\n' #define
pii pair<int, int> #define pll pair<ll, ll> #define vi vector<ll> #define vpi vector<pii> #define vpl vector<pll> #define mi map<ll,ll> #define all(a) (a).begin(),(a).end() #define gcd __gcd #define pb push_back #define mp make_pair #define lb lower_bound #define ub upper_bound #define ff first #define ss second #define test4(x, y, z, a) cout<<"x is "<<x<<" y is "<<y<<" z is "<<z<<" a is "<<a<<endl; #define test3(x, y, z) cout<<"x is "<<x<<" y is "<<y<<" z is "<<z<<endl; #define test2(x, y) cout<<"x is "<<x<<" y is "<<y<<endl; #define test1(x) cout<<"x is "<<x<<endl; using namespace std; const int N = 3e5 + 10; const int maxx = 0x3f3f3f; const int mod = 1e9 + 7; const int minn = -0x3f3f3f; const int M = 2 * N; ll T, n, m; ll a[N]; ll son[N*32][2],idx,cnt[N*32]; ll vis[N*2 ]; void insert(ll n ){ int p=0; for ( int i=32;i>=0;i--){ int u = (n>>i)&1 ; if ( !son[p][u] ) son[p][u] = ++idx; p = son[p][u]; } cnt[p] = n; } ll query(ll n){ int p = 0; for ( int i=32;i>=0;i--){ int u = (n>>i)&1; if ( son[p][u] ){ p = son[p][u]; }else{ p = son[p][u^1]; } } return n^cnt[p]; } void solve() { cin>>n>>m; rep(i,1,n) {cin>>a[i]; vis[a[i]]=1 ;} rep(i,0,2*N){ if ( !vis[i] ) { insert(i); } } ll h = 0; ll x; rep(i,1,m){ cin>>x; h = h^x; cout<<query(h)<<endl; } } int main() { fast; solve(); return 0; }
View Code