ccf201809_4,再賣菜

一開始列了不等式,然後開始遞推,結果只有10分。。。後來看了一個答案說用動態規劃,代碼看不懂…然後看了另一個答案用暴搜+記憶化搜索,欸這個可以,於是寫出來了…感覺確實沒什麼難度,用遞歸的思想其實就一路往下推就可以,主要是怎麼寫出來。

#include<cstdio>
#include <cstring>
#include <algorithm>

using namespace std;


int n;
int a[305];
int x[305];

bool f[305][305][305];

void dfs(int day,int lastx,int curx){
    if(lastx <= 0||curx <= 0)
    {
        return;
    }
    if(f[day][lastx][curx]){
        return;
    }
    f[day][lastx][curx] = true;

    if(day==n)
    {
        if((x[day-1]+x[day])/2 == a[day])
        {
            for(int i = 1;i<=n;i++)
            {
                printf("%d ",x[i]);
            }
            exit(0);
        }
    }else{
        x[day+1]=a[day]*3-lastx-curx;
        dfs(day+1,x[day],x[day+1]);

        x[day+1]=a[day]*3-lastx-curx+1;
        dfs(day+1,x[day],x[day+1]);

        x[day+1]=a[day]*3-lastx-curx+2;
        dfs(day+1,x[day],x[day+1]);
    }
}

int main() {
    scanf("%d",&n);
    for(int i =1;i<=n;i++)
    {
        scanf("%d",&a[i]);

    }
    for(int i = 1;i<=a[1]*2;i++)
    {
        x[1] = i;x[2] = a[1]*2-x[1];
        dfs(2,x[1],x[2]);

        x[1] = i;x[2] = a[1]*2+1-x[1];
        dfs(2,x[1],x[2]);
    }

    return 0;
}

在這裏插入圖片描述

2019年9月4日更新

#include <bits/stdc++.h>
using namespace std;

int n;
int a[301];
bool undo[301][301][301];
int x[301];

void over(){
    for(int i = 0 ;i<n;i++)
    {
        printf("%d ",x[i]);
    }
    exit(0);
}

void dfs(int day,int cur,int next){
    if(cur <=0 || next <= 0)
    {
        return;
    }
    if(undo[day][cur][next]){
        return;
    }

    x[day] = cur;

    if(day == n-2)
    {
        if((cur+next)/2 == a[n-1]){
            x[day+1] = next;
            over();
        }
    }

    if(day<n-2){

        for(int i = 0;i<3;i++)
        {
            dfs(day+1,next,a[day+1]*3+i-cur-next);
            undo[day][cur][next] = true;
        }
    }
}


int main(){
    scanf("%d",&n);
    for(int i = 0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }

    for(int i = 1;i<=a[0]*2;i++){
        dfs(0,i,a[0]*2-i);
    }

    for(int i = 1;i<=a[0]*2+1;i++){
        dfs(0,i,a[0]*2+1-i);
    }


    return 0;
}



/**
8
2 2 1 3 4 9 10 13

*/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章