2012-04-22 10:58:21Morris

[ZJ] a450. 棒棒糖比身高

內容 :

傳說,棒棒糖也會比身高 ( Candy Candy Girl~~ )

輸入說明 :

第一行有兩個正整數 N , Q , 代表有N根棒棒糖和Q筆詢問

( 1 <= N,Q <= 1,000,000 )

再來有N個正整數Ai( 1 <= Ai <= 1,000,000,000 ) ,分別代表每根棒棒糖的高度

接下來有Q行,每行有兩個正整數 a , b ( 1 <= a <= b <= 1,000,000,000 )

輸出說明 :

對於每筆詢問,請輸出高度介於 a - b 的棒棒糖數目 ( 包含a和b )

找不到請輸出 "The candies are too short" (不包含雙引號) 

範例輸入 :help

5 3
2 3 7 9 0
2 6
2 8
1 1

範例輸出 :

2  // 身高介於  2 - 6 的有 2 3
3  // 身高介於  2 - 8 的有 2 3 7
The candies are too short // 找不到身高介於 1 - 1 之間的

提示 :

至少有40%測資 N <= 10,000 且 Q <= 10,000 且 Ai <= 1,000,000

2012/4/13 題目修正,不用多筆輸入,每筆側資只有一組輸入

因為棒棒糖很猥瑣,所以時間卡的很緊!

出處 :

從其他題目中突發奇想~ (管理:stanley17112000)



#include <stdio.h>
#include <algorithm>
using namespace std;

struct Node {
    int x, y;
};
inline int ReadInt(int *x) {
    static char c, neg;
    while((c = getchar()) < '-')    {if(c == EOF) return EOF;}
    neg = (c == '-') ? -1 : 1;
    *x = (neg == 1) ? c-'0' : 0;
    while((c = getchar()) >= '0')
        *x = (*x << 3) + (*x << 1) + c-'0';
    *x *= neg;
    return 1;
}
bool cmp1(Node i, Node j) {
    return i.x < j.x;
}
bool cmp2(Node i, Node j) {
    return i.y < j.y;
}
int main() {
    int N, Q, i, a, b, x, y;
    while(scanf("%d %d", &N, &Q) == 2) {
        int j = 0;
        int *A = new int[N];
        int *ans = new int[Q];
        Node *FA = new Node[Q];
        Node *FB = new Node[Q];
        for(i = 0; i < N; i++) {
            ReadInt(&A[i]);
        }
        for(i = 0; i < Q; i++) {
            ReadInt(&FA[i].x);
            ReadInt(&FB[i].x);
            FA[i].y = i;
            FB[i].y = i;
        }
        sort(A, A+N);
        sort(FA, FA+Q, cmp1);
        sort(FB, FB+Q, cmp1);
        int idx1 = 0, idx2 = 0;
        while(idx1 < N && idx2 < Q) {
            if(A[idx1] < FA[idx2].x)
                idx1++;
            else {
                FA[idx2].x = idx1;
                idx2++;
            }
        }
        while(idx2 < Q) FA[idx2++].x = idx1;

        idx1 = 0, idx2 = 0;
        while(idx1 < N && idx2 < Q) {
            if(A[idx1] <= FB[idx2].x)
                idx1++;
            else {
                FB[idx2].x = idx1;
                idx2++;
            }
        }
        while(idx2 < Q) FB[idx2++].x = idx1;
        for(i = 0; i < Q; i++) {
            ans[FA[i].y] = FA[i].x;
        }
        for(i = 0; i < Q; i++) {
            ans[FB[i].y] = FB[i].x - ans[FB[i].y];
        }
        for(i = 0; i < Q; i++) {
            if(ans[i])
                printf("%d\n", ans[i]);
            else
                puts("The candies are too short");
        }
        delete[] A;
        delete[] FA;
        delete[] FB;
    }
    return 0;
}