bzoj 1306 [CQOI2009]match循环赛 meet in the middle
题面
解法
显然可以用meet in the middle解决
时间复杂度:\(O(3^\frac{m}{2}×n)\)(map自带巨大常数)
bzoj上竟然9916ms苟过去了
当然还有更好的算法,剪枝力度也比较强,这里就不再赘述了
代码
#include <bits/stdc++.h>
#define N 100
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
x = 0; int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
int n, tot;
long long ans;
struct Info {
int num[10];
bool operator < (const Info &a) const {
for (int i = 1; i <= n; i++)
if (num[i] != a.num[i]) return num[i] < a.num[i];
return false;
}
} a, b;
struct Node {
int x, y;
} c[N];
map <Info, int> h;
bool check(Info x) {
for (int i = 1; i <= n; i++)
if (x.num[i] > a.num[i]) return false;
return true;
}
void dfs1(int x, int lim, Info y) {
if (!check(y)) return;
if (x > lim) {h[y]++; return;}
Info z = y; z.num[c[x].x] += 3; dfs1(x + 1, lim, z);
z = y, z.num[c[x].x]++, z.num[c[x].y]++, dfs1(x + 1, lim, z);
z = y, z.num[c[x].y] += 3; dfs1(x + 1, lim, z);
}
void dfs2(int x, int lim, Info y) {
if (!check(y)) return;
if (x > lim) {
for (int i = 1; i <= n; i++) y.num[i] = a.num[i] - y.num[i];
ans += h[y]; return;
}
Info z = y; z.num[c[x].x] += 3; dfs2(x + 1, lim, z);
z = y, z.num[c[x].x]++, z.num[c[x].y]++, dfs2(x + 1, lim, z);
z = y, z.num[c[x].y] += 3; dfs2(x + 1, lim, z);
}
int main() {
read(n);
for (int i = 1; i <= n; i++) read(a.num[i]);
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
c[++tot] = (Node) {i, j};
dfs1(1, tot / 2, b); dfs2(tot / 2 + 1, tot, b);
cout << ans << "\n";
return 0;
}