二分 hdu2141 Can you find it?

来源:互联网 发布:js定义有返回值的函数 编辑:程序博客网 时间:2024/05/22 10:31

如果枚举A和B,再在C中二分k-a-b必然超时


但是看到A和B的数量都只有500个,所以可以先把A,B两个加起来,组成一个新的D

然后枚举C,在D中二分k-c,这样复杂度就减少很多了


#include<cstdio>#include<cmath>#include<cstring>#include<queue>#include<vector>#include<functional>#include<algorithm>using namespace std;typedef long long LL;typedef pair<int, int> PII;const int MX = 1000 + 5;const int INF = 0x3f3f3f3f;const double exps = 1e-8;LL A[MX], B[MX], C[MX], D[MX*MX];int BS(LL A[], int L, int R, int x) {    int l = L, r = R, m;    while(l <= r) {        m = (l + r) >> 1;        if(A[m] == x) return m;        if(A[m] < x)  l = m + 1;        else        r = m - 1;    }    return -1;}int main() {    int N1, N2, N3, ansk = 0;    while(~scanf("%d%d%d", &N1, &N2, &N3)) {        for(int i = 1; i <= N1; i++) {            scanf("%I64d", &A[i]);        }        for(int i = 1; i <= N2; i++) {            scanf("%I64d", &B[i]);        }        for(int i = 1; i <= N3; i++) {            scanf("%I64d", &C[i]);        }        int tot = 0;        for(int i = 1; i <= N1; i++) {            for(int j = 1; j <= N2; j++) {                D[++tot] = A[i] + B[j];            }        }        sort(D + 1, D + tot + 1);        tot = unique(D + 1, D + tot + 1) - D - 1;        int Q;        LL k;        scanf("%d", &Q);        printf("Case %d:\n", ++ansk);        while(Q--) {            scanf("%I64d", &k);            bool sign = false;            for(int i = 1; i <= N3; i++) {                LL s = k - C[i];                if(BS(D, 1, tot, s) != -1) {                    sign = true;                    break;                }            }            printf("%s\n", sign ? "YES" : "NO");        }    }    return 0;}


0 0
原创粉丝点击