#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include<stdio.h>
using namespace std;
const int infinity = 0x3ffffff;
struct node
{
vector<int> selection;
int lb;
node() {}
node(vector<int> &v, int b)
{
selection = v;
lb = b;
}
bool operator>(const node &a) const
{
return lb > a.lb;
}
};
int getNodeLb(vector<int> selection, int **arr, int n, int m)
{
int index_i = 0;
int sum = 0;
vector<int>::iterator it;
for (it = selection.begin(); it != selection.end(); it++, index_i++)
{
int index_j = *it;
sum += *((int *)arr + index_i * m + index_j);
}
for (int i = selection.size(); i < n; i++)
{
int minval = infinity;
for (int j = 0; j < m; j++)
{
int flag = count(selection.begin(), selection.end(), j);
if (flag)
continue;
else
minval = min(minval, *((int *)arr + i * m + j));
}
sum += minval;
}
return sum;
}
int main()
{
freopen("in.txt", "r", stdin);
int n, m;
cin >> n >> m;
int c[n][m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin >> c[i][j];
}
}
priority_queue<node, vector<node>, greater<node> > tree;
vector<int> start;
node root(start,getNodeLb(start,(int**)c,n,m));
tree.push(root);
while(1)
{
vector<int> uplayer = tree.top().selection;
cout<<"root :: "<<tree.top().lb<<endl;
tree.pop();
for (int j = 0; j < n; j++)
{
vector<int> nowlayer(uplayer);
int flag = count(uplayer.begin(), uplayer.end(), j);
if (!flag)
{
nowlayer.push_back(j);
int tmp = getNodeLb(nowlayer, (int **)c, n, m);
node new_node(nowlayer, tmp);
tree.push(new_node);
cout<<j+1<<" :: "<<tmp<<endl;
}
}
int tmp = tree.top().selection.size();
if(tmp==n-1) break;
}
cout<<tree.top().lb<<endl;
}
測試用例
4 4
9 2 7 8
6 4 3 7
5 8 1 8
7 6 9 4
***********
3 3
10 2 3
2 3 4
3 4 5