HDU Problem - 3763 CD(二分)

题目链接

Problem Description

Jack and Jill have decided to sell some of their Compact Discs, while they still have some value. They have decided to sell one of each of the CD titles that they both own. How many CDs can Jack and Jill sell?Neither Jack nor Jill owns more than one copy of each CD.

Input

The input consists of a sequence of test cases. The first line of each test case contains two non-negative integers N and M, each at most one million, specifying the number of CDs owned by Jack and by Jill, respectively. This line is followed by N lines listing the catalog numbers of the CDs owned by Jack in increasing order, and M more lines listing the catalog numbers of the CDs owned by Jill in increasing order. Each catalog number is a positive integer no greater than one billion. The input is terminated by a line containing two zeros. This last line is not a test case and should not be processed.

Output

For each test case, output a line containing one integer, the number of CDs that Jack and Jill both own.

Sample Input

3 3
1
2
3
1
2
4
0 0

Sample Output

2

AC

  • 统计重复数字的个数
  • 本来想用map,但是内存不够
  • 二分
#include <iostream>
#include <stdio.h>
#include <map>
#include <vector>
#include <queue>
#include <algorithm>
#define N 2000005
#define ll long long
#define P pair<int, int>
#define mk make_pair
using namespace std;
ll a[N];

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif
    int n, m;
    while (scanf("%d%d", &n, &m), n && m) {
        for (int i = 0; i < n + m; ++i) {
            scanf("%lld", &a[i]);
        }
        sort(a, a + n + m);
        int ans = 0;
        for (int i = 0; i < n + m; ++i) {
            int pos = upper_bound(a + i, a + n + m, a[i]) - a;
            ans += pos - i - 1;
            i = pos - 1;
        }
        printf("%d\n", ans);
    } 


    return 0;
} 
#include <iostream>
#include <stdio.h>
#include <map>
#include <vector>
#include <queue>
#include <algorithm>
#define N 2000005
#define ll long long
#define P pair<int, int>
#define mk make_pair
using namespace std;
ll a[N];

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif
    int n, m;
    while (scanf("%d%d", &n, &m), n && m) {
        for (int i = 0; i < n + m; ++i) {
            scanf("%lld", &a[i]);
        }
        sort(a, a + n + m);
        int ans = 0;
        for (int i = 0; i < n + m; ++i) {

            int l = i, r = n + m - 1;
            while (l < r) {
                int mid = (l + r) >> 1;
                if (a[mid] > a[i])  r = mid;
                else    l = mid + 1;
            }
            if (a[l] > a[i])    ans += l - i - 1, i = l - 1;
            else    ans += l - i, i = l;            

        }
        printf("%d\n", ans);
    }   
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/henuyh/article/details/81749627