Advertisement
Josif_tepe

Untitled

Jan 19th, 2025
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6. vector<pair<int,int>>v[100000];
  7.  
  8. struct node{
  9.   int idx;
  10.   int dist;
  11.   node(){}
  12.   node(int _idx,int _dist){
  13.     idx=_idx;
  14.     dist=_dist;
  15.   }
  16.   bool operator < (const node & tmp)const{
  17.     return dist > tmp.dist;
  18.   }
  19. };
  20. void dijkstra(int s,int n){
  21. vector<bool>visited(n,false);
  22. vector<int>dist(n,2e9);
  23.  
  24. dist[s]=0;
  25. priority_queue<node>pq;
  26. pq.push(node(s,0));
  27.  
  28.   while(!pq.empty()){
  29.     node c = pq.top();
  30.     pq.pop();
  31.     if(visited[c.idx]==true){
  32.         continue;
  33.     }
  34.     else{
  35.         visited[c.idx]=true;
  36.     }
  37.  
  38.     for(int i = 0;i<v[c.idx].size();i++){
  39.         int sosed = v[c.idx][i].first;
  40.         int dist2 = v[c.idx][i].second;
  41.  
  42.         if(visited[sosed]==false && c.dist + dist2 < dist[sosed]){
  43.           dist[sosed] = c.dist + dist2;
  44.           pq.push(node(sosed,dist[sosed]));
  45.         }
  46.     }
  47.   }
  48.  cout<<dist[n-1]<<endl;
  49. }
  50.  
  51. int main()
  52. {
  53.     int n,V;
  54.     cin>>n>>V;
  55.     vector<int>x(n);
  56.     for(int i = 0;i<n;i++){
  57.         cin>>x[i];
  58.     }
  59.     for(int i = 0;i<n;i++){
  60.         if(i>0){
  61.           v[i].push_back(make_pair(i-1,1));
  62.             v[i - 1].push_back(make_pair(i,1));
  63.  
  64.         }
  65.         if(i + 1 < n){
  66.           v[i].push_back(make_pair(i+1,1));
  67.             v[i + 1].push_back(make_pair(i,1));
  68.  
  69.         }
  70.         for(int j = 0;j<n;j++){
  71.             if(x[i]==x[j]){
  72.                 v[i].push_back(make_pair(j,V));
  73.                 v[j].push_back(make_pair(i,V));
  74.  
  75.             }
  76.         }
  77.     }
  78.     dijkstra(0, n);
  79.     return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement