WORM
Time Limit: 20000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 278 Accepted Submission(s): 169
Problem Description
Partychen discover a strange worm in ECNU.The worm is too laze so it spends most of his life in sleep,the only way to wake it up is turn the worm's body into the same color. This worm’s body consist of N body sections, each body section could only be three kinds of colors: red (r), green (g), blue (b) . This worm's body color could change with the following two rules:
1:two adjacent section with different colors can change into another at the same time, such as rg could be bb,bg could be rr etc.
2: only one change could happen in the worm’s body per second.
Illustration below shows a series change in two seconds:
Now Partychen want you to tell him how long it required to wake up the strange worm at least.
1:two adjacent section with different colors can change into another at the same time, such as rg could be bb,bg could be rr etc.
2: only one change could happen in the worm’s body per second.
Illustration below shows a series change in two seconds:

Now Partychen want you to tell him how long it required to wake up the strange worm at least.
Input
The first line of input contains one integer N( N<=200),specifying the number of test cases to follow.The following N lines each line contain a series characters denotes the color status of the worm’s body.’r’,’g’,’b’ represents “red”,”‘green”,”blue” respectively.there are no extra spaces or blanks in the characters and the total length of each line is at most 10.
Output
Output one line each case.if there is no way to wake up the strange worm output “No solution!”,otherwise output the smallest total time to do so.
Sample Input
8 rbgrg rbbgbbr bgr bgrbrgbr bggrgbgrr gbrggrbggr rrrrr bgbr
Sample Output
5 7 1 6 No solution! 8 0 4
Source
Recommend
看到有人用十维数组来标记,其实一个map就可以了
#include<iostream>
#include<map>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
string ch;
int l;
struct Node
{
string s;
int step;
friend bool operator <(Node a, Node b)
{
return a.step>b.step;
}
};
void BFS()
{
priority_queue<Node> Q;
map<string,int> my;
Node p,q;
int i,k,flag;
p.s=ch;
p.step=0;
Q.push(p);
while(!Q.empty())
{
p=Q.top();
Q.pop();
if(my[p.s])
{
continue;
}
my[p.s]=1;
flag=0;
for(i=1;i<l;i++)
{
if(p.s[i]!=p.s[i-1])
{
flag=1;
break;
}
}
if(!flag)
{
printf("%d\n",p.step);
return ;
}
for(k=1;k<l;k++)
{
q.s=p.s;
q.step=p.step;
if(q.s[k]!=q.s[k-1])
{
if(q.s[k]=='r'&&q.s[k-1]=='b'||(q.s[k-1]=='r'&&q.s[k]=='b'))
{
q.s[k]='g';
q.s[k-1]='g';
}
else if(q.s[k]=='r'&&q.s[k-1]=='g'||(q.s[k-1]=='r'&&q.s[k]=='g'))
{
q.s[k]='b';
q.s[k-1]='b';
}
else
{
q.s[k]='r';
q.s[k-1]='r';
}
q.step++;
Q.push(q);
}
}
}
printf("No solution!\n");
}
int main()
{
int i,j;
int T;
scanf("%d",&T);
while(T--)
{
cin>>ch;
l=ch.length();
BFS();
}
return 0;
}