hdu1355The Peanuts

感觉我的代码是没有错的,哈哈哈....其中abs不知道老是用不了,结果只能用最土的方法了啊a>b?a:b;

但是没有通过

#include "iostream"
#include "cmath"
#include "algorithm"
using namespace std;
struct  student{
  int x,y,count,time;
}num[10000];
struct{
  int time,count;
}dp[10000];
int cmp(student a,student b){
  return a.count>b.count;
}
int abs(int a){return a>0?a:0;}
int match(int a,int b){
  int temp=0;
  temp+=num[a].x>num[b].x?(num[a].x-num[b].x):(num[b].x-num[a].x);
  temp+=num[a].y>num[b].y?(num[a].y-num[b].y):(num[b].y-num[a].y);
  return temp;
}
int max(int a,int b){return a>b?a:b;}
int main(){
  int ncase,top,m,n,k,i,j,map[60][60],maxb;
  cin>>ncase;
  while(ncase--){
    top=1;
    cin>>m>>n>>k;
    for(i=1;i<=m;i++){
      for(j=1;j<=n;j++){
        cin>>map[i][j];
        if(map[i][j]){
          num[top].x=i;num[top].y=j;num[top].count=map[i][j];num[top++].time=i+1;
        }
      }
    }
    sort(num+1,num+top,cmp);
    for(i=1;i<top;i++){
      if(k>=2*num[i].x+1){
        dp[i].time=k-num[i].x-1;
        dp[i].count=num[i].count;
      }
    }
    maxb=dp[1].count;
    for(i=2;i<top;i++){
      for(j=1;j<i;j++){
        //cout<<dp[j].time<<' '<<" i j "<<i<<' '<<j;
        //cout<<"match(i,j) "<<match(i,j)<<' '<<num[i].x<<' '<<match(i,j)+num[i].x+1<<endl;
        if(dp[j].time>=match(i,j)+num[i].x+1){
          if(dp[i].count<dp[j].count+num[i].count){
            //cout<<"i "<<i<<" j "<<j<<' '<<match(i,j)<<endl;
            dp[i].time=dp[j].time-match(i,j)-1;
            //cout<<"time "<<dp[i].time<<endl;
            dp[i].count=dp[j].count+num[i].count;
            maxb=max(maxb,dp[i].count);
          }
        }
      }
    }
    cout<<maxb<<endl;
  }
}

人家的代码,是直接的贪心算法来的,不过我不觉得他们那样做是对的,因为有可能最大数在一个角落,而且其他小数的和比最大数大,这样贪心算法就是错的

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int mm=55;
class node
{
    public:
    int x,y,peanuts;
}f[mm*mm];
int grap[mm][mm];
int dp[2][mm*mm];
int cas,m,n,t,pos;
bool cmp(node a,node b)
{
    return a.peanuts>b.peanuts;
}
int fabs(int x)
{
    return x>0?x:-x;
}
int main()
{
    while(cin>>cas)
    {
        while(cas--)
        {    pos=0;
            cin>>m>>n>>t;
            memset(dp,0,sizeof(dp));
            for(int i=1;i<=m;i++)
            for(int j=1;j<=n;j++)
            {
                cin>>grap[i][j];
                f[pos].x=i;f[pos].y=j;f[pos].peanuts=grap[i][j];
                pos++;
            }
            sort(f,f+pos,cmp);
            int shu=f[0].peanuts,uset=0,ans=0,nx=0,ny=f[0].y;
            for(int i=0;i<pos;i++)
            {   if(f[i].peanuts==0)break;
                if(uset+fabs(f[i].x-nx)+fabs(f[i].y-ny)+f[i].x+1<=t)
                {
                    uset+=fabs(f[i].x-nx)+fabs(f[i].y-ny)+1;
                    nx=f[i].x;ny=f[i].y;
                    ans+=f[i].peanuts;
                }
                else break;
            }
            cout<<ans<<"\n";
        }
    }
}

 

posted @ 2013-08-30 14:24  龙城星  阅读(122)  评论(0编辑  收藏  举报