1 #include<cstdio> 2 #include<cstdlib> 3 #include<cmath> 4 #include<cstring> 5 #include<algorithm> 6 #include<iostream> 7 #include<vector> 8 #include<map> 9 #include<set> 10 #include<queue> 11 #define inf 1000000000 12 #define maxn 50000+100 13 #define maxm 2000000 14 #define eps 1e-10 15 #define ll long long 16 #define pa pair<int,int> 17 using namespace std; 18 inline int read() 19 { 20 int x=0,f=1;char ch=getchar(); 21 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();} 22 while(ch>=‘0‘&&ch<=‘9‘){x=10*x+ch-‘0‘;ch=getchar();} 23 return x*f; 24 } 25 int n,m,tot; 26 int d[1005],head[1005]; 27 bool v[1005]; 28 struct edge{int go,next,w;}e[50005]; 29 void insert(int x,int y,int z) 30 { 31 e[++tot].go=y;e[tot].w=z;e[tot].next=head[x];head[x]=tot; 32 } 33 void dijkstra() 34 { 35 priority_queue<pa,vector<pa>,greater<pa> >q; 36 for(int i=1;i<=n;i++)d[i]=inf; 37 memset(v,0,sizeof(v)); 38 d[1]=0;q.push(make_pair(0,1)); 39 while(!q.empty()) 40 { 41 int x=q.top().second;q.pop(); 42 if(v[x])continue;v[x]=1; 43 for(int i=head[x],y;i;i=e[i].next) 44 if(d[x]+e[i].w<d[y=e[i].go]) 45 { 46 d[y]=d[x]+e[i].w; 47 q.push(make_pair(d[y],y)); 48 } 49 50 } 51 } 52 int main() 53 { 54 freopen("input.txt","r",stdin); 55 freopen("output.txt","w",stdout); 56 m=read();n=read(); 57 for(int i=1;i<=m;i++) 58 { 59 int x=read(),y=read(),z=1; 60 insert(x,y,z); 61 } 62 dijkstra(); 63 if(d[n]==inf)puts("-1"); 64 else printf("%d",d[n]+1); 65 return 0; 66 }
BZOJ1674: [Usaco2005]Part Acquisition,布布扣,bubuko.com
BZOJ1674: [Usaco2005]Part Acquisition
原文:http://www.cnblogs.com/zyfzyf/p/3927604.html