这道题看别人用模拟做代码短,时间也快,我用hash做,纯粹只是为了练习,hash的确是不熟,还得多练练。
//47ms
#include <iostream>
using namespace std;
#define SIZE 102
#define TAB_SIZ 14997
int size;
struct ListNode
{
char s[2*SIZE];
struct ListNode *next;
};
struct ListNode *table[TAB_SIZ];
int Hash(char *key)
{
unsigned int hashVal = 0, i;
for(i = 0; i < 2*size; i++)
hashVal = (hashVal << 5) + key[i];
return hashVal % TAB_SIZ;
}
bool isFind(int key, char *b)
{
struct ListNode *l, *p;
bool flag = false;
int i;
l = table[key];
p = l->next;
while(p != NULL && !flag)
{
for(i = 0; i < 2*size; i++)
if(b[i] != p->s[i])
break;
if(i == 2*size)
flag = true;
else
p = p->next;
}
// cout << "flag " << flag << endl;
return flag;
}
void Insert(int key, char *b)
{
struct ListNode *newCell, *l;
int i;
newCell = (ListNode *)malloc(sizeof(ListNode));
l = table[key];
newCell->next = l->next;
l->next = newCell;
for(i = 0; i < 2*size; i++)
newCell->s[i] = b[i];
}
void shuffle(char *s1, char *s2, char *tmp)
{
int i;
for(i = 0; i < size; i++)
{
tmp[2*i] = s2[i];
tmp[2*i+1] = s1[i];
}
tmp[2*size] = '\0';
}
void split(char *s1, char *s2, char *tmp)
{
int i;
for(i = 0; i < 2*size; i++)
if(i < size)
s1[i] = tmp[i];
else
s2[i-size] = tmp[i];
s1[size] = '\0';
s2[size] = '\0';
}
int main()
{
int cas, i, j = 1, dist;
char s1[SIZE], s2[SIZE];
char tmp[2*SIZE], target[2*SIZE];
// freopen("a.txt", "r", stdin);
for(i = 0; i < TAB_SIZ; i++)
{
table[i] = (struct ListNode *)malloc(sizeof(struct ListNode));
table[i]->next = NULL;
}
cin >> cas;
while(j <= cas)
{
for(i = 0; i < TAB_SIZ; i++)
table[i]->next = NULL;
dist = 0;
cin >> size;
cin >> s1 >> s2 >> target;
// cout << target << endl;
// cout << s1 << " " << s2 << endl;
cout << j << " ";
while(true)
{
shuffle(s1, s2, tmp);
// cout << "tmp " << tmp << endl;
for(i = 0; i < 2*size; i++)
if(target[i] != tmp[i])
break;
if(i == 2*size)
{
cout << dist+1 << endl;
break;
}
else
{
int key = Hash(tmp);
if(isFind(key, tmp))
{
cout << -1 << endl;
break;
}
else
{
Insert(key, tmp);
dist++;
}
}
split(s1, s2, tmp);
// cout << s1 << " " << s2 << endl;
}
j++;
}
return 0;
}