Codeforces Round #277.5 (Div. 2)-B. BerSU Ball

http://codeforces.com/problemset/problem/489/B

B. BerSU Ball
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.

We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.

For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.

Input

The first line contains an integer n (1 ≤ n ≤ 100) — the number of boys. The second line contains sequence a1, a2, ..., an (1 ≤ ai ≤ 100), where ai is the i-th boy's dancing skill.

Similarly, the third line contains an integer m (1 ≤ m ≤ 100) — the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≤ bj ≤ 100), where bj is the j-th girl's dancing skill.

Output

Print a single number — the required maximum possible number of pairs.

Sample test(s)
input
4
1 4 6 2
5
5 1 5 7 9
output
3
input
4
1 2 3 4
4
10 11 12 13
output
0
input
5
1 1 1 1 1
3
1 2 3
output
2

解题思路: 将男孩和女孩升序排列, 分两种情况,1.当前男孩和女孩可以组成一组,那就组一组,2,当前南海比女孩的水平高1以上,查询下一个女孩,3,否则就查询下一个男孩,知道男孩或者女孩都选完

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 #include <time.h>
 6 #include <math.h>
 7 
 8 using namespace std;
 9 
10 int n, m, a[110], b[110];
11 
12 int cmp(const void *a, const void *b){
13     return *(int *)a - *(int *)b;
14 }
15 
16 void solve(){
17     int ans = 0, i = 0, j = 0;
18     while(i < n &&j < m){
19         if(a[i] > b[j] + 1){
20             j++;
21         }
22         else if(abs(a[i] - b[j]) == 1 || a[i] == b[j]){
23             ans++, i++, j++;
24         }
25         else{
26             i++;
27         }
28     }
29     printf("%d ", ans);
30 }
31 
32 int main(){
33     int i;
34     while(scanf("%d", &n) != EOF){
35         for(i = 0; i < n; i++){
36             scanf("%d", &a[i]);
37         }
38         qsort(a, n, sizeof(a[0]), cmp);
39         scanf("%d", &m);
40         for(i = 0; i < m; i++){
41             scanf("%d", &b[i]);
42         }
43         qsort(b, m, sizeof(b[0]), cmp);
44         solve();
45     }
46     return 0;

47 } 

原文地址:https://www.cnblogs.com/angle-qqs/p/4113646.html