Free Candies

uva 10118 Free Candies 出现了一点问题,题目不能复制过来,主要的大意是有4堆糖果,有一个篮子,这个篮子最多可以装5个糖果,从4堆糖果堆的顶部每次取一个糖果,如果篮子中有颜色相同的一对糖果那么就可以装进口袋里,否则口袋达到5个后就结束游戏。 https://vjudge.net/problem/UVA-10118 上代码: #include #include #include #define max(a,b) 阅读详情

Little Bob is playing a game. He wants to win some candies in it - as many as possible.

There are 4 piles, each pile contains N candies. Bob is given a basket which can hold at most 5 candies. Each time, he puts a candy at the top of one pile into the basket, and if there're two candies of the same color in it ,he can take both of them outside the basket and put them into his own pocket. When the basket is full and there are no two candies of the same color, the game ends. If the game is played perfectly, the game will end with no candies left in the piles.

For example, Bob may play this game like this (N=5):

Step1Initial PilesStep2Take one from pile #2
PilesBasketPocketPilesBasketPocket
1 2 3 4
1 5 6 7
2 3 3 3
4 9 8 6
8 7 2 1
nothingnothing
1   3 4
1 5 6 7
2 3 3 3
4 9 8 6
8 7 2 1
2nothing
Step3Take one from pile #2Step4Take one from pile #3
PilesBasketPocketPilesBasketPocket
1   3 4
1   6 7
2 3 3 3
4 9 8 6
8 7 2 1
2 5nothing
1     4
1   6 7
2 3 3 3
4 9 8 6
8 7 2 1
2 3 5nothing
Step5Take one from pile #2Step6put two candies into his pocket
PilesBasketPocketPilesBasketPocket
1     4
1   6 7
2   3 3
4 9 8 6
8 7 2 1
2 3 3 5nothing
1     4
1   6 7
2   3 3
4 9 8 6
8 7 2 1
2 5a pair of 3

Note that different numbers indicate different colors, there are 20 kinds of colors numbered 1..20.

'Seems so hard...'Bob got very much puzzled. How many pairs of candies could he take home at most?

 

Input

The input will contain no more than 10 test cases. Each test case begins with a line containing a single integer n(1<=n<=40) representing the height of the piles. In the following n lines, each line contains four integers xi1,xi2,xi3,xi4 (in the range 1..20). Each integer indicates the color of the corresponding candy. The test case containing n=0 will terminate the input, you should not give an answer to this case.

Output

Output the number of pairs of candies that the cleverest little child can take home. Print your answer in a single line for each test case.

Sample Input

5
1 2 3 4
1 5 6 7
2 3 3 3
4 9 8 6
8 7 2 1
1
1 2 3 4
3
1 2 3 4
5 6 7 8
1 2 3 4
0

Sample Output

8
0

3

题意:题目中给了四堆多种颜色的糖果,每一堆有n个糖果,还给了一个篮子,这个篮子一次最多只能装5个糖果,如果在装的过程中有两个糖果的颜色一样,那么就可以把这一对糖果带回家了。每次只能从某堆的堆顶取糖果,问最多能带回家多少对糖果。

思路:这个题用栈做,我们可以把这每堆糖果看成一个栈,每次从栈顶取糖果,这道题有一个剪枝,就当每取出一个糖果时,此时四个栈的状态是唯一的,因为只要达到以前有过的状态,那么肯定是有相同的结果的,就是记忆化搜索,能大大缩短运行时间。代码如下:

#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
int n,maxx,num[50][5],book[50][50][50][50];
stack<int>Q[4];
void dfs(int x,int f,int ans,int p[])
{
    if(f>4)
    {
        return;
    }
    if(ans>maxx)
        maxx=ans;
    for(int i=0; i<4; i++)
    {
        p[i]++;
        if(!Q[i].empty()&&!book[p[0]][p[1]][p[2]][p[3]])
        {
            int t=Q[i].top();
            Q[i].pop();
            if(x&(1<<t))
            {
                int now=x-(x&(1<<t));
                dfs(now,f-1,ans+1,p);
            }
            else
            {
                int now=x|(1<<t);
                dfs(now,f+1,ans,p);
            }
            book[p[0]][p[1]][p[2]][p[3]]=1;
            Q[i].push(t);
        }
        p[i]--;
    }
}
int main()
{
    while(~scanf("%d",&n)&&n)
    {
        maxx=0;
        for(int i=0; i<4; i++)
        {
            while(!Q[i].empty())
                Q[i].pop();
        }
        for(int i=0; i<n; i++)
            for(int j=0; j<4; j++)
                scanf("%d",&num[i][j]);
        for(int i=n-1; i>=0; i--)
        {
            for(int j=0; j<4; j++)
                Q[j].push(num[i][j]);
        }
        memset(book,0,sizeof(book));
        book[0][0][0][0]=1;
        int ll[4]= {0};
        dfs(0,0,0,ll);
        printf("%d\n",maxx);
    }
}

 

【DP 训练】Free Candies, UVa 10118 #include using namespace std; int n,dp[50][50][50][50],pile[5][50],top[5]; int dfs(int cur,int status) { if(cur==5)return 0; int& ans = dp[top[1]][top[2]][top[3]][top[4]]; if(ans!=-1)return ans; a 阅读详情

相关推荐

基于GEC6818开发板的C/C++贪吃蛇小游戏

f.开始游戏(进入游戏,并没有马上开游戏,需要点击播放才能开始)2.相关宏,全局变量(可以根据自己需要进行修改)k.显示文字前的相关初始化。k.自定义font.h文件。1.需要的主要头文件。l.在开发板上显示字1。m.在开发板上显示字2。a.显示固定大小图片。h.线程1:获得坐标。

2301_77273301的博客 2139

Free Candies(记忆化+深搜)

Free Candies(记忆化+深搜) Little Bob is playing a game. He wants to win some candies in it - as many as possible. There are 4 piles, each pile contains N candies. Bob is given a basket which can hold at most 5 candies. Each time, he puts a candy at the top of o

Anthcony的博客 287

手把手教你解锁TI MSPM0G3507开发板(2025新版,附XDS110接线图)

本文详细解析了2025版TI MSPM0G3507开发板的解锁方法,针对新版硬件中BSL引脚的电路设计变化提供了精准接线方案和UniFlash软件配置步骤。通过实测数据和专业指导,帮助开发者解决芯片锁定问题,确保调试接口正常响应。

weixin_42696271的博客 821

Free Candies(记忆化搜索)

  Little Bob is playing a game. He wants to win some candies in it - as many as possible.   There are 4 piles, each pile contains N candies. Bob is given a basket which can hold at most 5 candies. Eac...

桃夭丶的博客 304

C语言实现定时任务

例:设置定时任务,每周周X的X时X分自动重启系统 思路:将设置好的重启时间保存到本地配置文件中,设置定时器定时一分钟,每一分钟信号触发一次事件,事件函数中获取配置文件信息与当前系统时间信息,将两个时间进行时间差计算,符合条件的自动重启系统. //创建定时器函数(通过信号触发事件timer_task函数启动) int create_timer() { struct sigevent evp; int ret = 0; memset(&evp, 0, sizeof(stru

佳佳鸽的博客 5043

数字设计与计算机体系结构习题答案,数字设计和计算机体系结构习题答案DigitalDesignandComputerArchitecture.pdf...

数字设计和计算机体系结构习题答案DigitalDesignandComputerArchitecture.pdfDavid Money Harris and Sarah L. Harris, Digital Design and Computer Architecture, © 2007 by Elsevier Inc.Exercise SolutionsC H A P T E R ...

weixin_39851408的博客 1797

Uva--10118(动规,记忆化搜索)

2014-08-2422:24:57 Problem B. Free Candies The Problem Little Bob is playing a game. He wants to win some candies in it - as many as possible. There are 4 piles, each pile ...

dingdi3021的博客 250

本地AI语音生成与配音工作台Pandrator:从TTS到RVC的完整实践指南

语音合成(TTS)技术通过深度学习模型将文本转换为自然语音,其核心原理涉及声学建模与波形生成。这项技术不仅提升了人机交互体验,更在内容创作领域展现出巨大价值,广泛应用于有声书制作、视频配音、虚拟助手等场景。本文聚焦于一个集成了XTTS-v2、RVC等先进模型的本地化AI语音工作台——Pandrator,它通过模块化架构将语音合成、声音克隆、音频转录与翻译等流程无缝整合,为用户提供了一个图形化、可定制的完整解决方案。文章深入解析了其基于TTS与RVC(Retrieval-based Voice Convers

weixin_42676876的博客 348

uva 10118 Free Candies+记忆化搜索

uva 10118 Free Candies 解决方案:dp思路为:dp[a1][a2][a3][a4]表示当取四堆的a1、a2、a3、a4之后最多获得多少对糖,由于只有20种糖,可以开一个20大的数组表示当前篮子中的存在不存在这种糖(只存不同的糖,相同的收回口袋),用cnt来记录篮子中的糖的个数,若cnt==5,且没有相同的糖,则dp[a1][a2][a3][a4]=0,表示当前状态无法再取,

u012870383的专栏 674

QT+Halcon实现螺纹检测

工业上要检测螺丝的内外直径、内外牙距、内外角度,现在比较好用的图像处理库,开源的opencv,收费的有halcon。为了实现螺纹检测,和对比螺纹检测拿个库比较好。分别用opencv和halcon实现了螺纹检测,通过对比发现用halcon实现的效果比较。现在用博客把实现过程记录下来: 1、需要检测的螺纹数据如下: 2、为了实现检测螺丝以上数据,螺纹内径、螺纹外径、螺纹外牙距、螺纹...

专注现代C++实战,从核心语法到高性能编程,助力开发者深入掌握系统级编程精髓。 7063

原理之(〇)3D Gaussian Splatting 数学原理与推导

3D Gaussian Splatting源于EWA的理论基础,本文重点从EWA模型出发,详细推导3D GS中的数学原理,加深对鱼眼相机畸变场景下的理解。

scott198512的博客 4170

免费糖果 Free Candies

UVA10118 定义: dp[a][b][c][d]dp[a][b][c][d]dp[a][b][c][d]为第0列取了aaa颗糖果,第1列bbb颗,第二列ccc颗,第三列ddd后剩下的糖果还能最多再装进口袋多少个。那么答案就是dp[0][0][0][0]dp[0][0][0][0]dp[0][0][0][0],即考虑所有糖果。Candies[i][j]Candies[i][j]Candies[...

蒟蒻的博客 347

华为ensp、思科eve、华为ensp pro中通过cloud桥接本地网络和联通互联网的方法

华为ensp、思科eve中通过cloud桥接本地网络和联通互联网的方法

suofen9703的博客 468

[UVa 10118]Free Candies

Problem DescriptionLittle Bob is playing a game. He wants to win some candies in it - as many as possible.

373

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

UVA10118Free Candies

一开始看数据范围不大想直接暴力搜索,仔细考虑搜索的状态会有很多重复,搜索量仍然很大。 这就是传说中的记忆化搜索。。。number数组表示每一列取了多少个数,ans每一列取得相应数字个数时的最优解。 第九章前面的代码用了引用,在记忆化搜索里面很方便。这个题还要注意搜索的时候要回溯,搜不下去了要尝试另一种。 1 #include <stdio.h> 2 #incl...

188

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

【Uva 10118】Free Candies

【Link】: 【Description】 有4堆书; 每本书编号从1..20 每堆书都是N本; 然后每次只能从任意一堆的堆顶拿一本书装到自己的口袋里; 你的口袋最多容纳5本书; 当你的口袋里有两本一样的书的时候,那一对书就归你了; 但是一旦你的口袋装满了,就不能再装书了;游戏停止 问你最多能拿多少对书。 【Solution】 比较明显...

AWCXV 100

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: How many ways
下一篇: Palindrome
Angeliaaa
博客等级 码龄8年 17粉丝 90原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值