萌新求助:刷表法,为什么要判断下一个状态合不合法
查看原帖
萌新求助:刷表法,为什么要判断下一个状态合不合法
438461
liu_chen_hao楼主2022/11/8 21:05

RT,我的代码一直WA,看题解说要判断现在的状态能否转移到下一个状态。但是,如果这个转移非法,那dp的结果应该是负数,也不会转移错误。但判断的语句不写就会WA,请问大佬这是为什么。

我的代码:

#include <bits/stdc++.h>
using namespace std;
const int T=105,D=3505;

struct node {
	int t,w,h;
}a[T];
int n,m;
int f[T][D];

int read() {
    int sss=0,www=1;
    char ccch=getchar();
    while(ccch<'0' || ccch>'9') { if(ccch=='-') www=-1; ccch=getchar(); }
    while(ccch>='0' && ccch<='9') sss=sss*10+ccch-'0',ccch=getchar();
    return sss*www;
}
bool cmp(node x, node y) {
	return x.t<y.t;
}
int main()
{
    m=read(),n=read();
    for(int i=1; i<=n; i++)
    {
    	a[i].t=read();
    	a[i].w=read();
    	a[i].h=read();
    }
    sort(a+1,a+n+1,cmp);

    memset(f,-0x3f,sizeof(f));
    f[0][0]=10;
    for(int i=0; i<n; i++)
    {
    	for(int j=0; j<=m; j++)
    	{
    		if(f[i][j]<0) continue;

    		if(j+a[i+1].h>=m && f[i][j]-a[i+1].t+a[i].t>=0)
    		{
    			printf("%d", a[i+1].t);
    			return 0;
    		}

    		if(f[i][j]-a[i+1].t+a[i].t>=0)        //  这两句不写就WA,为什么呢?
    			f[i+1][j]=max(f[i+1][j],f[i][j]+a[i+1].w-a[i+1].t+a[i].t);
    		if(f[i][j]-a[i+1].t+a[i].t>=0)        //  这两句不写就WA,为什么呢?
    			f[i+1][j+a[i+1].h]=max(f[i+1][j+a[i+1].h],f[i][j]-a[i+1].t+a[i].t);
    	}
    }

    int s=10,p=0;
    for(int i=1; i<=n; i++)
    {
    	if(s-a[i].t+a[i-1].t<0)
    	{
    		printf("%d", p+s);
    		return 0;
    	}
    	s+=a[i].w-a[i].t+a[i-1].t;
    	p+=a[i].t-a[i-1].t;
    }
    printf("%d", s+p);

    return 0;
}
2022/11/8 21:05
加载中...