華爲機試 黑白棋子最佳匹配(全排列)

題目:棋盤上有黑白兩種顏色的棋子,選出一對黑白棋子,若白棋的橫座標小於黑棋的橫座標,白棋的縱座標小於黑棋的縱座標,則稱這一對棋子爲匹配。求任意個數的黑白棋中最佳匹配的對數。
輸入:白棋個數,黑棋個數
白棋的橫縱座標
黑棋的橫縱座標
例如:

2 2
1 1 2 2
1 1 2 2

則輸出爲1
分析:可以對黑白棋中個數較多的一方進行全排列,然後進行比較,找出最大匹配度。若黑白棋的個數均爲n,則問題的時間複雜度爲n!。

#include <iostream>
#include <vector>
using namespace std;

class Pos
{
public:
    void set (int i, int j)
    {
        x = i, y = j;
    }
    int getx()
    {
        return x;
    }
    int gety()
    {
        return y;
    }
private:
    int x;
    int y;
};

int max_match_degree = 0;
vector<Pos> black, white;

int match(vector<Pos>& w, vector<Pos> b)
{
    int num = w.size() < b.size() ? w.size() : b.size();
    int match_degree=0;
    for (int i = 0; i < num; ++i)
    {
        if (w[i].getx() < b[i].getx() && w[i].gety() < b[i].gety())
            ++match_degree;
    }
    return match_degree;
}

void permutation(vector<Pos>::iterator begin, vector<Pos>::iterator end, vector<Pos>::iterator start )
{
    if (start == end)
    {
        int num = match(white, black);
        if (num > max_match_degree)
            max_match_degree = num;
        return;
    }
    else
    {
        for (auto b = start; b != end; ++b)
        {
            auto temp = *b;
            *b = *start;
            *start = temp;
            permutation(begin, end, start+1);
            temp = *b;
            *b = *start;
            *start = temp;
        }
    }
}



int main()
{
    int black_num, white_num,x,y;

    Pos temp;
    cin >> white_num >> black_num;
    for (int i = 0; i < white_num; ++i)
    {
        cin >> x >> y;
        temp.set(x, y);
        white.push_back(temp);
    }
    for (int i = 0; i < black_num; ++i)
    {
        cin >> x >> y;
        temp.set(x, y);
        black.push_back(temp);
    }
    if (white.size()>black.size())
    permutation(white.begin(), white.end(),white.begin());
    else
        permutation(black.begin(), black.end(), black.begin());
    cout << max_match_degree << endl;
}

測試結果如下
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章