zju1107
来源:互联网 发布:php cms使用 编辑:程序博客网 时间:2024/05/24 04:10
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
typedef struct node
{
int x,y;
int num;
}node;
#define max_size 10020
node chess[max_size];
int opt[max_size];/*记录最优值*/
int n,k;
int cmp(const void *a,const void *b)/*按num排序*/
{
node *temp1=(node *)a;
node *temp2=(node *)b;
if(temp1->num != temp2->num)
{
return temp1->num - temp2->num;
}
else
{
if (temp1->x != temp2-> x)
return temp1->x - temp2->x;
else return temp1->y - temp2->y;
}
}
int dp_fuction()
{
int i,j;
int index;
int max_chess=-1;
for(i=0;i<n*n;i++)
if(chess[i].x==0 && chess[i].y==0)
{
index=i;
break;
}
opt[index]=chess[index].num;
for(i=index+1;i<n*n;i++)
opt[i]=-1;/*初始化没有解*/
for(i=index+1;i<n*n;i++)
{
for(j=index;j<i;j++)
{
if(opt[j]!=-1 && chess[j].num<chess[i].num && ( (chess[j].x==chess[i].x && abs(chess[j].y-chess[i].y)<=k) ||
(chess[j].y==chess[i].y && abs(chess[j].x-chess[i].x)<=k) ))
if(opt[i]<opt[j]+chess[i].num)
opt[i]=opt[j]+chess[i].num;
}
}
for(i=index;i<n*n;i++)
if(max_chess<opt[i])
max_chess=opt[i];
return max_chess;
}
int main()
{
int i,j;
while(1)
{
scanf("%d %d",&n,&k);
if(n==-1 && k==-1)
break;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&chess[i*n+j].num);
chess[i*n+j].x=i;
chess[i*n+j].y=j;
}
qsort(chess,n*n,sizeof(chess[0]),cmp);
printf("%d/n",dp_fuction());
}
return 0;
}