USCAO section Mother's Milk(搜索)

USACO section 3.4 Closed Fences(计算几何+叉积+二分) Closed Fences A closed fence in the plane is a set of non-crossing, connected line segments with N corners (3 i, yi}, i in (1..N). Every pair of adjacent vertices defines a side of the fence. 阅读详情
Mother's Milk

Farmer John has three milking buckets of capacity A, B, and C liters. Each of the numbers A, B, and C is an integer from 1 through 20, inclusive. Initially, buckets A and B are empty while bucket C is full of milk. Sometimes, FJ pours milk from one bucket to another until the second bucket is filled or the first bucket is empty. Once begun, a pour must be completed, of course. Being thrifty, no milk may be tossed out.

Write a program to help FJ determine what amounts of milk he can leave in bucket C when he begins with three buckets as above, pours milk among the buckets for a while, and then notes that bucket A is empty.

PROGRAM NAME: milk3

INPUT FORMAT

A single line with the three integers A, B, and C.

SAMPLE INPUT (file milk3.in)

8 9 10

OUTPUT FORMAT

A single line with a sorted list of all the possible amounts of milk that can be in bucket C when bucket A is empty.

SAMPLE OUTPUT (file milk3.out)

1 2 8 9 10

SAMPLE INPUT (file milk3.in)

2 5 10

SAMPLE OUTPUT (file milk3.out)

5 6 7 8 9 10


 

个人深搜解:这样编程需要很认真,否则容易出错,我也是调了挺久的

 

/*
ID:nealgav1
PROG:milk3
LANG:C++
*/
#include<fstream>
#include<cstring>
using namespace std;
int a,b,c;
bool s[22][22][22];
bool flag[23];
void dfs(int aa,int bb,int cc)
{
  if(s[aa][bb][cc])return;
  s[aa][bb][cc]=1;
  int x;
  if(aa==0)
  {
    flag[cc]=1;
    if(aa+cc<=a){x=cc;aa+=x;cc-=x;dfs(aa,bb,cc);aa-=x;cc+=x;}//c->a
    else {x=a-aa;cc-=x;aa+=x;dfs(aa,bb,cc);cc+=x;aa-=x;}
    if(aa+bb<=a){x=bb;bb-=x;aa+=x;dfs(aa,bb,cc);bb+=x;aa-=x;}//b->a
    else {x=a-aa;bb-=x;aa+=x;dfs(aa,bb,cc);bb+=x;aa-=x;}
    if(bb+cc<=c){x=bb;bb-=x;cc+=x;dfs(aa,bb,cc);cc-=x;bb+=x;}//b->c
    else{x=(c-cc);cc+=x;bb-=x;dfs(aa,bb,cc);bb+=x;cc-=x;}
    if(bb+cc<=b){x=cc;cc-=x;bb+=x;dfs(aa,bb,cc);cc+=x;bb-=x;}//c->b
    else{x=(b-bb);bb+=x;cc-=x;dfs(aa,bb,cc);bb-=x;cc+=x;}
  }
  else
  {
    if(aa+bb<=b){x=aa;bb+=x;aa-=x;dfs(aa,bb,cc);bb-=x;aa+=x;}//a->b
    else{x=(b-bb);aa-=x;bb+=x;dfs(aa,bb,cc);bb-=x;aa+=x;}
    if(aa+cc<=c){x=aa;cc+=x;aa-=x;dfs(aa,bb,cc);cc-=x;aa+=x;}//a->c
    else{x=(c-cc);aa-=x;cc+=x;dfs(aa,bb,cc);cc-=x;aa+=x;}
    if(aa+cc<=a){x=cc;aa+=x;cc-=x;dfs(aa,bb,cc);aa-=x;cc+=x;}//c->a
    else {x=a-aa;cc-=x;aa+=x;dfs(aa,bb,cc);cc+=x;aa-=x;}
    if(aa+bb<=a){x=bb;bb-=x;aa+=x;dfs(aa,bb,cc);bb+=x;aa-=x;}//b->a
    else {x=a-aa;bb-=x;aa+=x;dfs(aa,bb,cc);bb+=x;aa-=x;}
    if(bb+cc<=c){x=bb;bb-=x;cc+=x;dfs(aa,bb,cc);cc-=x;bb+=x;}//b->c
    else{x=(c-cc);cc+=x;bb-=x;dfs(aa,bb,cc);bb+=x;cc-=x;}
    if(bb+cc<=b){x=cc;cc-=x;bb+=x;dfs(aa,bb,cc);cc+=x;bb-=x;}//c->b
    else{x=(b-bb);bb+=x;cc-=x;dfs(aa,bb,cc);bb-=x;cc+=x;}
  }
}
int main()
{  int aa,bb,cc;
ifstream fin("milk3.in");
ofstream fout("milk3.out");
  while(fin>>a>>b>>c)
  {
    memset(flag,0,sizeof(flag));
    memset(s,0,sizeof(s));
        dfs(0,0,c);
        int ans=0;
        for(int i=0;i<21;i++)
        if(flag[i])
        ans=i;
        for(int i=0;i<21;i++)
        if(flag[i]&&ans!=i)
        fout<<i<<" ";
        fout<<ans<<"\n";
  }
}


 

以下摘自独孤的博客,感觉着个方法代码敲的少,不易错

还是个搜索题,每次最多无非有6种倒法,即a->b;a->c;b->a;b->c;c->a;c->b。所以如果用a、b、c代表三个桶的容积,x、y、z代表当前三个桶内的牛奶数,那么不难算出执行完a->b后,x变为max(0,x+y-b),y变为min(b,x+y),z不变。其它倒法类似。

最后注意判重最好的方法就是用bool数组flag[i][j][k]表示a、b、c桶分别装i、j、k升牛奶这种状态是否曾经搜到过。但由于牛奶总数不变,故知道了i和j,其实k也就知道了,所以用二维bool数组flag[i][j]就够了。

源码如下:

 

#include <fstream>

using namespace std;

int a,b,c;
bool flag[21][21],can[21];

void dfs(int,int,int);

int main() {
ifstream fin ("milk3.in");
ofstream fout ("milk3.out");
fin >> a >> b >> c;
dfs(0,0,c);
for (int i=0;i<c;i++) if (can[i]) fout << i << ' ';
fout << c << endl;
fin.close();
fout.close();
return 0;
}

void dfs(int x,int y,int z) {
if (flag[x][y]) return;
flag[x][y]=true;
if (x==0) can[z]=true;
if (x>0 && y<b) dfs(max(0,x+y-b),min(b,x+y),z);
if (x>0 && z<c) dfs(max(0,x+z-c),y,min(c,x+z));
if (y>0 && x<a) dfs(min(a,y+x),max(0,y+x-a),z);
if (y>0 && z<c) dfs(x,max(0,y+z-c),min(c,y+z));
if (z>0 && x<a) dfs(min(a,z+x),y,max(0,z+x-a));
if (z>0 && y<b) dfs(x,min(b,z+y),max(0,z+y-b));
}

 

 

 

 

USER: Neal Gavin Gavin [nealgav1]
TASK: milk3
LANG: C++

Compiling...
Compile: OK

Executing...
   Test 1: TEST OK [0.011 secs, 3348 KB]
   Test 2: TEST OK [0.000 secs, 3348 KB]
   Test 3: TEST OK [0.000 secs, 3348 KB]
   Test 4: TEST OK [0.000 secs, 3348 KB]
   Test 5: TEST OK [0.000 secs, 3348 KB]
   Test 6: TEST OK [0.000 secs, 3348 KB]
   Test 7: TEST OK [0.000 secs, 3348 KB]
   Test 8: TEST OK [0.000 secs, 3348 KB]
   Test 9: TEST OK [0.000 secs, 3348 KB]
   Test 10: TEST OK [0.000 secs, 3348 KB]

All tests OK.

Your program ('milk3') produced all correct answers! This is your submission #2 for this problem. Congratulations!

Here are the test data inputs:

------- test 1 ----
2 5 10
------- test 2 ----
20 20 20
------- test 3 ----
5 11 15
------- test 4 ----
2 12 20
------- test 5 ----
19 4 11
------- test 6 ----
5 11 13
------- test 7 ----
3 20 20
------- test 8 ----
7 16 20
------- test 9 ----
20 10 9
------- test 10 ----
7 12 18
Keep up the good work!

 

Mother's Milk
Russ Cox

We use a simple depth-first search to find all the possible states for the three buckets, pruning the search by not researching from states we've seen before.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>

#define MAX 20

typedef struct State	State;
struct State {
    int a[3];
};

int seen[MAX+1][MAX+1][MAX+1];
int canget[MAX+1];

State
state(int a, int b, int c)
{
    State s;

    s.a[0] = a;
    s.a[1] = b;
    s.a[2] = c;
    return s;
}

int cap[3];

/* pour from bucket "from" to bucket "to" */
State
pour(State s, int from, int to)
{
    int amt;

    amt = s.a[from];
    if(s.a[to]+amt > cap[to])
	amt = cap[to] - s.a[to];

    s.a[from] -= amt;
    s.a[to] += amt;
    return s;
}

void
search(State s)
{
    int i, j;

    if(seen[s.a[0]][s.a[1]][s.a[2]])
	return;

    seen[s.a[0]][s.a[1]][s.a[2]] = 1;

    if(s.a[0] == 0)	/* bucket A empty */
	canget[s.a[2]] = 1;

    for(i=0; i<3; i++)
    for(j=0; j<3; j++)
	search(pour(s, i, j));	
}

void
main(void)
{
    int i;
    FILE *fin, *fout;
    char *sep;

    fin = fopen("milk3.in", "r");
    fout = fopen("milk3.out", "w");
    assert(fin != NULL && fout != NULL);

    fscanf(fin, "%d %d %d", &cap[0], &cap[1], &cap[2]);

    search(state(0, 0, cap[2]));

    sep = "";
    for(i=0; i<=cap[2]; i++) {
	if(canget[i]) {
	    fprintf(fout, "%s%d", sep, i);
	    sep = " ";
	}
    }
    fprintf(fout, "\n");

    exit(0);
}

Ran Pang from Canada sends this non-recursive DP solution:

#include<stdio.h>

int m[21][21][21];
int poss[21];
int A, B, C;

int main(void) {
    int i,j,k;
    int flag;
    FILE* in=fopen("milk3.in","r");
    fscanf(in, "%d %d %d",&A, &B, &C);
    fclose(in);
    for(i=0;i<21;i++)
        for(j=0;j<21;j++)
            for(k=0;k<21;k++)
                m[i][j][k]=0;
    for(i=0;i<21;i++)
        poss[i]=0;
    m[0][0][C]=1;

    for(flag=1;flag;) {
        flag=0;
        for(i=0;i<=A;i++)
            for(j=0;j<=B;j++)
                for(k=0;k<=C;k++) {
                    if(m[i][j][k]) {
                	if(i==0) poss[k]=1;
		        if(i) {
	                    if(j<B) {
                                if(B-j>=i) {
                            	    if( m[0][j+i][k]==0) {
                                        m[0][j+i][k]=1;
                                	flag=1;
                            	    }
                                } else {
                            	    if( m[i-(B-j)][B][k] == 0) {
                                        m[i-(B-j)][B][k] =1;
                                        flag=1;
                                    }
                                }
                            }
                            if(k<C) {
                                if(C-k>=i) {
                                    if( m[0][j][k+i]==0) {
                                        m[0][j][k+i]=1;
                                        flag=1;
                                    }
                                }
                                else {
                                    if( m[i-(C-k)][j][C] == 0) {
                                        m[i-(C-k)][j][C] =1;
                                        flag=1;
                                    }
                                }
                            }
                        }
                        if(j) {
                            if(i<A) {
                                if(A-i>=j) {
                                    if( m[i+j][0][k]==0) {
                                        m[i+j][0][k]=1;
                                        flag=1;
                                    }
                                } else {
                                    if( m[A][j-(A-i)][k] == 0) {
                                        m[A][j-(A-i)][k] =1;
                                        flag=1;
                                    }
                                }
                            }
                            if(k<C) {
                                if(C-k>=j) {
                                    if( m[i][0][k+j]==0) {
                                        m[i][0][k+j]=1;
                                        flag=1;
                                    }
                                } else {
                                    if( m[i][j-(C-k)][C] == 0) {
                                        m[i][j-(C-k)][C] =1;
                                        flag=1;
                                    }
                                }
                            }
                        }
                        if(k) {
                            if(i<A) {
                                if(A-i>=k) {
                                    if( m[i+k][j][0]==0) {
                                        m[i+k][j][0]=1;
                                        flag=1;
                                    }
                                } else {
                                    if( m[A][j][k-(A-i)] == 0) {
                                        m[A][j][k-(A-i)] =1;
                                        flag=1;
                                    }
                                }
                            }
                            if(j<B) {
                                if(B-j>=k) {
                                    if( m[i][j+k][0]==0) {
                                        m[i][j+k][0]=1;
                                        flag=1;
                                    }
                                } else {
                                    if( m[i][B][k-(B-j)] == 0) {
                                        m[i][B][k-(B-j)] =1;
                                        flag=1;
                                    }
                                }
                            }
                        }
            }                   
        }
    }
    {
        FILE* out=fopen("milk3.out", "w");
        for(i=0;i<21;i++) {
            if(poss[i]) {
                fprintf(out,"%d",i);
                i++;
                break;
            }
        }
        for(;i<21;i++) {
            if(poss[i]) {
                fprintf(out, " %d", i);
            }
        }
        fprintf(out,"\n");
    }
    return 0;
}

Daniel Jasper from Germany writes:

Both other solutions (recursive and non-recursive) use a 3D-array to store the states, so that the memory usage is O(N3). However a 2D Array and O(N2) would be enough since a state is uniquely defined by the amount of milk in bucket B and C. The amount of milk in bucket A is size-of-C minus amount-in-C minus amount-in-B. This solution works with it, and is a little bit shorter (though not more elegant):

#include <stdio.h>
int A, B, C;
int CB[21][21]; // All states

void readFile() {
    FILE *f;
    f = fopen("milk3.in", "r");
    fscanf(f, "%d%d%d", &A, &B, &C);
    fclose(f);
}

void writeFile() {
    FILE *f; int i;
    f = fopen("milk3.out", "w");
    for(i = 0; i <= C; i++) {
        if(CB[i][C - i] == 1) {
            if((i != C-B) && (i != 0)) fprintf(f, " ");
            fprintf(f, "%d", i);
        }
    }
    fprintf(f, "\n");
    fclose(f);
}

// do brute-force search, c/b: current state
void search(int c, int b) {
    int a;
    if(CB[c][b] == 1) return; // already searched
    CB[c][b] = 1;
    a = C-b-c; // calc amount in A
    // do all moves:
    // c->b
    if(B < c+b) search(c - (B - b), B);
    else search(0, c + b);
    // b->c
    if(C < c+b) search(C, b - (C - c));
    else search(c + b, 0);
    // c->a
    if(A < c+a) search(c - (A - a), b);
    else search(0, b);
    // a->c
    if(C < c+a) search(C, b);
    else search(c + a, b);
    // b->a
    if(A < b+a) search(c, b - (A - a));
    else search(c, 0);
    // a->b
    if(B < b+a) search(c, B);
    else search(c, b + a);
   }
   
int main () {
    readFile();
    search(C, 0);
    writeFile();
    return 0;
}

 

 

Vivado2019.1 ZYNQ7020无Uart SDK调试打印调试信息xil_printf 阅读详情

相关推荐

VMFS数据存储(datastore)丢失后恢复步骤

vmfs datastore恢复步骤

jetliu05的博客 3267

【USACO】Mother's Milk(搜索)

一开始还在想去重的问题,结果发现后台数据貌似没有重复的情况= = /* ID: 18906421 LANG: C++ PROG: milk3 */ #include #include #include #include using namespace std; const int maxn = 25; int vis[maxn][maxn][maxn] = {0}; vectorans; int

花月阁 862

水文预报新手别怕!用Matlab 18小时搞定马斯京根法参数K和x(附完整代码)

本文详细介绍了如何使用Matlab在18小时内快速掌握水文预报中的马斯京根法参数K和x的求解方法。通过完整的代码示例和分步解析,帮助新手从理论到实践快速跨越,解决传统手工试算耗时耗力的问题,提升水文预报的效率和精度。

weixin_42573113的博客 256

uscao Mother's Milk

bfs吧,我做过一题非常可乐跟这题很像。就是每次把牛奶在两个杯子中互倒,找到所有情况把a==0这个情况下的c保存起来(可能不同状态下的c相同用vis标记)。 /* ID: jinbo wu LANG: C++ TASK: milk3 */ #include using namespace std; bool v[25][25][25]; bool vis[25]; struct

silence401的博客 362

vscode中创建vue快捷键

1.安装Vetur插件(扩展里面直接搜) 2.vscode 界面里面左上角选则 文件=> 首选项=> 用户代码片段=>新建全局代码片段=>在输入框中新建名称为vue.json 3.删除里面的注释,当然你也可以留着,把下面的代码粘贴进去! { // Place your 全局 snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and // descri

Leon_940002463的博客 3207

基因组研究之单倍型T2T基因组(一)

单倍型T2T基因组(Haplotype-resolved T2T genome)是一种高精度、高连续性、高完整性的基因组组装技术,它能够提供从端粒到端粒的完整基因组序列,包括所有的基因和非编码序列。完整覆盖:T2T基因组覆盖从端粒到端粒的染色体序列,包含所有的基因和非编码序列,包括以往难以解析的端粒和着丝粒区域。单倍型解析:单倍型T2T基因组能够区分来自父母本的遗传信息,进行亚基因组不对称演化研究,挖掘单倍型等位基因间的表达差异,这对于重测序、性状定位、进化、基因功能、基因编辑等研究至关重要。

2401_89507557的博客 2438

[USACO1.4]母亲的牛奶 Mother's Milk 搜索

题目 Farmer John has three milking buckets of capacity A, B, and C liters. Each of the numbers A, B, and C is an integer from 1 through 20, inclusive. Initially, buckets A and B are empty while bucket C...

戒毒戒赌戒网瘾,学习学问学做人——好好学习 675

基于ADS1299的8通道脑电采集系统硬件设计实战

生物电信号采集是医疗电子与可穿戴设备中的关键环节,微弱信号的高保真放大与数字化处理直接影响系统性能。高精度模数转换器与低噪声模拟前端设计成为工程实践的核心。ADS1299作为专用生物电测量芯片,集成多通道低噪声放大器与24位Δ-Σ ADC,广泛应用于脑电、心电等生理信号检测。本文基于ADS1299构建8通道脑电采集系统,详细阐述硬件架构、电源与参考设计、输入保护、PCB布局布线、固件SPI配置及数据读取,并结合实测数据分享噪声抑制与调试经验,为EEG采集设备开发提供完整参考。

weixin_29169505的博客 224

USCAO-Section 1.4 Mother's Milk

原题: Mother’s MilkFarmer John has three milking buckets of capacity A, B, and C liters. Each of the numbers A, B, and C is an integer from 1 through 20, inclusive. Initially, buckets A and B are empty

qq_34407173的博客 355

FTViewSE利用VB脚本制作简易日报表

罗克韦尔SE用VB做的简单的报表

z0800656的博客 3023

用HFSS仿真平面线圈的电感量

平面线圈是指在平面上绕制而成的线圈,如PCB上的电感线圈、无线供电使用的金属丝绕制而成的线圈等。根据线圈的不同形状可将平面线圈分为方形线圈,六角形线圈、八角形线圈、螺旋原型线圈等。

johnboat的专栏 1万+

USACO section 3.1 Contact(AC自动机)

Contact IOI'98 The cows have developed a new interest in scanning the universe outside their farm with radiotelescopes. Recently, they noticed a very curious microwave pulsing emission sent right f

nealgavin的专栏 9384

服务器搭建原神私服教程

项目的稳定版分支提供了编译好的服务端程序,但是博主觉得还是用dev版本的比较好。dev版本需要自己编译的,不要听到编译这两个字就头大,相反,这个服务端的编译相当简单。把文件中的两个IP地址127.0.0.1修改为你服务器的地址,修改完成后按 esc 输入 :wq。Mongodb作为服务端的数据库使用,我们这里安装最新版的Mongodb5。注意:如果想要使用最新版的服务端,必须安装>=17版本的java。tmux可以保证你关掉控制台的时候,程序依然继续运行。至此,服务端所需要的运行环境全部配置完成。

用最简单的方式说最重要的事!服务器、存储、云计 算、A智能的大数据产品、游戏开发技术。致力于广 大开发者、政企用户、各项机构等,构建云上世界提供全方位云计算解决方案。旨在打造差异化的开放式闭环生态系统帮助用户快速构建稳定、安全的云计算环境。 1万+

USCAO section 1.3 Calf Flac

Calf Flac It is said that if you give an infinite number of cows an infinite number of heavy-duty laptops (with very large keys), that they will ultimately produce all the world's great palindromes

nealgavin的专栏 6656

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

深度学习工具包 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")

USACO section 1.5 Checker Challenge(dfs深搜)

Checker ChallengeExamine the 6x6 checkerboard below and note that the six checkers are arranged on the board so that one and only one is placed in each row and each column, and there is never more tha

nealgavin的专栏 1923

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

USACO section 2.3 Longest Prefix(dp)

Longest Prefix IOI'96 The structure of some biological objects is represented by the sequence of their constituents, where each part is denote by an uppercase letter. Biologists are interested in

nealgavin的专栏 1486

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

USACO section 2.4 Cow Tours(并查集+最短路)

Cow Tours Farmer John has a number of pastures on his farm. Cow paths connect some pastures with certain other pastures, forming a field. But, at the present time, you can find at least two pasture

nealgavin的专栏 1405

USACO section3.1 Shaping Regions(漂浮法)

Shaping Regions N opaque rectangles (1 <= N <= 1000) of various colors are placed on a white sheet of paper whose size is A wide by B long. The rectangles are put with their sides parallel to the s

nealgavin的专栏 1052

USACO section 2.2 Runaround Numbers

Runaround Numbers Runaround numbers are integers with unique digits, none of which is zero (e.g., 81362) that also have an interesting property, exemplified by this demonstration: If you start

nealgavin的专栏 989

USACO section 3.1 Stamps(dp)

Stamps Given a set of N stamp values (e.g., {1 cent, 3 cents}) and an upper limit K to the number of stamps that can fit on an envelope, calculate the largest unbroken list of postages from 1 cent

nealgavin的专栏 980

USCAO section 4.1 Fence Loops(最短路,最小环,5级)

Fence Loops The fences that surround Farmer Brown's collection of pastures have gotten out of control. They are made up of straight segments from 1 through 200 feet long that join together only a

nealgavin的专栏 941

USACO section 1.5 Superprime Rib(深搜)

Superprime RibButchering Farmer John's cows always yields the best prime rib. You can tell prime ribs by looking at the digits lovingly stamped across them, one by one, by FJ and the USDA. Farmer John

nealgavin的专栏 937

USACO section 2.2 Party Lamps

Party Lamps IOI 98 To brighten up the gala dinner of the IOI'98 we have a set of N (10 <= N <= 100) colored lamps numbered from 1 to N. The lamps are connected to four buttons: Button 1: Wh

nealgavin的专栏 913

USACO section 3.2 Spinning Wheels(模拟)

Spinning Wheels 1998 ACM NE Regionals Each of five opaque spinning wheels has one or more wedges cut out of its edges. These wedges must be aligned quickly and correctly. Each wheel also has an ali

nealgavin的专栏 875

USACO section 3.2 Feed Ratios(高斯定理)

Feed Ratios 1998 ACM Finals, Dan Adkins Farmer John feeds his cows only the finest mixture of cow food, which has three components: Barley, Oats, and Wheat. While he knows the precise mixture of th

nealgavin的专栏 803
上一篇: hdu 1010 Tempter of the Bone(DFS+剪枝优化)
下一篇: hdu 2795 Billboard(线段树)
剑不飞
博客等级 码龄15年 86粉丝 505原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值