POJ 1847 Tram dij
分析:d[i]表示到i点,最少的操作数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<cstring> #include<queue> #include<cstdlib> #include<algorithm> #include<vector> #include<cmath> using namespace std; typedef long long LL; const int N=100+5; const int INF=0x3f3f3f3f; struct Edge{ int v,w,next; bool operator<(const Edge &e)const{ return w>e.w; } }edge[N*N]; int head[N],tot,n,s,t,d[N]; void add(int u,int v,int w){ edge[tot].v=v; edge[tot].w=w; edge[tot].next=head[u]; head[u]=tot++; } priority_queue<Edge>q; bool vis[N]; int dij(int s,int t){ for(int i=1;i<=n;++i)d[i]=INF,vis[i]=0; d[s]=0,q.push(Edge{s,0,0}); while(!q.empty()){ while(!q.empty()&&vis[q.top().v])q.pop(); if(q.empty())break; int u=q.top().v; q.pop(); vis[u]=1; for(int i=head[u];~i;i=edge[i].next){ int v=edge[i].v; if(!vis[v]&&d[v]>d[u]+edge[i].w){ d[v]=d[u]+edge[i].w; q.push(Edge{v,d[v],0}); } } } return d[t]==INF?-1:d[t]; } int main(){ scanf("%d%d%d",&n,&s,&t); memset(head,-1,sizeof(head)); for(int i=1;i<=n;++i){ int k,v; scanf("%d",&k); for(int j=1;j<=k;++j){ scanf("%d",&v); add(i,v,j==1?0:1); } } printf("%d\n",dij(s,t)); return 0; }