1646: [Usaco2007 Open]Catch That Cow 抓住那只牛
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 <= N <= 100,000) on a number line and the cow is at a point K (0 <= K <= 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting. * Walking: FJ can move from any point X to the points X-1 or X+1 in a single minute * Teleporting: FJ can move from any point X to the point 2*X in a single minute. If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
农夫约翰被通知,他的一只奶牛逃逸了!所以他决定,马上幽发,尽快把那只奶牛抓回来.
他们都站在数轴上.约翰在N(O≤N≤100000)处,奶牛在K(O≤K≤100000)处.约翰有
两种办法移动,步行和瞬移:步行每秒种可以让约翰从z处走到x+l或x-l处;而瞬移则可让他在1秒内从x处消失,在2x处出现.然而那只逃逸的奶牛,悲剧地没有发现自己的处境多么糟糕,正站在那儿一动不动.
那么,约翰需要多少时间抓住那只牛呢?
Input
* Line 1: Two space-separated integers: N and K
仅有两个整数N和K.
Output
* Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
最短的时间.
Sample Input
5 17
Farmer John starts at point 5 and the fugitive cow is at point 17.
Farmer John starts at point 5 and the fugitive cow is at point 17.
Sample Output
4
这道题和以前做的一道题很像,但是不明白那道题为什么是DP,但是似乎有人用SPFA做出来了,%用SPFA做的大神。。。
不过这道题是用SPFA,其实比较重要的就是判断2*i的边界,容易想到,如果2*i>(假设n<k;n1是n关于k对称的点)n1,那么在n1之后的点如果通过2*i
走到,那么耗费的时间一定大于直接从n走到k,所以只需要从0到n1相邻的点建立双向边,1到n1建立i*2的单向边,然后求SPFA即可。。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #define maxn 201000 7 #define maxm 400000 8 #define ll long long 9 #define inf 1000000000 10 using namespace std; 11 struct edge{int go,next,w;}e[2*maxm]; 12 int n,m,k,s,t,tot,q[maxn],d[maxn],head[maxn]; 13 bool v[maxn]; 14 void ins(int x,int y) 15 { 16 e[++tot].go=y;e[tot].w=1;e[tot].next=head[x];head[x]=tot; 17 } 18 void insert(int x,int y) 19 { 20 ins(x,y);ins(y,x); 21 } 22 void spfa() 23 { 24 for(int i=1;i<=m;++i) d[i]=inf; 25 memset(v,0,sizeof(v)); 26 int l=0,r=1,x,y;q[1]=n;d[n]=0; 27 while(l!=r) 28 { 29 x=q[++l];if(l==maxn)l=0;v[x]=0; 30 for(int i=head[x];i;i=e[i].next) 31 if(d[x]+e[i].w<d[y=e[i].go]) 32 { 33 d[y]=d[x]+e[i].w; 34 if(!v[y]){v[y]=1;q[++r]=y;if(r==maxn)r=0;} 35 } 36 } 37 } 38 int main(){ 39 scanf("%d%d",&n,&k); 40 if(k<=n){printf("%d",abs(k-n));return 0;} 41 m=k+abs(k-n)+1; 42 for(int i=0;i<m;i++)insert(i,i+1); 43 for(int i=1;i<=m/2;i++)ins(i,i*2); 44 spfa(); 45 printf("%d",d[k]); 46 return 0; 47 }