Advertisement
pb_jiang

CF1846G AC

Jul 10th, 2023
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <assert.h>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. #ifndef __DEBUG__
  5. #define dbg(...) 42
  6. #endif
  7. template <class T> using mpq = priority_queue<T, vector<T>, greater<T>>;
  8.  
  9. using ll = long long;
  10. using pii = pair<int, int>;
  11. using pll = pair<ll, ll>;
  12. using vl = vector<ll>;
  13. using vi = vector<int>;
  14. using b10s = bitset<10>;
  15.  
  16. b10s getset(const string &s)
  17. {
  18.     assert(s.size() <= 10);
  19.     int res = 0;
  20.     for (int i = 0; i < s.size(); ++i)
  21.         res = (res << 1) | s[i] == '1';
  22.     return b10s(res);
  23. }
  24.  
  25. int dijkstra(const vector<string> &in, const vector<string> &out, const vi &ds, int start, int dest)
  26. {
  27.     int n = in[0].size(), m = in.size();
  28.     vi dist(1 << (n + 1), INT_MAX / 2);
  29.     dist[start] = 0;
  30.     dbg(start, dest);
  31.     vector<int> ind(m), outd(m);
  32.     auto f = [](const string &s) { return (int) getset(s).to_ullong(); };
  33.     transform(in.begin(), in.end(), ind.begin(), f);
  34.     transform(out.begin(), out.end(), outd.begin(), f);
  35.     set<int> vis;
  36.     mpq<pii> pq;
  37.     pq.push({0, start});
  38.     while (pq.empty() == false) {
  39.         auto [d, u] = pq.top();
  40.         pq.pop();
  41.         if (vis.count(u))
  42.             continue;
  43.         vis.insert(u);
  44.         dist[u] = min(dist[u], d);
  45.  
  46.         for (int i = 0; i < m; ++i) {
  47.             int v = (u & ~ind[i]) | outd[i];
  48.             if (dist[v] > d + ds[i]) {
  49.                 dist[v] = d + ds[i];
  50.                 pq.push({dist[v], v});
  51.             }
  52.         }
  53.     }
  54.  
  55.     return INT_MAX / 2 == dist[dest] ? -1 : dist[dest];
  56. }
  57.  
  58. int main(int argc, char **argv)
  59. {
  60.     int t, n, m;
  61.     cin >> t;
  62.     while (t--) {
  63.         cin >> n >> m;
  64.         string start;
  65.         cin >> start;
  66.         vi ds(m);
  67.         vector<string> in(m), out(m);
  68.         for (int i = 0; i < m; ++i)
  69.             cin >> ds[i] >> in[i] >> out[i];
  70.  
  71.         int ans = dijkstra(in, out, ds, (int) getset(start).to_ullong(), 0);
  72.         cout << ans << endl;
  73.     }
  74.     return 0;
  75. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement