forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkingdoms.cpp
116 lines (97 loc) · 2.07 KB
/
kingdoms.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
bool onebit(ll n) {
return n && !(n & (n-1));
}
ll getbit(ll n) {
ll ct = 0;
while(n > 0) {
ct++;
n >>= 1;
}
return ct;
}
vector<ll> getallbit(ll n) {
vector<ll> res;
ll ct = 0;
while(n > 0) {
if(n&1) res.push_back(ct);
n >>= 1;
ct++;
}
return res;
}
ll unset(ll n, ll bit) {
return n & ~(1 << bit);
}
struct lex_compare {
bool operator() (const ll& i1, const ll& i2) {
if(getbit(i1) == getbit(i2)) {
return i1 > i2;
}
return getbit(i1) > getbit(i2);
}
};
void getnext(vector<vector<ll>>& v, set<ll, lex_compare>& states, ll curr, ll n) {
vector<ll> keep = getallbit(curr);
vector<ll> owe(n,0);
for(auto i : keep) {
for(auto j : keep) {
owe[i] += v[i][j];
}
}
for(auto i : keep) {
if(owe[i] > 0) {
states.insert(unset(curr,i));
}
}
}
void solve() {
ll n;
cin >> n;
// v[i][j]=x means i owes j x dollars
// Read in this case
vector<vector<ll>> v(n, vector<ll>(n));
for(ll i = 0; i < n; i++) {
for(ll j = 0; j < n; j++) {
cin >> v[i][j];
}
}
// Get starting number
ll start = 0;
for(ll i = 0; i != n; i++) {
start |= (1<<i);
}
// Build set of all states
set<ll, lex_compare> states;
states.insert(start);
// Process all possible states
set<ll> answer;
while(!states.empty()) {
ll curr = *states.begin();
states.erase(curr);
// If one bit, add it to answer
if(onebit(curr)) {
answer.insert(getbit(curr));
continue;
}
// Otherwise, get all 'next' from it
getnext(v, states, curr, n);
}
// Print the answer
if(answer.size() == 0) {
cout << "0";
}
for(auto i : answer) {
cout << i << " ";
}
cout << endl;
}
int main() {
ll cases;
cin >> cases;
while(cases--) {
solve();
}
}