Advertisement
Guest User

Untitled

a guest
Jul 7th, 2015
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.19 KB | None | 0 0
  1. #include <iostream>
  2. #include <string.h>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. struct node{
  8.     int d;
  9.     int r;
  10.  
  11.     bool operator>(const node& n)const{
  12.         return d>n.d;
  13.     }
  14. };
  15.  
  16. int n,h,m,a,b,t,c;
  17. bool is_hotel[10010];
  18. vector<pair<int,int> > rds[10010];
  19. vector<int> r_bfs[10010];
  20. priority_queue<node,vector<node>,greater<node> > q;
  21. queue<node> qu;
  22. node top;
  23. bool vis[10010];
  24.  
  25. int main()
  26. {
  27.     while(1){
  28.         cin>>n;
  29.         if(n==0)break;
  30.         cin>>h;
  31.         memset(is_hotel,0,sizeof(is_hotel)/sizeof(bool));
  32.         for(int i=0;i<h;i++){cin>>c; is_hotel[c-1]=true;}
  33.  
  34.         cin>>m;
  35.         while(m--){
  36.             cin>>a>>b>>t;
  37.             a--; b--;
  38.             rds[a].push_back(make_pair(t,b));
  39.             rds[b].push_back(make_pair(t,a));
  40.         }
  41.  
  42.         // DIJSKTRA
  43.         for(int i=0;i<n;i++){
  44.             if(!(is_hotel[i] || i==0))continue;
  45.             memset(vis,0,sizeof(vis)/sizeof(bool));
  46.             q=priority_queue<node,vector<node>,greater<node> >();
  47.             q.push({0,i});
  48.  
  49.             while(!q.empty()){
  50.                 top=q.top();
  51.                 q.pop();
  52.  
  53.                 if(vis[top.r] || top.d>600)continue;
  54.                 vis[top.r]=true;
  55.  
  56.                 if((top.r!=i) && (top.r==n-1 || is_hotel[top.r]))r_bfs[i].push_back(top.r);
  57.  
  58.                 for(int j=0;j<rds[top.r].size();j++){
  59.                     q.push({top.d+rds[top.r][j].first,rds[top.r][j].second});
  60.                 }
  61.             }
  62.         }
  63.  
  64.         for(int i=0;i<n;i++)
  65.             rds[i].clear();
  66.  
  67.         // BFS
  68.         memset(vis,0,sizeof(vis)/sizeof(bool));
  69.         qu = queue<node>();
  70.         qu.push({0,0});
  71.         bool f=false;
  72.  
  73.         while(!qu.empty()){
  74.             top=qu.front();
  75.             qu.pop();
  76.  
  77.             if(vis[top.r])continue;
  78.             vis[top.r]=true;
  79.  
  80.             if(top.r==n-1){f=1; break;}
  81.  
  82.             for(int j=0;j<r_bfs[top.r].size();j++){
  83.                 qu.push({top.d+((r_bfs[top.r][j]==n-1)?0:1),r_bfs[top.r][j]});
  84.             }
  85.         }
  86.  
  87.         for(int i=0;i<n;i++)
  88.             r_bfs[i].clear();
  89.  
  90.         if(f)
  91.             cout<<top.d<<endl;
  92.         else
  93.             cout<<"-1"<<endl;
  94.     }
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement