Guest User

Problem 2

a guest
Jan 26th, 2021
531
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #define ll long long
  5. #define f first
  6. #define s second
  7. #define NMAX 100000
  8. #define inf 2000000000000
  9.  
  10. using namespace std;
  11.  
  12. ll n, k, v1[100], v2[100], m[100][100], dist[NMAX+10], viz[NMAX+10];
  13. vector <pair <ll, ll> > a, nod[NMAX+10];
  14. priority_queue <pair <ll, ll>, vector <pair <ll, ll> >, greater <pair <ll, ll> > > pq;
  15.  
  16. int main()
  17. {
  18.     ios_base::sync_with_stdio(false);
  19.     cin.tie(0);
  20.     cout.tie(0);
  21.     cin >> n >> k;
  22.     for(ll i=1; i<=n; i++)
  23.         {   ll x;
  24.             cin >> x;
  25.             if(!v1[x]) v1[x] = i;
  26.             v2[x] = i;
  27.         }
  28.     for(ll i=1; i<=k; i++)
  29.         {   if(!v1[i]) continue;
  30.             a.push_back({v1[i], i});
  31.             if(v1[i] == v2[i]) continue;
  32.             a.push_back({v2[i], i});
  33.         }
  34.     for(ll i=1; i<=k; i++)
  35.         {   string s;
  36.             cin >> s;
  37.             for(ll j=0; j<k; j++)
  38.                 m[i][j+1] = s[j] - '0';
  39.         }
  40.  
  41.     for(ll i=0; i<a.size(); i++)
  42.         for(ll j=i+1; j<a.size(); j++)
  43.             {   if(m[a[i].s][a[j].s])
  44.                     {   if(a[i].f < a[j].f)
  45.                             nod[a[i].f].push_back({a[j].f, 0});
  46.                         else
  47.                             nod[a[i].f].push_back({a[j].f, a[i].f - a[j].f});
  48.                     }  
  49.                 if(m[a[j].s][a[i].s])
  50.                     {   if(a[j].f < a[i].f)
  51.                             nod[a[j].f].push_back({a[i].f, 0});
  52.                         else
  53.                             nod[a[j].f].push_back({a[i].f, a[j].f - a[i].f});
  54.                     }
  55.             }
  56.     pq.push({0, 1});
  57.     for(ll i=2; i<=n; i++)
  58.         dist[i] = inf;
  59.     while(!pq.empty())
  60.         {   pair <ll, ll> a = pq.top();
  61.             pq.pop();
  62.             if(a.s == n)
  63.                 {   cout << 2 * a.f + n - 1 << '\n';
  64.                     return 0;
  65.                 }
  66.             if(viz[a.s]) continue;
  67.             viz[a.s] = 1;
  68.             for(auto u : nod[a.s])
  69.                 {   if(viz[u.f]) continue;
  70.                     ll d = a.f + u.s;
  71.                     if(dist[u.f] > d)
  72.                         {   dist[u.f] = d;
  73.                             pq.push({d, u.f});
  74.                         }
  75.                 }
  76.         }
  77.     cout << -1 << '\n';
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment