糯米

TI DaVinci, gstreamer, ffmpeg
随笔 - 167, 文章 - 0, 评论 - 47, 引用 - 0
数据加载中……

POJ 2111 Millenium Leapcow 动态规划

思路:

先按棋盘上的值从大到小排序。
然后先解决值大的,再解决值小的。
注意路径的比较。应该很容易WA的。

#include <stdio.h>
#include 
<algorithm>

using namespace std;

#define MAX_N 512

struct seq_node {
    
short y, x;
}
;
struct map_node {
    
int val, cnt;
    
struct map_node *pre;
}
;
struct map_node map[MAX_N][MAX_N], *ans;
struct seq_node seq[MAX_N*MAX_N];
int N;

int cmp_seq(const void *a, const void *b)
{
    
return    map[((struct seq_node *)a)->y][((struct seq_node *)a)->x].val - 
            map[((
struct seq_node *)b)->y][((struct seq_node *)b)->x].val;
}


inline 
int cmp_path(struct map_node *a, struct map_node *b)
{
    
while (a && b) {
        
if (a->val != b->val)
            
return a->val - b->val;
        a 
= a->pre;
        b 
= b->pre;
    }

    
return 0;
}


inline 
void update(struct map_node *a, int y2, int x2)
{
    
struct map_node *= &map[y2][x2];

    
if (y2 < 0 || y2 >= N || x2 < 0 || x2 >= N)
        
return ;    
    
if (b->val > a->val && 
        (b
->cnt > a->cnt || b->cnt == a->cnt && cmp_path(b, a->pre) < 0)
        ) 
    
{
        a
->cnt = b->cnt;
        a
->pre = b;
    }

}


int main()
{
    
int x, y, i;
    
struct seq_node *t;
    
struct map_node *m;

    freopen(
"e:\\test\\in.txt""r", stdin);

    scanf(
"%d"&N);
    i 
= 0;
    
for (y = 0; y < N; y++{
        
for (x = 0; x < N; x++{
            scanf(
"%d"&map[y][x].val);
            seq[i].y 
= y;
            seq[i].x 
= x;
            i
++;
        }

    }

    qsort(seq, N
*N, sizeof(seq[0]), cmp_seq);

    
for (t = &seq[N*- 1]; t >= seq; t--{
        m 
= &map[t->y][t->x];
        update(m, t
->- 2, t->+ 1);
        update(m, t
->+ 2, t->+ 1);
        update(m, t
->- 2, t->- 1);
        update(m, t
->+ 2, t->- 1);
        update(m, t
->- 1, t->+ 2);
        update(m, t
->+ 1, t->+ 2);
        update(m, t
->- 1, t->- 2);
        update(m, t
->+ 1, t->- 2);
        m
->cnt++;
        
if ((!ans || m->cnt > ans->cnt) ||
            (m
->cnt == ans->cnt && cmp_path(m, ans) < 0)
            ) 
            ans 
= m;
    }


    printf(
"%d\n", ans->cnt);
    
while (ans) {
        printf(
"%d\n", ans->val);
        ans 
= ans->pre;
    }


    
return 0;
}

posted on 2010-04-27 14:14 糯米 阅读(381) 评论(0)  编辑 收藏 引用 所属分类: POJ


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理