HDU 5402
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5402
题意:
给一个n*m矩阵,矩阵每个格子有权值。问怎样不重复的走能使得权值和最大。
思路:
大模拟。
n与m中有一个奇数,就可以全部走完。
n与m都为偶数,需要舍弃一个权值最小且满足(i + j) % 2 != 0的点。
具体就自己模拟去吧,我也WA了无数发,改出来的感觉真好。
源码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
#define LL long long
const int MAXN = 100 + 5;
int a[MAXN][MAXN];
int n, m;
void Ytravel(int j)
{
if(j % 2 == 0)
for(int k = 2 ; k <= n ; k++)
printf("U");
else
for(int k = 2 ; k <= n ; k++)
printf("D");
}
void Xtravel(int i)
{
if(i % 2 == 0)
for(int k = 2 ; k <= m ; k++)
printf("L");
else
for(int k = 2 ; k <= m ; k++)
printf("R");
}
void XXtravel(int i, int x, int y)
{
// printf("XX\n");
int j, dj;
if(i % 2 == 0){
j = m, dj = -1;
}
else
j = 1, dj = 1;
int flag = !(i % 2);
while(j > 0 && j <= m){
if(j == y){
flag = !flag;
}
else if(flag == 0)
printf("D");
else if(flag == 1)
printf("U");
if(dj == -1 && j != 1)
printf("L");
else if(dj == 1 && j != m)
printf("R");
// printf("\nj = %d\n", j);
j += dj;
flag = !flag;
}
}
void YYtravel(int i, int x, int y)
{
// printf("YY\n");
// printf("x = %d, y = %d\n", x, y);
int j, dj;
if(i % 2 == 0){
j = n, dj = -1;
}
else
j = 1, dj = 1;
int flag = !(i % 2);
while(j > 0 && j <= n){
if(j == x){
flag = !flag;
}
else if(flag == 0)
printf("R");
else if(flag == 1)
printf("L");
if(dj == -1 && j != 1)
printf("U");
else if(dj == 1 && j != n)
printf("D");
j += dj;
flag = !flag;
}
}
int main()
{
while(scanf("%d%d", &n, &m) != EOF){
LL sum = 0;
int mmin = 10000 + 5;
int x, y;
for(int i = 1 ; i <= n ; i++)
for(int j = 1 ; j <= m ; j++){
scanf("%d", &a[i][j]);
sum += a[i][j];
if((i + j) % 2 != 0){
if(mmin > a[i][j]){
mmin = a[i][j];
x = i, y = j;
}
}
}
if(n % 2 != 0){
printf("%I64d\n", sum);
for(int i = 1 ; i <= n ; i++){
Xtravel(i);
if(i != n)
printf("D");
}
printf("\n");
}
else if(m % 2 != 0){
printf("%I64d\n", sum);
for(int i = 1 ; i <= m ; i++){
Ytravel(i);
if(i != m)
printf("R");
}
printf("\n");
}
else{
printf("%I64d\n", sum - mmin);
int i, j;
if(y != 1 && y != m){
int flag = 0;
for(i = 1 ; i <= n ; i++){
if((i-1)/2 != (x-1)/2){
Xtravel(i - flag);
}
else{
XXtravel(i++, x, y);
flag = 1;
}
if(i < n)
printf("D");
}
}
else{
int flag = 0;
for(i = 1 ; i <= m ; i++){
if((i-1)/2 != (y-1)/2){
Ytravel(i - flag);
}
else{
flag = 1;
YYtravel(i++, x, y);
}
if(i < m)
printf("R");
}
}
printf("\n");
}
}
return 0;
}
/*
4 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
4 4
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
2 2
1 2
3 4
2 2
1 3
2 4
2 4
3 3 3 1
3 3 3 3
*/