懂得怎么建图就好做了,有些路权值为1,有些为0
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=10000; 4 const int maxm=50000; 5 const int INF=1e9; 6 7 inline int read() 8 { 9 int x=0,k=1;char c=getchar(); 10 while(c<‘0‘||c>‘9‘) {if(c==‘-‘) k=-1;c=getchar();} 11 while(c>=‘0‘&&c<=‘9‘) x=(x<<3)+(x<<1)+(c^48),c=getchar(); 12 return x*k; 13 } 14 15 int cnt,dis[maxn],vis[maxn],head[maxm],n,m,s,t; 16 17 struct Edge{ 18 int u,v,w,next; 19 }e[maxm]; 20 21 inline void add(int u,int v,int w) 22 { 23 e[++cnt].u=u; 24 e[cnt].v=v; 25 e[cnt].w=w; 26 e[cnt].next=head[u]; 27 head[u]=cnt; 28 } 29 30 struct node{ 31 int w,now; 32 inline bool operator <(const node& x) const 33 { 34 return w>x.w; 35 } 36 }; 37 38 priority_queue<node> q; 39 40 void dijikstra() 41 { 42 for(int i=1;i<=n;++i) dis[i]=INF; 43 dis[s]=0; 44 q.push((node){0,s}); 45 while(!q.empty()) 46 { 47 node x=q.top(); 48 q.pop(); 49 int u=x.now; 50 if(vis[u]) continue; 51 vis[u]=1; 52 for(int i=head[u];i;i=e[i].next) 53 { 54 int v=e[i].v; 55 if(dis[v]>dis[u]+e[i].w) 56 { 57 dis[v]=dis[u]+e[i].w; 58 q.push((node){dis[v],v}); 59 } 60 } 61 } 62 } 63 64 int main() 65 { 66 n=read(),s=read(),t=read(); 67 for(int i=1,x,y,z;i<=n;++i) 68 { 69 x=read(); 70 for(int j=1;j<=x;++j) 71 { 72 y=read(); 73 if(j==1) add(i,y,0); 74 else add(i,y,1); 75 } 76 } 77 dijikstra(); 78 if(dis[t]>=INF) printf("-1"); 79 else printf("%d",dis[t]); 80 return 0; 81 }
原文地址:https://www.cnblogs.com/zytwan/p/9931818.html
时间: 2024-10-14 23:14:58