原题地址:https://ac.nowcoder.com/acm/contest/882/D
题意:求一个无向图的第 k k k小的团
思路:团的问题一般使用 d f s dfs dfs来解决问题。由于要求 k k k小团,所以我们可以使用一个优先队列来存储所有的所有团的信息,用 b i t s e t bitset bitset来记录当前选了哪些点,权值,以及最后加入团的编号(这是为了防止重复,每次选择下一个点就从这个编号开始)
这里有一个很重要的优化:要判断某个点能否加入某个团,可以将这个团的状态st,和代表这个点的邻接矩阵行进行位&操作,如果最后还等于状态st,就说明该点可以加入这个团。
#include <bits/stdc++.h>
#define eps 1e-8
#define INF 0x3f3f3f3f
#define PI acos(-1)
#define lson l,mid,rt<<1
#define rson mid+1,r,(rt<<1)+1
#define CLR(x,y) memset((x),y,sizeof(x))
#define fuck(x) cerr << #x << "=" << x << endl
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int seed = 131;
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;
int n, k;
struct node {
ll w;//权重
int id;//最后入团的点
bitset<105>st;//表示状态
bool operator <(const node &a)const {
return w > a.w;
}
node() {}
node(ll w, int id, bitset<105>st): w(w), id(id), st(st) {}
};
priority_queue<node>q;
ll a[105];
bitset<105>mp[105];
char str[maxn];
int main() {
scanf("%d%d", &n, &k);
for (int i = 0; i < n; i++) scanf("%lld", &a[i]);
for (int i = 0; i < n; i++) {
scanf("%s", str);
for (int j = 0; j < n; j++) {
if (str[j] == '1')mp[i][j] = 1;
}
fuck(mp[i]);
}
bitset<105>bt;
for (int i = 0; i < n; i++) {
bt.set(i);
q.push(node(a[i], i, bt));
bt.reset(i);
}
int cnt = 1;
ll ans = 0;
while (!q.empty() && cnt < k) {
node tmp = q.top();
q.pop();
cnt++;
ans = tmp.w;
for (int i = tmp.id + 1; i < n; i++) {
if ((mp[i]&tmp.st) == tmp.st) {
tmp.st[i] = 1;
q.push(node(tmp.w + a[i], i, tmp.st));
tmp.st[i] = 0;
}
}
}
if (cnt < k) printf("-1\n");
else printf("%lld\n", ans);
return 0;
}
/*
4 8
8 2 7 5
0010
0011
1100
0100
*/