题目:http://community.topcoder.com/stat?c=problem_statement&pm=11705&rd=15491
参考:http://apps.topcoder.com/wiki/display/tc/SRM+571
用的是与D2L3类似的方法,还可以用 优化的 Bron–Kerbosch algorithm。
代码:
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;
#define CHECKTIME() printf("%.2lf\n", (double)clock() / CLOCKS_PER_SEC)
typedef pair<int, int> pii;
typedef long long llong;
typedef pair<llong, llong> pll;
#define mkp make_pair
/*************** Program Begin **********************/
class MagicMolecule {
public:
vector <int> magicPower;
vector <string> magicBond;
vector <pii> edges;
int n, res;
bool used[55];
void backtrack(int p, int cnt)
{
if (p == edges.size()) { // base case
int sum = 0;
for (int i = 0; i < n; i++) {
if (!used[i]) {
sum += magicPower[i];
}
}
res = max(res, sum);
return;
}
int x = edges[p].first, y = edges[p].second;
if (used[x] || used[y]) {
// ignore, process next edge
backtrack(p + 1, cnt);
} else {
if ( (cnt + 1) * 3 <= n ) {
// add x
used[x] = true;
backtrack(p + 1, cnt + 1);
used[x] = false;
// add y
used[y] = true;
backtrack(p + 1, cnt + 1);
used[y] = false;
}
}
}
int maxMagicPower(vector <int> magicPower, vector <string> magicBond) {
n = magicPower.size();
this->magicPower = magicPower;
this->magicBond = magicBond;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && magicBond[i][j] == 'N') {
edges.push_back(mkp(i, j));
}
}
}
res = 0;
memset(used, 0, sizeof(used));
backtrack(0, 0);
res = (res == 0 ? -1 : res);
return res;
}
};
/************** Program End ************************/