hdu2578 Dating with girls(1) (二分 || map)

題目鏈接:點擊打開鏈接


在這題中使用二分查找比使用map查找更快


二分查找法代碼如下(625ms):

#include <cstdio>
#include <algorithm>
using namespace std;

const int N = 111111;
int a[N];

int main()
{
    int t, n, *m, k, cnt, f;
    scanf("%d", &t);
    while(t-- && scanf("%d%d", &n, &k)) {
        cnt = 0, f = 0;
        for(int i = 0; i < n; i++) scanf("%d", a + i);
        sort(a, a + n);
        m = unique(a, a + n);
        for(int i = 0; i < m - a; i++) {
            if(a[i] << 1 > k) break;
            if(binary_search(a, m, k - a[i])) {
                if(a[i] << 1 == k) f = 1;
                cnt++;
            }
        }
        cnt <<= 1;
        printf("%d\n", f ? cnt - 1 : cnt);
    }
    return 0;
}

map查找法代碼如下(1390ms):

#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;

const int N = 111111;
int a[N];
map<int, int> m;

int main()
{
    int t, n, k, f, cnt;
    scanf("%d", &t);
    while(t-- && scanf("%d%d", &n, &k)) {
        m.clear();
        cnt = 0, f = 0;
        for(int i = 0; i < n; i++) {
            scanf("%d", a + i);
            m[a[i]] = 1;
        }
        sort(a, a + n);
        int l = unique(a, a + n) - a;
        for(int i = 0; i < l; i++) {
            if(a[i] << 1 > k) break;
            if(m[k - a[i]]) {
                if(a[i] << 1 == k) f = 1;
                cnt++;
            }
        }
        cnt <<= 1;
        printf("%d\n", f ? cnt - 1 : cnt);
    }
    return 0;
}




發佈了40 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章