匈牙利算法(素数伴侣(HW1112))

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<string>
#include<stdio.h>
#include<stdlib.h>
using namespace std;

const int N = 101;
bool isSushu(int n)
{
    if (n % 2 == 0 || n % 3 == 0) return false;
    else{
        for (int i = 5; i*i <= n; i += 6)
            if (n%i == 0 || n % (i + 2) == 0) return false;
        return true;
    }
}
int n1, n2, ans;
int result[N];
bool state[N];
bool map[N][N];

bool find(int x)
{
    for (int i = 1; i <= n2; ++i){
        if (map[x][i] && !state[i]){
            state[i] = true;
            if (result[i] == 0 || find(result[i])){
                result[i] = x;
                return true;
            }
        }
    }
    return false;
}
int hungary()
{
    for (int i = 1; i <= n1; ++i){
        memset(state, 0, sizeof(state));
        if (find(i)) ++ans;
    }
    return ans;
}

class xx{
    string &name;
};
int main()
{
    int n, val;
    vector<int> odd, even;
    scanf("%d", &n);
    for (int i = 0; i < n; ++i){
        scanf("%d", &val);
        if (val % 2 == 0) even.push_back(val);
        else odd.push_back(val);
    }
    memset(map, 0, sizeof(map));

    for (int i = 0; i < odd.size(); ++i){
        for (int j = 0; j < even.size(); ++j){
            if (isSushu(odd[i] + even[j])) map[i + 1][j + 1] = true;
        }
    }

    memset(result, 0, sizeof(result));
    n1 = odd.size(); n2 = even.size(); ans = 0;
    cout << hungary() << endl;
}

 

posted @ 2015-09-01 21:31  湛雷冲  阅读(1205)  评论(0编辑  收藏  举报