ZOJ1221 Risk 图形的遍历
一开始做图形遍历的题都是用链表做的,这次用数组体会到了方便但就是有点浪费。
不过题目给的内存限制已经足够了。
View Code
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<queue> 5 #include<iostream> 6 7 using namespace std; 8 9 typedef struct 10 { 11 int v; 12 int step; 13 }Point; 14 Point P[21]; 15 int visit[21], map[21][21],n; 16 int ncases, A[21], B[21]; 17 18 queue<Point>q; 19 int main() 20 { 21 int i, j, from, to,k=1; 22 while(scanf("%d",&n) != EOF) 23 { 24 memset(map,0,sizeof(map)); 25 26 while( n-- ) 27 { 28 scanf("%d",&to); 29 map[1][to] = 1; 30 map[to][1] = 1; 31 } 32 for(i=2; i<=19; i++) 33 { 34 scanf("%d",&n); 35 while( n-- ) 36 { 37 scanf("%d",&to); 38 map[i][to] = 1; 39 map[to][i] = 1; 40 } 41 } 42 scanf("%d",&ncases); 43 printf("Test Set #%d\n",k++); 44 while( ncases-- ) 45 { 46 scanf("%d%d",&from,&to); 47 memset(visit,0,sizeof(visit)); 48 for(i=1; i<=20; i++) 49 { 50 P[i].v = i; 51 P[i].step = 0; 52 } 53 q.push(P[from]); 54 visit[from] = 1; 55 while(!q.empty()) 56 { 57 Point u = q.front(); 58 q.pop(); 59 if(u.v == to) 60 { 61 printf("%d to %d: %d\n",from,to,u.step); 62 break; 63 } 64 for(i=1; i<=20; i++) 65 { 66 if(!visit[i]&&map[u.v][i]) 67 { 68 P[i].step = u.step+1; 69 q.push(P[i]); 70 visit[i] = 1; 71 } 72 } 73 } 74 while(!q.empty()) 75 q.pop(); 76 } 77 printf("\n"); //这里没加卡了一下 78 } 79 return 0; 80 }