Problem
Chef loves games! But he likes to invent his own. Now he plays game "Digit Jump". Chef has a sequence of digits . He is staying in the first digit and wants to reach the last digit in the minimal number of jumps.
While staying in some index Chef can jump into and , but he can't jump out from sequence. Or he can jump into any digit with the same value .
Help Chef to find the minimal number of jumps he need to reach digit from digit .
Input
Input contains a single line consist of string of length - the sequence of digits.
Output
In a single line print single integer - the minimal number of jumps he needs.
Constraints
- Each symbol of is a digit from to .
Sample 1:
01234567890
1
Explanation:
Test Case 1: Chef can directly jump from the first digit (it is ) to the last (as it is also ).
Sample 2:
012134444444443
4
Explanation:
Test Case 2: Chef should follow the following path: .
Program :
#include <stdio.h>
#define MAX_N 100000
int N;
int in[MAX_N + 2];
int vis[MAX_N + 2];
int pos[10][MAX_N];
int ans[10];
int q[2*MAX_N + 1];
const int sent = -1;
int main(void)
{
//freopen("input.txt", "r", stdin);
char c;
int d;
for (int i = 0; i < 10; ++i)
{
ans[i] = 0;
}
N = 0;
vis[0] = 1;
for (N = 1, c = getchar(); c >= '0' && c <= '9'; ++N, c = getchar())
{
d = c - 48;
in[N] = d;
vis[N] = 0;
pos[d][ans[d]++] = N;
}
vis[N--] = 1;
int head = 0, tail = 0;
q[tail++] = 1;
q[tail++] = sent;
int path = 0;
int sib;
while (tail< 2*MAX_N)
{
d = q[head++];
vis[d] = 1;
if (d == sent)
{
++path;
q[tail++] = sent;
continue;
}
if (d == N)
{
printf("%d", path);
break;
}
if (vis[d - 1] == 0) {
q[tail++] = d - 1;
vis[d - 1] = 1;
}
if (vis[d + 1] == 0) {
q[tail++] = d + 1;
vis[d + 1] = 1;
}
sib = in[d];
for (int i = ans[sib] - 1; i >= 0; --i)
{
if (vis[pos[sib][i]] == 0)
{
q[tail++] = pos[sib][i];
vis[pos[sib][i]] = 1;
}
}
ans[sib] = 0;
}
return 0;
}
0 Comments