AcWing - 103 - 电影(离散化)

题目链接
  没什么好说的,就照着题意做就行了,不过要最后输出的编号是电影在c或者d数组里的下标而不是值。之前用unordered_map跑了1500ms,这个跑了350ms,常数真是个可怕的东西

const int maxn = 2e5+10;
int a[maxn], b[maxn], c[maxn], d[maxn], cnt[maxn];
int bnsh(int l, int r, int x) {
    while(l<=r) {
        int mid = (l+r)>>1;
        if (b[mid]==x) return mid;
        if (b[mid]<x) l = mid+1;
        else r =  mid-1;
    }
    return -1; 
    //我们二分查找在a数组是否存在这个数
    //如果不存在就是-1存在就是它的下标,这样来进行离散化
}
int main(void) {
    int n, m;
    scanf("%d", &n);
    for (int i = 0; i<n; ++i) scanf("%d", &a[i]);
    scanf("%d", &m);
    for (int i = 0; i<m; ++i) scanf("%d", &c[i]);
    for (int i = 0; i<m; ++i) scanf("%d", &d[i]);
    sort(a, a+n);
    for (int i = 0; i<n; ++i) b[i] = a[i];
    int len = unique(b, b+n)-b-1; //去重
    for (int i = 0; i<n; ++i) {
        int tmp = bnsh(0, len, a[i]); //对数组a离散化并统计数量
        if (~tmp) ++cnt[tmp];
    }
    for (int i = 0; i<m; ++i) {
        //对数组b和c离散化,之所以不和上面放一起是因为n和m大小不同
        c[i] = bnsh(0, len, c[i]);
        d[i] = bnsh(0, len, d[i]);
    }
    int maxx = 0, maxx2 = 0, ans = 1;
    for (int i = 0; i<m; ++i) {
        if (c[i]!=-1 && maxx<cnt[c[i]]) {
            ans = i+1;
            maxx = cnt[c[i]];
            maxx2 = cnt[d[i]];
        }
        else if (c[i]!=-1 && d[i]!=-1 && maxx==cnt[c[i]] && maxx2<cnt[d[i]]) {
            ans = i+1;
            maxx2 = cnt[d[i]];
        }
    }
    printf("%d\n", ans);
    return 0;
}
posted @ 2020-03-24 17:23  shuitiangong  阅读(198)  评论(0编辑  收藏  举报