Advertisement
Dmaxiya

P2761 软件补丁问题 参考代码

Mar 17th, 2025
81
0
364 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long LL;
  5. const int maxn = (1 << 20) + 100;
  6. const int maxm = 100 + 100;
  7. const LL INF = 0x3f3f3f3f3f3f3f3f;
  8. struct Node {
  9.     int pos;
  10.     LL dis;
  11. };
  12.  
  13. bool operator<(const Node &a, const Node &b) {
  14.     return a.dis > b.dis;
  15. }
  16.  
  17. struct Edge {
  18.     LL dis;
  19.     int b1, b2, f1, f2;
  20.  
  21.     Edge() {}
  22.  
  23.     Edge(const string &s1, const string &s2, LL dis) : dis(dis) {
  24.         b1 = b2 = f1 = f2 = 0;
  25.         for (int i = 0; i < (int) s1.length(); ++i) {
  26.             if (s1[i] == '+') {
  27.                 b1 |= 1 << i;
  28.             }
  29.             if (s1[i] == '-') {
  30.                 b2 |= 1 << i;
  31.             }
  32.         }
  33.         for (int i = 0; i < (int) s2.length(); ++i) {
  34.             if (s2[i] == '-') {
  35.                 f1 |= 1 << i;
  36.             }
  37.             if (s2[i] == '+') {
  38.                 f2 |= 1 << i;
  39.             }
  40.         }
  41.     }
  42.  
  43.     Node get(int pos) {
  44.         if ((pos & b1) == b1 && (pos & (~b2)) == pos) {
  45.             return {(pos & (~f1)) | f2, dis};
  46.         }
  47.         return {0, INF};
  48.     }
  49. };
  50.  
  51. int n, m, w;
  52. bool vis[maxn];
  53. LL dis[maxn];
  54. string s1, s2;
  55. Edge edge[maxm];
  56. priority_queue<Node> que;
  57.  
  58. void dij(int s) {
  59.     memset(dis, 0x3f, sizeof(dis));
  60.     dis[s] = 0;
  61.     que.push({s, 0});
  62.     while (!que.empty()) {
  63.         Node tmp = que.top();
  64.         que.pop();
  65.         if (vis[tmp.pos]) {
  66.             continue;
  67.         }
  68.         vis[tmp.pos] = true;
  69.         for (int i = 0; i < m; ++i) {
  70.             Node node = edge[i].get(tmp.pos);
  71.             if (dis[node.pos] > dis[tmp.pos] + node.dis) {
  72.                 dis[node.pos] = dis[tmp.pos] + node.dis;
  73.                 que.push({node.pos, dis[node.pos]});
  74.             }
  75.         }
  76.     }
  77. }
  78.  
  79. int main() {
  80. #ifdef ExRoc
  81.     freopen("test.txt", "r", stdin);
  82. #endif
  83.     ios::sync_with_stdio(false);
  84.  
  85.     cin >> n >> m;
  86.     for (int i = 0; i < m; ++i) {
  87.         cin >> w >> s1 >> s2;
  88.         edge[i] = Edge(s1, s2, w);
  89.     }
  90.     dij((1 << n) - 1);
  91.     cout << (dis[0] == INF ? 0 : dis[0]) << endl;
  92.  
  93.     return 0;
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement