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
| #include <cstdio> #include <queue> using namespace std; typedef long long LL; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; flag && (x = ~x + 1); } template <class Type> void write(Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar(x % 10 + '0'); } const LL inf = 1e18; const int N = 20, M = 110, K = 1 << 20; bool vis[K]; LL d[K]; int n, m, b1[M], b2[M], f1[M], f2[M], wt[M]; int main() { read(n), read(m); for (int i = 1; i <= m; i++) { read(wt[i]); static char str[N + 10]; scanf("%s", str); for (int j = 0; j < n; j++) { str[j] == '+' && (b1[i] |= 1 << j); str[j] == '-' && (b2[i] |= 1 << j); } scanf("%s", str); for (int j = 0; j < n; j++) { str[j] == '+' && (f2[i] |= 1 << j); str[j] == '-' && (f1[i] |= 1 << j); } } for (int i = 0; i < (1 << n); i++) d[i] = inf; d[(1 << n) - 1] = 0; queue<int> q; q.push((1 << n) - 1); vis[(1 << n) - 1] = true; while (!q.empty()) { int t = q.front(); q.pop(); vis[t] = false; for (int i = 1; i <= m; i++) if ((t & b1[i]) == b1[i] && (t & b2[i]) == 0) { int j = t & (~f1[i]) | f2[i]; if (d[t] + wt[i] < d[j]) { d[j] = d[t] + wt[i]; if (!vis[j]) { q.push(j); vis[j] = true; } } } } write(d[0] == inf ? 0 : d[0]); return 0; }
|