Codechef Xor it (March 12 challenge)

來源:互聯網
上載者:User

標籤:style   http   ar   color   sp   for   on   art   bs   

題意很簡單,給定N <= 10^5個數,問你兩兩異或的前k小值。1 ≤ K ≤ min{250000, N*(N-1)/2},a[i] < 2^31

容易想到,要建一個0/1串的trie樹,然後考慮每層實際上就是二進位的每一位,然後我們看看ΣC(size,2)是否達到了k,因為這位有ΣC(size,2)對數異或值為0。我們要找的是第一個滿足條件的位元,統計前k小即可。實際實現的時候我們可以考慮,把一個數組排個序,其實每段區間就是trie樹中的每一層,不需要把trie建出來。二分位元,對每一位計算區間即可。

代碼參考了欽爺的代碼,感覺吊炸天

Code

#include <bits/stdc++.h>using namespace std;const int N = 100005;int n, k, a[N];vector<int> ans;int main() {scanf("%d%d", &n, &k);for (int i = 0; i < n; ++i)scanf("%d", &a[i]);sort(a, a + n);int l = -1, r = 31;while (l < r - 1) {int mid = l + r >> 1;long long sum = 0ll;int i, j;for (i = j = 1; i < n; ++i) {if ((a[i] ^ a[i - 1]) < 1 << mid)++j;//實際是trieelse sum += (long long)j * (j - 1) / 2, j = 1;}sum += (long long)j * (j - 1) / 2;if (sum >= k)r = mid;else l = mid;}if (r == 0)for (int i = 0; i < k; ++i)printf("0 ");else {int i, j;for (i = 1, j = 0; i < n; ++i) {if ((a[i] ^ a[i - 1]) < 1 << r) for (int l = j; l < i; ++l)ans.push_back(a[i] ^ a[l]);else j = i;}partial_sort(ans.begin(), ans.begin() + k, ans.end());for (i = 0; i < k; ++i)printf("%d ", ans[i]);}puts("");return 0;}


Codechef Xor it (March 12 challenge)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.