Light oj 1149--Factors and Multiples【二分匹配 && 经典建图】

1149 - Factors and Multiples
PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB

You will be given two sets of integers. Let's call them set A and set B. Set A contains n elements and set B contains m elements. You have to remove k1 elements from set A and k2 elements from set B so that of the remaining values no integer in set B is a multiple of any integer in set Ak1 should be in the range [0, n] and k2 in the range [0, m].

You have to find the value of (k1 + k2) such that (k1 + k2) is as low as possible. P is a multiple of Q if there is some integer K such that P = K * Q.

Suppose set A is {2, 3, 4, 5} and set B is {6, 7, 8, 9}. By removing 2 and 3 from A and 8 from B, we get the sets {4, 5} and {6, 7, 9}. Here none of the integers 6, 7 or 9 is a multiple of 4 or 5.

So for this case the answer is 3 (two from set A and one from set B).

Input

Input starts with an integer T (≤ 50), denoting the number of test cases.

The first line of each case starts with an integer n followed by n positive integers. The second line starts with m followed by m positive integers. Both n and m will be in the range [1, 100]. Each element of the two sets will fit in a 32 bit signed integer.

Output

For each case of input, print the case number and the result.

Sample Input

Output for Sample Input

2

4 2 3 4 5

4 6 7 8 9

3 100 200 300

1 150

Case 1: 3

Case 2: 0

 


#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int map[110][110];
int a[110], b[110];
int n, m;
int used[110], link[110];

bool dfs(int x){
    for(int i = 1; i <= n; ++i){
        if(map[x][i] && !used[i]){
            used[i] = 1;
            if(link[i] == -1 || dfs(link[i])){
                link[i] = x;
                return true;
            }
        }
    }
    return false;
}

void hungary(){
    int ans = 0;
    memset(link, -1, sizeof(link));
    for(int j = 1; j <= m; ++j){
        memset(used, 0, sizeof(used));
        if(dfs(j))
            ans++;
    }
    printf("%d\n", ans);
}

int main (){
    int T;
    scanf("%d", &T);
    int k = 1;
    while(T--){
        memset(map, 0, sizeof(map));
        scanf("%d", &n);
        for(int i = 1; i <= n; ++i)
            scanf("%d", &a[i]);
        scanf("%d", &m);
        for(int i = 1; i <= m; ++i)
            scanf("%d", &b[i]);
        for(int i = 1; i <= m; ++i){
            for(int j = 1; j <= n; ++j){
                if(b[i] % a[j] == 0)
                    map[i][j] = 1;
            }
        }
        printf("Case %d: ", k++);
        hungary();
    }
    return 0;
}


你可能感兴趣的:(Light oj 1149--Factors and Multiples【二分匹配 && 经典建图】)