C++从入门到入土-递推算法

1.过河卒

C++从入门到入土-递推算法_第1张图片

代码:

#include 
#include 
#include  
using namespace std;
int xi[9]={0,-2,-1,1,2,2,1,-1,-2},
    yi[9]={0,1,2,2,1,-1,-2,-2,-1};
unsigned long long a[21][21],n,m,x,y,j;
bool map[21][21];
int main()
{
	freopen("knight.in","r",stdin);
	freopen("knight.out","w",stdout); 
    cin>>n>>m>>x>>y;
    for(int i=1;i<=8;i++)
    {
        if(xi[i]+x>=0&&xi[i]+x<=20&&yi[i]+y>=0&&yi[i]+y<=20)//判断边界 
            map[xi[i]+x][yi[i]+y]=1;
    }
    map[x][y]=1;
    for(int i=0;i<=20;i++)
    {
		if(map[0][i]==1)
		{
			a[0][i]=0;
			break;
		}
		a[0][i]=1;
	}
    for(int i=0;i<=20;i++)
    {
		if(map[i][0]==1)
		{
			a[i][0]=0;
			break;
		}
		a[i][0]=1;
	}      
    for(int i=1;i<=n;i++)
        for(j=1;j<=m;j++)
        {
	        if(map[i][j]==1)	
				a[i][j]=0;
	        else a[i][j]=a[i-1][j]+a[i][j-1];
        }
    cout<

2.邮票问题

C++从入门到入土-递推算法_第2张图片

#include
#include
#include
using namespace std;
int m,n,i;
int a[256];
int piece[33333];
int main(void)
{
	freopen("stamp.in","r",stdin);
	freopen("stamp.out","w",stdout);
	cin>>m>>n;
	for(i=1;i<=m;i++)
		cin>>a[i];
	memset(piece,0,sizeof(piece));	
	int maxx=0;
	while(true)
	{
		maxx++;
		for(i=1;i<=m;i++)
			if(maxx-a[i]>=0)
			{
				if (piece[maxx] == 0) 
					piece[maxx] = piece[maxx-a[i]] + 1;
	            if (piece[maxx]>piece[maxx-a[i]]+1)
					piece[maxx] = piece[maxx-a[i]]+1;
			}
		if((piece[maxx]==0)||(piece[maxx]>n))
		{
			cout<

你可能感兴趣的:(递推)