题目
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 a 1, a 2, …, a n (1 ≤ a i ≤ 100), where a i 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 b 1, b 2, …, b m (1 ≤ b j ≤ 100), where b j is the j-th girl’s dancing skill.
Output
Print a single number — the required maximum possible number of pairs.
Examples
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、这道题的意思,就是问两个序列中元素差值<=1的有多少个。
1、这道题,读题的时候就想着用list来做,放数组里肯定是不行的,因为用过的元素不能再用了,但是再实际操作过程中,遇到很多问题,特别是list再遍历过程中remove元素,这里还是比较薄弱的地方。其实思路挺简单的,就是判断。这里需要注意的还有一点,数据需要先排序,然后才能保证最大程度的利用元素。下面给出代码。
参考代码
package weekC;
/**
* 思路挺简单的,实现起来,不太容易,就当是练习了一下List的用法
* 需要排一下序
* 容易出现
* 6 4 5 6
* 4 5 5 6
* 如果不排序直接比较可能最后结果会出错
*
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class F {
static int sum=0;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int arr[]=new int[a];
for(int i=0;i<a;i++)
arr[i]=sc.nextInt();
int b=sc.nextInt();
int arr2[]=new int[b];
for(int i=0;i<b;i++)
arr2[i]=sc.nextInt();
Arrays.sort(arr);
Arrays.sort(arr2);
List<Integer> l1=new ArrayList<Integer>();
List<Integer> l2=new ArrayList<Integer>();
for(int i=0;i<arr.length;i++)
l1.add(arr[i]);
for(int i=0;i<arr2.length;i++)
l2.add(arr2[i]);
int cu[]=new int[2];
while(cunzai(l1, l2)) {
sum++;
cu=find(l1, l2);
l1.remove(cu[0]);
l2.remove(cu[1]);
}
System.out.println(sum);
}
static boolean cunzai(List<Integer> list,List<Integer> list2) {
for(int i=0;i<list.size();i++) {
for(int j=0;j<list2.size();j++) {
if(list.get(i)==list2.get(j)||list.get(i)-list2.get(j)==1||list.get(i)-list2.get(j)==-1) {
// System.out.println("i="+i+" j="+j);
return true;
}
}
}
return false;
}
static int[] find(List<Integer> list,List<Integer> list2) {
int arr[]=new int[2];
c:
for(int i=0;i<list.size();i++) {
for(int j=0;j<list2.size();j++) {
if(list.get(i)==list2.get(j)||list.get(i)-list2.get(j)==1||list.get(i)-list2.get(j)==-1) {
arr[0]=i;
arr[1]=j;
break c;
}
}
}
return arr;
}
}