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; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步