bzoj1674 [Usaco2005]Part Acquisition

来源:互联网 发布:钢琴编曲软件 编辑:程序博客网 时间:2024/05/26 17:48

Description

The cows have been sent on a mission through space to acquire a new milking machine for their barn. They are flying through a cluster of stars containing N (1 <= N <= 50,000) planets, each with a trading post. The cows have determined which of K (1 <= K <= 1,000) types of objects (numbered 1..K) each planet in the cluster desires, and which products they have to trade. No planet has developed currency, so they work under the barter system: all trades consist of each party trading exactly one object (presumably of different types). The cows start from Earth with a canister of high quality hay (item 1), and they desire a new milking machine (item K). Help them find the best way to make a series of trades at the planets in the cluster to get item K. If this task is impossible, output -1.

Input

* Line 1: Two space-separated integers, N and K. * Lines 2..N+1: Line i+1 contains two space-separated integers, a_i and b_i respectively, that are planet i's trading trading products. The planet will give item b_i in order to receive item a_i.

Output

* Line 1: One more than the minimum number of trades to get the milking machine which is item K (or -1 if the cows cannot obtain item K).

Sample Input

6 5 //6个星球,希望得到5,开始时你手中有1号货物.
1 3 //1号星球,希望得到1号货物,将给你3号货物
3 2
2 3
3 1
2 5
5 4

Sample Output

4


OUTPUT DETAILS:

The cows possess 4 objects in total: first they trade object 1 for
object 3, then object 3 for object 2, then object 2 for object 5.

题意是有n个星球,在每个星球上你可以用a[i]物品换b[i]物品,要求用最少步数换到m。

初看连题目都没看懂……觉得好像很难的样子……看懂之后发现,这不是水题吗

转成有n条有向边,边权为1,求1到m的最短路

#include<cstdio>#include<cstring>struct edge{int to,next,v;}e[100010];int head[1010];int dist[1010];int ans[1010];bool mrk[1010];int q[500010];int n,m,x,y,cnt,len,t,w=1;inline void ins(int u,int v,int w){e[++cnt].to=v;e[cnt].v=w;e[cnt].next=head[u];head[u]=cnt;}inline int read(){    int x=0,f=1;char ch=getchar();    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}    return x*f;}inline void spfa(){memset(dist,127/3,sizeof(dist));q[1]=1;mrk[1]=1;dist[1]=0;while (t<w){int now=q[++t];for (int i=head[now];i;i=e[i].next)  if (dist[e[i].to]>dist[now]+e[i].v)  {  dist[e[i].to]=dist[now]+e[i].v;  if (!mrk[e[i].to])  {  mrk[e[i].to]=1;  q[++w]=e[i].to;  }  }mrk[now]=0;}}int main(){m=read();n=read();for (int i=1;i<=m;i++)  {  x=read();y=read();  ins(x,y,1);  }spfa();if (dist[n]>10000)dist[n]=-2;printf("%d\n",dist[n]+1);}


0 0
原创粉丝点击