标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5402
类似于黑白棋盘,有的格子是可以不走的,有的格子是不能不走的,对于m或n中有一个奇数的情况,
所有的数都可以走到,当m和n都是偶数的时候,则需要分情况讨论,两行缩成一行走,
从而走遍可以走的数。m=1且n=1的时候需要特判
1 #include<stdio.h> 2 #include<cstring> 3 const int MAXN = 105; 4 int main(){ 5 int n, m; 6 int sum; 7 int maze[MAXN][MAXN]; 8 // freopen("e.txt","r",stdin); 9 while(~scanf("%d%d",&n,&m)){ 10 sum = 0; 11 memset(maze,0,sizeof(maze)); 12 for( int i = 0; i < n; ++i){ 13 for( int j = 0; j < m; ++j){ 14 scanf("%d",&maze[i][j]); 15 sum += maze[i][j]; 16 } 17 } 18 if( n == 1 && m == 1){ 19 printf("%d\n",sum); 20 printf("R\n"); 21 continue; 22 } 23 if( n % 2 == 1 ){ 24 printf("%d\n",sum); 25 for( int i = 0; i < n; ++i){ 26 for(int j = 1; j < m; ++j){ 27 if( m == 1 ){ 28 printf("D"); 29 continue; 30 } 31 if( i % 2 == 0) 32 printf("R"); 33 else 34 printf("L"); 35 } 36 if( i < n-1) 37 printf("D"); 38 } 39 printf("\n"); 40 continue; 41 } 42 else if( m % 2 == 1 ){ 43 printf("%d\n",sum); 44 for( int i = 0; i < m; ++i){ 45 for(int j = 1; j < n; ++j){ 46 if( i % 2 == 0) 47 printf("D"); 48 else 49 printf("U"); 50 } 51 if( i< m-1) 52 printf("R"); 53 } 54 printf("\n"); 55 continue; 56 } 57 else{ 58 int _min = 1000; 59 int pi, pj; 60 for(int i = 0; i < n; ++i){ 61 for( int j = 0; j < m; ++j){ 62 if( (i+j) % 2 == 1 && (maze[i][j] < _min)){ 63 _min = maze[i][j]; 64 pi = i; 65 pj = j; 66 } 67 } 68 } 69 // 找到最小值 70 printf("%d\n",sum-_min); 71 if( pi % 2 == 1 ){ 72 for( int i = 0; i < pi-1; ++i ){ 73 for( int j = 0; j < m-1; ++j){ 74 if( i % 2 == 0) 75 printf("R"); 76 else 77 printf("L"); 78 } 79 if( i < n-1) 80 printf("D"); 81 } 82 } 83 // 如果是奇数行出现,前pi-2行按规律走 84 else{ 85 for( int i = 0; i < pi; ++i ){ 86 for( int j = 0; j < m-1; ++j){ 87 if( i % 2 == 0) 88 printf("R"); 89 else 90 printf("L"); 91 } 92 if( i < n-1) 93 printf("D"); 94 } 95 } 96 // 如果是偶数行出现,前pi-1行按规律走 97 for( int i = 0; i < pj; ++i){ 98 if( i % 2 == 0) 99 printf("D"); 100 else 101 printf("U"); 102 printf("R"); 103 } 104 if( pj < m - 1 ) 105 printf("R"); 106 for( int i = pj+1; i < m; ++i){ 107 if( i % 2 == 1) 108 printf("D"); 109 else 110 printf("U"); 111 if( i < m-1) 112 printf("R"); 113 } 114 if( !( pi % 2 == 1 && pi + 1 == n) && !( pi % 2 == 0 && pi + 2 == n )) 115 printf("D"); 116 // 两行变一行 117 if( pi % 2 == 1 ){ 118 for( int i = pi+1; i < n; ++i ){ 119 for( int j = 0; j < m-1; ++j){ 120 if( i % 2 == 1) 121 printf("R"); 122 else 123 printf("L"); 124 } 125 if( i < n-1) 126 printf("D"); 127 } 128 } 129 else{ 130 for( int i = pi+2; i < n; ++i ){ 131 for( int j = 1; j < m; ++j){ 132 if( i % 2 == 1) 133 printf("R"); 134 else 135 printf("L"); 136 137 } 138 if( i < n-1) 139 printf("D"); 140 } 141 } 142 } 143 printf("\n"); 144 } 145 }
hdoj 5402 Travelling Salesman Problem
标签:
原文地址:http://www.cnblogs.com/blueprintf/p/4743126.html