原题 http://www.matrix67.com/blog/archives/550 一个广搜就过了。 合法解:设mm从A出发,gg从B出发 mm->I gg->A mm->H gg->I mm->G gg->H mm->F->L gg->I mm->E->D gg->H->J mm->C gg->K mm->B gg->B
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
const int MAXINT = 1 << 30;
int n;
char vc[12]; //点的颜色
int e[12]; int p[12][3]; char c[12][3]; //邻接表
const int QSIZE = 100000;
int q[QSIZE][5], qf, qr, qn;
int steps[12][12]; //最优化
inline void enqueue(int a, int b, int s, int prva, int prvb)
{
q[qr][0] = a; q[qr][1] = b; q[qr][2] = s;
q[qr][3] = prva; q[qr][4] = prvb;
qr++; qr %= QSIZE;
qn++;
}
void dequeue(int &a, int &b, int &s, int &prva, int &prvb)
{
a = q[qf][0]; b = q[qf][1]; s = q[qf][2];
prva = q[qf][3]; prvb = q[qf][4];
qf++; qf %= QSIZE;
qn--;
}
int main()
{
ifstream fin("valentine.txt");
fin >> n;
for (int i=0; i<n; i++) fin >> vc[i]; //点的颜色,C(yan) R(ed) Y(ellow)
int ecount;
fin >> ecount;
for (int i=0; i<n; i++) e[i] = 0;
for (int i=0; i<ecount; i++) //边集输入,格式为"字母1 字母2 颜色"
{
char u, v, tc;
fin >> u >> v >> tc;
u -= 'A';
v -= 'A';
p[u][e[u]] = v;
p[v][e[v]] = u;
c[u][e[u]] = c[v][e[v]] = tc;
e[u]++; e[v]++;
}
fin.close();
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
steps[i][j] = MAXINT;
qf = qr = qn = 0;
enqueue(0, 1, 0, -1, -1); //start from Va and Vb
int a, b, s, prva, prvb;
while (qn > 0)
{
dequeue(a, b, s, prva, prvb);
if (steps[a][b] > s) //较优移动
{
cout<<char(a+'A')<<" "<<char(b+'A')<<" "<<s
<<"/t("<<char(prva+'A')<<" "<<char(prvb+'A')<<")"<<endl;
steps[a][b] = s;
if (a == b) //合法解
{
cout<<"FIND SOL AT V"<<a<<" STEP="<<s<<endl;
continue;
}
}
else //较劣移动
continue;
//move a
for (int i=0; i<e[a]; i++)
if (c[a][i] == vc[b])
enqueue(p[a][i], b, s+1, a, b);
//move b
for (int i=0; i<e[b]; i++)
if (c[b][i] == vc[a])
enqueue(a, p[b][i], s+1, a, b);
}
system("pause");
return 0;
}
/*
valentine.txt
12
RYCRYCRYCYRR
15
A B C
B C R
C D Y
D E C
E F R
F G Y
G H C
H I R
I A Y
H J R
B K Y
E L C
F L Y
J K C
K L R
*/