USACO section 4.1 Fence Rails(搜索+优化)

Usaco Training Section 6.3 Fence Rails Fence Rails 栅栏的木料 农民John 准备建一个栅栏来围住他的牧场.他已经确定了栅栏的形状,但是他在木料方面有些 问题.当地的杂货储存商扔给John 一些木板,而John 必须从这些木板中找出尽可能多所需的木料. 当然,John 可以切木板.因此,一个9 英尺的木板可以切成一个5 英尺和一个4 英尺的木料 (当然也能切成3 个3 英尺的,等等).John 有一把梦幻之锯,因此他在切木料... 阅读详情

Fence Rails
Burch, Kolstad, and Schrijvers

Farmer John is trying to erect a fence around part of his field. He has decided on the shape of the fence and has even already installed the posts, but he's having a problem with the rails. The local lumber store has dropped off boards of varying lengths; Farmer John must create as many of the rails he needs from the supplied boards.

Of course, Farmer John can cut the boards, so a 9 foot board can be cut into a 5 foot rail and a 4 foot rail (or three 3 foot rails, etc.). Farmer John has an `ideal saw', so ignore the `kerf' (distance lost during sawing); presume that perfect cuts can be made.

The lengths required for the rails might or might not include duplicates (e.g., a three foot rail and also another three foot rail might both be required). There is no need to manufacture more rails (or more of any kind of rail) than called for the list of required rails.

PROGRAM NAME: fence8

INPUT FORMAT

Line 1:N (1 <= N <= 50), the number of boards
Line 2..N+1:N lines, each containing a single integer that represents the length of one supplied board
Line N+2:R (1 <= R <= 1023), the number of rails
Line N+3..N+R+1:R lines, each containing a single integer (1 <= ri <= 128) that represents the length of a single required fence rail

SAMPLE INPUT (file fence8.in)

4
30
40
50
25
10
15
16
17
18
19
20
21
25
24
30

OUTPUT FORMAT

A single integer on a line that is the total number of fence rails that can be cut from the supplied boards. Of course, it might not be possible to cut all the possible rails from the given boards.

SAMPLE OUTPUT (file fence8.out)

7

HINTS (use them carefully!)


思路:这是高纬度背包,只要开个dp[50][1023*128]来次背包就完事了,可惜开不出。

 而背包可以用搜索来实现,先将board,tail从小到大排,然后二分其能砍出的段的个数。

重点在于判断是否能砍出。

优化。space记录浪费空间,当space大于,总的borad-tail个数的和就砍不出。

先用小的borad的砍起,tail从大的开始,当tail[x-1]==tail[x] 那么tail[x-1]就不从从最小的开始搜了,可以再tail[x]的基础上开始。


/*
ID:nealgav1
LANG:C++
PROG:fence8
*/
#include<cstdio>
#include<fstream>
#include<cstring>
#include<algorithm>
using namespace std;
const int mm=1029;
ifstream cin("fence8.in");
ofstream cout("fence8.out");
int bo[mm],tail[mm],sum[mm],total,vb[mm],space=0;
int N,R,mid;
bool ok(int x,int z)
{ if(x<1)return 1;
  /// cout<<total<<" total"<<endl;
  if(total-space<sum[mid])///浪费空间过大
    return 0;

  for(int i=z;i<=N;++i)
  {
    if(vb[i]>=tail[x])
    {
      vb[i]-=tail[x];
      if(vb[i]<tail[1])space+=vb[i];///浪费的空间
      if(tail[x-1]==tail[x])///如果两块板一样,则这块板一定在i之后,如果在i之前,早就搜出解了
      {
        if(ok(x-1,i))return 1;
      }
      else if(ok(x-1,1))return 1;
      if(vb[i]<tail[1])space-=vb[i];
      vb[i]+=tail[x];

    }
  }
  return 0;
}
int main()
{
  while(cin>>N)
  { total=0;
    for(int i=1;i<=N;++i)
      {cin>>bo[i];total+=bo[i];}
    cin>>R;
    for(int i=1;i<=R;++i)
      cin>>tail[i];
      sort(bo+1,bo+N+1);sort(tail+1,tail+R+1);

    memset(sum,0,sizeof(sum));
    for(int i=1;i<=R;++i)
      sum[i]=sum[i-1]+tail[i];
    while(total<sum[R])--R;
    int l=1,r=R;int ans=0;
    while(l<=r)
    {
      mid=(l+r)/2;space=0;
      for(int i=1;i<=N;++i)vb[i]=bo[i];
      if(ok(mid,1)){l=mid+1;if(ans<mid)ans=mid;}
      else r=mid-1;
      ///cout<<total<<" ta"<<endl;
     /// cout<<mid<<" mid\n";
    }
    cout<<ans<<"\n";
  }
}

Fence Rails
Hal Burch

This is a high dimensionality multiple knapsack problem, so we just have to test the cases. Given that the search space has a high out-degree, we will use depth first search with iterative deepening in order to limit the depth of the tree. However, straight DFSID will be too slow, so some tree-pruning is necessary.

Note that if there is a way to cut k rails, there is a way to cut the k shortest rails, so we will only consider subsets of the rails that contain the k shortest rails. Also, we know the sum or the rails cut cannot exceed the sum of the lengths of the rails, so we can stop our DFS-ID if it finds a way to cut the largest set of shortest rails such that the sum of the lengths of the rails is less than the sum of the board lengths.

Since finding a board from which to cut a longer rail is more difficult than finding a board for a shorter rail, we will perform the search in such that the longest rail is cut first, then the second longest rail, etc.

Also, if two rails are of the same length, then cutting the first from board A and the second from board B is the same as cutting the first from board B and the second from board A, so within sets of rails of the same length, we will ensure that the rails are cut from boards of non-decreasing index.

If there are two boards of the same length, we need to check cutting the rail from only the first.

If there is a board of the same length of the rail, then cutting that rail from that board is optimal.

If, when cutting a board, we get a length of board less than the shortest rail, it is useless, and we can discard it from consideration. This reduces the total amount of board-feet left from which to cut the rest of the rails.

Here is Reid Barton's solution, which might or might not match the above description (sorry).

/*
ID: reid001
PROG: fence8
*/


#include <stdio.h>
#include <stdlib.h>

#define MAXBOARDS 50
#define MAXRAILS 1024

int nboards;
int boards[MAXBOARDS];
int next_board;

int nrails;
int rails[MAXRAILS];
int used[MAXRAILS];
int nused;

int best;

int num_V, num_L, num_R;

int comp_func( const void *a, const void *b );
int rev_comp_func( const void *a, const void *b );
void search( void );
int maximal( int k, int next, int other, int smin, int smax,
			 int remain[], int origid[], int bound );

inline int max( int a, int b )
{
	return (a < b) ? b : a;
}

int main( void )
{
	FILE *input = fopen( "fence8.in", "r" );
	fscanf( input, "%d", &nboards );
	for (int i = 0; i < nboards; i++)
		fscanf( input, "%d", &boards[i] );
	fscanf( input, "%d", &nrails );
	for (int i = 0; i < nrails; i++)
		fscanf( input, "%d", &rails[i] );
	rails[nrails++] = 1000000;
	qsort( boards, nboards, sizeof(int), comp_func );
	qsort( rails, nrails, sizeof(int), comp_func );
	
	int ans;
	if (boards[nboards-1] >= 1000000)
		// the answer might be off by one if we could supply the big rail.
		// but then we could supply all the other rails, so no need to search.
		ans = nrails - 1;
	else
	{
		next_board = 0;
		search();
		ans = best;
	}
	
	FILE *output = fopen( "fence8.out", "w" );
	fprintf( output, "%d\n", ans );
	
	//fprintf( stderr, "%d %d %d %d\n", ans, num_V, num_L, num_R );
	
	return 0;
}

int comp_func( const void *a, const void *b )
{
	const int *p = (const int *)a;
	const int *q = (const int *)b;
	if (*p < *q)
		return -1;
	else if (*p > *q)
		return 1;
	else
		return 0;
}

int rev_comp_func( const void *a, const void *b )
{
	return -comp_func( a, b );
}


void search( void )
{
	if (next_board == nboards)
	{
		if (best < nused)
			best = nused;
//		fprintf( stderr, "nused = %d best = %d\n", nused, best );
		return;
	}
	
int nremain;
int remain[MAXRAILS];
int origid[MAXRAILS];

	// find remaining rails,
	// as well as max # for this board, all remaining boards
	int boardsum = 0;
	for (int j = next_board; j < nboards; j++)
		boardsum += boards[j];
	
	nremain = 0;
	int k = 0, l = 0;
	for (int j = 0, sum = 0; j < nrails; j++)
		if (used[j] == 0)
		{
			remain[nremain] = rails[j];
			origid[nremain] = j;
			nremain++;
			sum += rails[j];
			if (sum <= boards[next_board])
				k++;
			if (sum <= boardsum)
				l++;
		}
	
	int bound;
	if ((bound = nused + l) <= best)
		return;
	// try all maximal m-subsets of remaining boards
	for (int m = k; m >= 0; m--)
		maximal( m, l-1, nremain-1, 0, boards[next_board],
				 remain, origid, bound );
}

int maximal( int k, int next, int other, int smin, int smax,
			 int remain[], int origid[], int bound )
{
	if (k == 0)
	{
		if ((smin <= 0) && (0 <= smax))
		{
			next_board++;
			search();
			next_board--;
		}
		return 0;
	}
	
	if (k > next+1)
		return 0;		// not enough boards left
	
	num_V++;
	
	int low_sum = 0;
	for (int j = 0; j < k; j++)
		low_sum += remain[j];
	if (low_sum > smax)
	{
		num_L++;
		return 0;
	}
	int hi_sum = 0;
	for (int j = 0; j < k; j++)
		hi_sum += remain[next-j];
	if (hi_sum < smin)
	{
		num_R++;
		return 0;
	}
	
	int last = other;
	for (int m = next; m >= k-1; m--)
	{
		if (remain[m] != remain[last] && (low_sum - remain[k-1] + remain[m]) <= smax)
		{
			int new_min = max( smin - remain[m], smax - remain[last] + 1 );
			used[origid[m]] = 1;
			nused++;
			int x = maximal( k-1, m-1, last, new_min, smax - remain[m],
							 remain, origid, bound );
			used[origid[m]] = 0;
			nused--;
			
			if (k == 1)
				return 0;
			
			if (bound <= best)
				return 0;
		}
		last = m;
	}
	
	return 0;
}


Hassan Eslami submitted a dramatically faster solution:
#include <cstdlib>
#include <fstream>
#include <algorithm>
#include <iostream>

using namespace std;

const int maxboard=50+1;
const int maxrail=1023+1;

// the arrays contains rails and boards lenght's
int rail[maxrail], board[maxboard];

// the array contains how much of the i_th board remain for cutting the rails from
int remain[maxboard];

// number of boards and rails
int nboard, nrail;

// sumlen[i] contains sum of the length of first i rails in the case
// that rails are in the sorted order

int sumlen[maxrail];

// minindex[i] contains the index of smallest board that i_th rail
// can cut from it(rails and boards are in the sorted order)
int minindex[maxrail];

//amount of board that 'can' be waste during one run of DSF
long long maywaste;

//amount of board that waste yet
int waste;

//best solution that we want to find
int best;

ifstream fin("fence8.in");
ofstream fout("fence8.out");


//r is the rail that we want cut from board index1 or index1+1 or ... or nboard-1
void DFS(int r, int index1){
    
    //if r is equal to 0 we must search for the last step of solution
    if (r == 0) {
        for (int i=index1; i<nboard; ++i)
            if (remain[i]>=rail[0]){
                
                //if we can cut best+1 rails, we print the solution
                fout << best+1 << endl;
                fout.close();
                exit(0);
            }
        return;
    }
    
    
    for (int i=index1; i<nboard; ++i)
        
        //for cutting r_th rail from i_th board this condition must hold
        if (remain[i]>=rail[r]) {
            int oldwaste=waste;
            remain[i]-=rail[r];
            
	    //now we check if i_th board being useless, amount of
	    // wasted board must be less than 'maywaste'
            if (remain[i]<rail[0] && waste+remain[i]>maywaste) {
                remain[i]+=rail[r];
                continue;
            }
            
            // if i_th board being useless we must update 'waste'
            if (remain[i]<rail[0]) waste+=remain[i];
            
	    // now we check if two rails have equal size, then the
	    // usage of board for them must be in non-decreasing order

            if (rail[r-1] == rail[r]) DFS(r-1, i);
            else DFS(r-1, minindex[r-1]);
            
            // at last we set the initial state again
            remain[i]+=rail[r];
            waste=oldwaste;
        }
}

int main() {
    
    // reading the input and compute sum of the boards length's,
    // also set the initial state of 'remain'

    fin >> nboard;
    long long sum=0;
    for (int i=0; i<nboard; ++i) {
        fin >> board[i];
        sum+=board[i];
        remain[i]=board[i];
    }
    fin >> nrail;
    for (int i=0; i<nrail; ++i)
        fin >> rail[i];
    fin.close();
    
    // sort the rails and boards
    sort(&board[0], &board[nboard]);
    sort(&rail[0], &rail[nrail]);
    
    // set maximum number of rails that we want to use, with out loss anything
    int temp=0;
    sumlen[0]=rail[0];
    for (; temp<nrail && sumlen[temp]<=sum; ++temp, sumlen[temp]=sumlen[temp-1]+rail[temp])
	;
    nrail=temp;
    
    // set minindex array
    for (int i=0, j=0; i<nrail; ++i) {
        while (j<nboard && rail[i]>board[j]) j++;
        minindex[i]=j;
        if (j == nboard) {
            nrail=i;
            break;
        }
    }
    
    // check out one special case
    if (nrail == 0) {
        fout << 0 << endl;
        fout.close();
        return 0;
    }
    
    // main part of code that use DFS+ID
    for (int i=nrail-1; i>=0; --i){
        waste=0;
        maywaste=sum-sumlen[i];
        best=i;
        DFS(i, minindex[i]);
    }
}

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

Compiling...
Compile: OK

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

All tests OK.

YOUR PROGRAM ('fence8') WORKED FIRST TIME! That's fantastic -- and a rare thing. Please accept these special automated congratulations.


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. 阅读详情

相关推荐

nnDetection复现Luna16 附模型

淘论文发现nnDetection框架对肺结节的检测效果挺好,便跑了跑复现了下, 作者诚不欺人,确实挺好, 并附上我依据文档训练的模型。

HeavenWalker 2597

Section 4.1 Fence Rails(DFS_ID迭代加深搜索+剪枝)

Fence Rails Burch, Kolstad, and Schrijvers Farmer John is trying to erect a fence around part of his field. He has decided on the shape of the fence and has even already installed the posts, but h

志当存高远 1045

GCC调试黑科技:-fomit-frame-pointer优化下如何保证栈回溯能力

本文深入探讨了GCC编译器在启用`-fomit-frame-pointer`优化选项时如何保证栈回溯能力。通过分析`.eh_frame`段的结构与DWARF调试信息,提供了从编译选项配置到实战调试的完整解决方案,帮助开发者在性能优化与调试能力之间找到最佳平衡点。

u6v7w8x的博客 904

[USACO]Fence Rails

Fence RailsBurch, Kolstad, and SchrijversFarmer John is trying to erect a fence around part of his field. He has decided on the shape of the fence and has even already installed the posts, but he's ha...

weixin_30919235的博客 282

13-单片机模块化程序: 单片机AT指令配置模块程序模板(非阻塞版)

资料源码:https://gitee.com/yang456/OpenProgrammingModuleForMCU.git 点击加入群聊【单片机,物联网,上位机】: 说明1:知识从未如此性感。 烂程序员关心的是代码,好程序员关心的是数据结构和它们之间的关系! 说明2:学的是思想,而非程序!此代码思路适用于所有的单片机。 说明3:学会以后,下面的代码可能会跟你一辈子! 说明4:这一系列文章是为大幅度裁剪本人博客文章!使博客文章更有条理。便于推其它教程! 拷贝这两个文件到自己的工程 ..

杨奉武的博客 1280

STM32CubeMX 6.4.0 + STM32F407ZGT6 实战:基于YT8512C PHY的lwIP以太网配置与调试

本文详细介绍了使用STM32CubeMX 6.4.0为STM32F407ZGT6微控制器配置YT8512C PHY芯片,并成功移植lwIP以太网协议栈的实战过程。文章从硬件差异分析入手,逐步讲解时钟配置、ETH外设设置、PHY寄存器适配以及lwIP协议栈剪裁等关键步骤,旨在帮助开发者解决非标准PHY芯片的联网难题,最终实现网络连通与Ping测试。

n8m7b6v5c4的博客 593

usaco training 4.1.2 Fence Rails 题解

强大的搜索剪枝!

阿蒋的专栏 2126

嵌入式状态机编程-QP状态机框架与常见状态机方法

状态机基本术语 现态:是指当前所处的状态。 条件:又称为“事件”,当一个条件被满足,将会触发一个动作,或者执行一次状态的迁移。 动作:条件满足后执行的动作。动作执行完毕后,可以迁移到新的状态,也可以仍旧保持原状态。动作不是必需的,当条件满足后,也可以不执行任何动作,直接迁移到新状态。 次态:条件满足后要迁往的新状态。“次态”是相对于“现态”而言的,“次态”一旦被激活,就转变成新的“现态”了。 传统有限状态机Fsm实现方法 如图,是一个定时计数器,计数器存在两种状态,一种为设置状态,一种为计时状态 设

qq_36969440的博客 9663

USACO 6.3 Fence Rails(一道纯剪枝应用)

Fence RailsBurch, Kolstad, and Schrijvers Farmer John is trying to erect a fence around part of his field. He has decided on the shape of the fence and has even already installed the posts, but ...

weixin_30291791的博客 208

树莓派5安装ROS1避坑指南:从系统配置到cmake报错全解决

本文详细介绍了在树莓派5上安装ROS1的完整流程,包括系统配置、环境变量设置、cmake报错解决等关键步骤。针对树莓派5的ARM架构特性,提供了从基础安装到高级调试的系统级解决方案,帮助开发者高效部署ROS1并避免常见编译陷阱。特别针对cmake报错问题,给出了深度解析和实用修复方法。

spark7igniter的博客 233

OmniParser V2 和 OmniTool 让 AI 来控制 Windows 设备

OmniParser V2 和 OmniTool 是由微软开发的一套工具,通过屏幕解析技术让 AI 能够理解和控制 Windows 设备。OmniParser V2 是一款数据解析工具,可以解读屏幕内容,并将内容传递给大模型OmniTool 则是一个运行 Windows Agent 的工具,提供 Windows 界面给 AI 操作。

简简单单Onlinezuozuo 2731

USACO Section 4.1 Fence Rails

题意: n个木头  m个木块  问: 任意的切木头  最终能得到多少个

House 860

multisim14.3无法访问数据库...如何解决?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值 。

**My Coding Family** 4453

USACO SECTION 4.1 Fence Rails

Fence Rails Burch, Kolstad, and Schrijvers Farmer John is trying to erect a fence around part of his field. He has decided on the shape of the fence and has even already installed the posts, but he

572

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

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

USACO Section 4.1 Fence Rails(DFSID)

Fence RailsBurch, Kolstad, and Schrijvers Farmer John is trying to erect a fence around part of his field. He has decided on the shape of the fence and has even already installed the posts, but ...

angtongyou1893的博客 322

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

USACO Section 4.1 Fence Rails - 用DFSID解多维背包..

这题自己想了两天~~~各种超时...还是只能去拜读好些多大牛的文章..才搞定这题..这题真的很好很典型很经典阿..用到的主体思想是DFSID..为辅的是二分答案~~    所谓DFSID既是迭代加深搜索...名字挺玄乎~~实质上就是先确定一个搜索的层数..然后用DFS搜完整棵树..如果没找到解..那么层数再放深一些..再次DFS搜整棵树..直道搜出解为止..很类似BFS了..但是是用DFS来实现

zzyzzy12 1208

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

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

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

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的专栏 1922

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

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
上一篇: 简单的SQL语句(不定期更新)
下一篇: codeforce 66E - Petya and Post(dp+减少冗余)
剑不飞
博客等级 码龄15年 86粉丝 505原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值