思路:
我们发现下一次的灌水次数只和当前每个人被灌的奇偶有关,也就是0和1.
那我们就直接用状压,直到找到环后就求答案
c o d e code code
#include<iostream>
#include<cstdio>
#define ll long long
using namespace std;
const ll MAXN = 21;
ll ans, p[1 << MAXN], k;
ll n, h;
ll a[MAXN], a1[MAXN];
ll head[MAXN], tot, f[1 << MAXN];
bool v[MAXN], v1[MAXN];
struct node {
ll to, next;
}b[MAXN * 4];
void add(ll x, ll y) {
b[++tot] = (node){ y, head[x] };
head[x] = tot;
}
int main() {
scanf("%lld%lld", &n, &h);
for(ll i = 1; i <= n; i ++)
for(ll j = 1; j <= n; j ++) {
ll x;
scanf("%1lld", &x);
if(x) add(i, j);
}
bool flag = 0;
h --;
for(ll i = head[1]; i; i = b[i].next) {
ll y = b[i].to;
a[y] = 1, ans ++;
}
if(!h) { printf("%lld", ans); return 0; }
p[1] = ans;
ll s = 0, g = 1, q = 0;
k = ans;
while(1) {
g ++;
s = 0;
for(ll i = 1; i <= n; i ++) {
for(ll j = head[i]; j; j = b[j].next) {
ll y = b[j].to;
if(a[i] % 2 == 1) a1[y] += 1;
else a1[y] += 2;
}
}
for(ll i = 1; i <= n; i ++)
a[i] = a1[i], k += a1[i], a1[i] = 0;
p[g] = k;
for(ll i = 1; i <= n; i ++)
if(a[i] % 2 == 1) s = s ^ (1 << i - 1);
if(f[s]) { q = f[s]; break; }
f[s] = g;
}
if(!h) { printf("%lld", p[g]); return 0; }
else printf("%lld", (h - q + 1) / (g - q) * (p[g] - p[q]) + p[q] + p[q + (h - q + 1) % (g - q)] - p[q]);
return 0;
}