3 3 2 3 3 3 3 3 3 3 2
25 RRDLLDRR
当n,m有奇数时,可以选择一条蛇形道路全部点都取到。算总和就行。
如果n,m为偶数时,选择(i+j)%==1的位置中最小的点不走,其他全部点选择即可。
还是蛇形道路,但是对于选择不走的那个位置所在行和相邻行,要特殊处理,优先上下方向走就行。
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> using namespace std; int num[111][111]; int n,m; void work(){ long long ans = 0; for(int i = 0;i < n; i++) for(int j = 0;j < m; j++) ans += num[i][j]; printf("%I64d\n",ans); if(n % 2 == 1){ for(int i = 0;i < n; i++){ for(int j = 1;j < m; j++){ if(i%2==0) putchar('R'); else putchar('L'); } if(i != n - 1) putchar('D'); } } else { for(int i = 0;i < m; i++){ for(int j = 1;j < n; j++){ if(i%2 == 0) putchar('D'); else putchar('U'); } if(i != m-1)putchar('R'); } } } int check[111][111]; int ok(int x,int y){ if(x < 0 || x == n || y < 0 || y == m) return 0; if(check[x][y] == 1) return 0; return 1; } void dfs(int x,int y,int c1,int c2){ check[x][y] = 1; if(x == c1){ if(ok(x+1,y)){ putchar('D'); dfs(x+1,y,c1,c2); } else if(ok(x,y+1)){ putchar('R'); dfs(x,y+1,c1,c2); } else if(ok(x,y-1)){ putchar('L'); dfs(x,y-1,c1,c2); } } else if(x == c2){ if(ok(x-1,y)){ putchar('U'); dfs(x-1,y,c1,c2); } else if(ok(x,y+1)){ putchar('R'); dfs(x,y+1,c1,c2); } else if(ok(x,y-1)){ putchar('L'); dfs(x,y-1,c1,c2); } else if(ok(x+1,y)){ putchar('D'); dfs(x+1,y,c1,c2); } } else { if(ok(x,y+1)){ putchar('R'); dfs(x,y+1,c1,c2); } else if(ok(x,y-1)){ putchar('L'); dfs(x,y-1,c1,c2); } else if(ok(x+1,y)){ putchar('D'); dfs(x+1,y,c1,c2); } } } void work2(){ long long ans = 0, res = 10000000000ll; int c1,c2,y; for(int i = 0 ;i < n; i++) for(int j = 0;j < m; j++){ ans += num[i][j]; if((i+j)% 2 == 1){ if(res > num[i][j]){ res = num[i][j]; c1 = i; y = j; } } } printf("%I64d\n",ans-res); if(c1 == 0) c2 = 1; else c2 = c1-1; memset(check,0,sizeof(check)); check[c1][y] = 1; dfs(0,0,min(c1,c2),max(c1,c2)); } int main(){ while(scanf("%d%d",&n,&m)!=EOF){ for(int i = 0;i < n; i++) for(int j = 0;j < m; j++) scanf("%d",&num[i][j]); if( n%2 == 1 || m % 2 == 1) work(); else work2(); printf("\n"); } return 0; } /* 3 3 2 3 3 3 3 3 3 3 2 3 2 2 3 3 3 3 3 2 3 2 3 3 3 3 3 4 4 1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 2 2 1 2 5 2 1 2 1 2 2 1 2 1 */