/* Problem: DIGJUMP
Algorithm used: String searching and BFS by implementing a graph datatype
Time Taken : O(n^2)
Author: brobear1995
*/
#include<iostream>
#include <list>
#include<algorithm>
using namespace std;
int len;
// This class represents a directed graph using adjacency list representation
class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing adjacency lists
// void DFSUtil( int v, bool visited[]);
public:
int *distTo; // shortest path
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
void BFS(int s); // prints BFS traversal from a given source s
// void DFS(int v);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
distTo= new int[V];
for(int i=0;i<V;i++)
{
distTo[i]=999999; // MAX_INT BETWEEN THE LIST
}
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v�¢ï¿½ï¿½s list.
adj[w].push_back(v); // undirected graph
//cout<<v<<" connected to "<<w<<"\n";
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
distTo[s]=0;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
queue.pop_front();
// Get all adjacent vertices of the dequeued vertex s
// If a adjacent has not been visited, then mark it visited
// and enqueue it
for(i = adj[s].begin(); i != adj[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
distTo[*i]=distTo[s]+1;
if(*i!=s)
{
queue.push_back(*i); //optimised bfs
}
}
}
}
}
void solvedigjump()
{
// Create a graph given in the above diagram
string s;
cin>>s;
int k=0;
int i=0;
int j=0;
len=s.length();
if(len==1)
{
cout<<0;
return;
}
len--;
// create an instance for the graph class
//size_t dist =0;
/* connect adjacent elements and connect elements having smae value here */
//size_t u = s.find_first_of(s[len]);
Graph g(len+1);
for(i=0;i<=(len-1);i++)
{
j=i;
g.addEdge(i,i+1); // connecting adjacent elements
while(j<=len)
{
// cout<<j<<"\n";
if(s[j]==s[i])
{
g.addEdge(i,j); // connecting element having same value // break;
}
j++;
}
}
/* Network generates in O(n^2) time */
g.BFS(0); // Implement Breadth First search in the network O(n) time
cout<<g.distTo[len]; // output the shortest distance
}
// Driver program to test methods of graph class
int main()
{
solvedigjump();
return 0;
}