-
Notifications
You must be signed in to change notification settings - Fork 2
/
10067.cpp
121 lines (106 loc) · 2.02 KB
/
10067.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAXN 10000
int Tval;
int Q[MAXN],QH,QT;
int MAX;
struct ss {
int level;
char visit;
}V[MAXN];
int Val(int a, int b, int c, int d) {
return a*1000+b*100+c*10+d;
}
int Push(int n, int l) {
if(V[n].visit == 'r') return 0;
if(n == Tval) return 1;
V[n].visit = 'r';
V[n].level = l;
Q[QH++] = n;
QH %= MAXN;
return 0;
}
int Pop() {
int n;
n = Q[QT++];
QT %= MAXN;
return n;
}
int IsEmpty() {
return QH == QT;
}
int PushAll(int a, int b, int c, int d, int lev) {
int val, i, j;
int x[] = {1,-1};
char temp[100],dummy[100];
val = Val(a,b,c,d);
sprintf(temp,"%04d",val);
strcpy(dummy,temp);
for(i = 0; i<4; i++) {
for(j = 0; j<2; j++) {
temp[i] = ((dummy[i] - '0' + x[j] + 10)%10)+'0';
if(Push(atoi(temp),lev)) return 1;
}
strcpy(temp,dummy);
}
return 0;
}
void Ini() {
int i;
for(i = 0; i<MAXN; i++){
V[i].level = 0;
V[i].visit = 'w';
}
}
void DoBfs(int a, int b, int c, int d) {
int p, q, r, s, val, lev, n;
char dummy[100];
MAX = 21474873;
if(V[Tval].visit == 'r') {
printf("-1\n");
return;
}
QH = QT = 0;
val = Val(a,b,c,d);
V[val].level = 0;
Push(val,0);
while(!IsEmpty()) {
n = Pop();
sprintf(dummy,"%04d",n);
p = dummy[0]-'0'; q = dummy[1]-'0';
r = dummy[2]-'0'; s = dummy[3]-'0';
lev = V[n].level+1;
if(PushAll(p,q,r,s,lev)) {
printf("%d\n",lev);
return;
}
}
printf("-1\n");
}
int main() {
int kase, i, r, f, t;
int sa, sb, sc, sd;
int a, b, c, d, v;
scanf("%d",&kase);
while(kase--) {
Ini();
f = 0;
scanf("%d%d%d%d",&sa,&sb,&sc,&sd);
scanf("%d%d%d%d",&a,&b,&c,&d);
Tval = Val(a,b,c,d);
t = Val(sa,sb,sc,sd);
scanf("%d",&r);
for(i = 0; i<r; i++) {
scanf("%d%d%d%d",&a,&b,&c,&d);
v = Val(a,b,c,d);
V[v].visit = 'r';
}
if(Tval == t && V[t].visit != 'r') {
printf("0\n");
continue;
}
DoBfs(sa,sb,sc,sd);
}
return 0;
}