Catch That Cow
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?
Input
Line 1: Two space-separated integers: N and 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
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int arr[100001];
int main()
{
int n, k, m;
scanf("%d%d", &n, &k);
if(n > k)
{
printf("%d\n", n-k);
return 0;
}
memset(arr, -1, sizeof(arr));
queue<int> q;
q.push(n);
arr[n] = 0;
m = n;
while(!q.empty())
{
m = q.front();
q.pop();
if(m == k)
{
break;
}
else
{
if(2*m <= 100000 && arr[2*m] == -1) //走两倍
{
q.push(2*m);
arr[2*m] = arr[m]+1;
}
if(m+1 <= 100000 && arr[m+1] == -1) //向前走一步
{
q.push(m+1);
arr[m+1] = arr[m]+1;
}
if(m-1 > 0 && arr[m-1] == -1) //向后走一步
{
q.push(m-1);
arr[m-1] = arr[m]+1;
}
}
}
printf("%d\n", arr[k]);
return 0;
}
Find The Multiple
Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.
Input
The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.
Output
For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.
Sample Input
2 6 19 0
Sample Output
10 100100100100100100 111111111111111111
#include <stdio.h>
#include <queue>
using namespace std;
int panda(int c)
{
int n = 0;
while(c)
{
n++;
c /= 10;
}
return n;
}
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
if(n == 0) break;
queue<unsigned long long> q;
q.push(1);
int c = 1;
unsigned long long m;
while(panda(c) < 19)
{
m = q.front();
q.pop();
if(m%n == 0) break;
m *= 10; //末位添0
q.push(m);
m += 1; //末位添1
q.push(m);
c++;
}
printf("%lld\n", m);
}
return 0;
}