点分治模板、例题整理

【学习笔记】点分治 整理的算法模板合集: ACM模板 点我看算法全家桶系列!!! 实际上是一个全新的精炼模板整合计划 点分治 点分治适合处理大规模的树上路径信息问题。 点分治,即基于树上结点的分治,显然我们在处理路径信息问题的时候,普通结点到根节点的路径信息比较容易计算和维护,因此我们考虑将一棵树分治拆分成若干棵子树,将问题从任意结点到结点间的问题转变为结点与根节点之间的问题递归分治解决。 例如在处理树上任意两点间的最短路径距离问题,显然有两种情况 经过根节点的路径。 不经过根节点的路径。 对于第一种路径,有 dis 阅读详情

1.Acwing252. 树

传送门

1.题意

求一个树中距离小于等于k的点对的个数。

1 ≤ N ≤ 1 0 4 1≤N≤10^4 1≤N≤104

2.分析

点分治算法:

树的重心

树的重心是指:删除该点后,最大子树(的点数)最小的点。
关于重心的结论:删除重心之后,最大子树的点数小于等于总点数/2。

于是:我们可以将一个树上问题删去重心点之后分解成若干个子树内部的问题和子树之间的问题。这样可以保证是log级的时间复杂度。(边分治则不行,会被菊花图卡成n)

关于本题

我们先将重心找出来,然后路径小于等于k的点对可以分成如下:
1.两点在同一颗子树中。(递归到下一层求解)
2.两点在不同子树中。(在本层求解)
3.有一点是该层的重心。(在本层求解)

现在考虑如何处理本层的信息:
1.预处理出该联通块所有点到该层重心的距离。
2.先将同一颗子树中到重心距离和小于等于k的点对个数统计出来,删去(容斥原理)。
3.遍历所有点对,统计答案(无论是不是在同一颗子树中)。
4.统计 有一点是该层的重心 的个数。

具体实现

1.递归出口
定义一个bool st[]数组,记录哪些点还没被作为重心删掉,如果递归到一个st[u]==false的点,则return。

if (st[u]) return;

2.计算该连通块中到重心的距离(每次都要重新计算)
无需建立点于距离的对应关系,dist直接保存在q数组中就行了。

void get_dist(int u, int fa, int dist, int& qt)
{
    if (st[u]) return;
    q[qt ++ ] = dist;
    for (int i = h[u]; ~i; i = ne[i])
        if (e[i] != fa)
            get_dist(e[i], u, dist + w[i], qt);
}

3.求该连通块的重心
递归进该层时,重新计算该层的重心,并返回该层的点数
注意:这里求出的重心并不一定是真正的重心,只是满足删除该点之后,最大子树的点数小于等于总点数/2。

int get_wc(int u, int fa, int tot, int &wc) //求重心,返回子树大小
{
    if (st[u])
        return 0;
    int sum = 1, ms = 0;
    for (int i = h[u]; ~i; i = ne[i])
    {
        int j = e[i];
        if (j == fa)
            continue;
        int t = get_wc(j, u, tot, wc);
        ms = max(ms, t); //ms是最大子树size
        sum += t;
    }
    ms = max(ms, tot - sum);
    if (ms <= tot / 2)
        wc = u;
    return sum;
}

4.通过已经储存下来的dist数组,统计答案

int get(int a[], int len) //统计答案,和小于等于k的点对个数
{
    sort(a, a + len);
    int res = 0;
    for (int i = len - 1, j = -1; i >= 0; i--)
    {
        while (j + 1 < i && a[j + 1] + a[i] <= k)
            j++;
        j = min(j, i - 1);
        res += j + 1;
    }
    return res;
}

具体代码

(对着y总的代码码了一遍)

#include <bits/stdc++.h>

using namespace std;
//-----pre_def----
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
#define fir(i, a, b) for (int i = (a); i <= (b); i++)
#define rif(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
#define init_h memset(h, -1, sizeof h), idx = 0;
#define lowbit(x) x &(-x)

//---------------
//点分支:在树上分支,每次找到的点是当前子树重心
//问题:一颗树中长度小于等于k的路径条数
const int N = 1e4 + 10;
int n, k;
int h[N], e[N << 1], w[N << 1], ne[N << 1], idx;
bool st[N];
int q[N], p[N];
void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx++;
}
int get_size(int u, int fa) //返回该子树的大小
{
    if (st[u])
        return 0;
    int res = 1;
    for (int i = h[u]; ~i; i = ne[i])
    {
        if (e[i] != fa)
            res += get_size(e[i], u);
    }
    return res;
}
void get_dist(int u, int fa, int dist, int &qt) //重新计算每个点到root的dist 存在q数组中
{
    if (st[u])
        return;
    q[qt++] = dist;
    for (int i = h[u]; ~i; i = ne[i])
        if (e[i] != fa)
            get_dist(e[i], u, dist + w[i], qt);
}
int get_wc(int u, int fa, int tot, int &wc) //求重心,返回子树大小
{
    if (st[u])
        return 0;
    int sum = 1, ms = 0;
    for (int i = h[u]; ~i; i = ne[i])
    {
        int j = e[i];
        if (j == fa)
            continue;
        int t = get_wc(j, u, tot, wc);
        ms = max(ms, t); //ms是最大子树size
        sum += t;
    }
    ms = max(ms, tot - sum);
    if (ms <= tot / 2)
        wc = u;
    return sum;
}
int get(int a[], int kk) //统计答案
{
    sort(a, a + kk);
    int res = 0;
    for (int i = kk - 1, j = -1; i >= 0; i--)
    {
        while (j + 1 < i && a[j + 1] + a[i] <= k)
            j++;
        j = min(j, i - 1);
        res += j + 1;
    }
    return res;
}
int calc(int u)
{
    if (st[u])
        return 0;                      //已经作为重心被删去了
    get_wc(u, -1, get_size(u, -1), u); //找到重心,此时u就是重心
    //求解该层中两点不在一颗子树中的情况
    st[u] = true;
    int res = 0;
    int pt = 0;
    for (int i = h[u]; ~i; i = ne[i])
    {
        int j = e[i], qt = 0;
        get_dist(j, -1, w[i], qt);      //求出该子树每个点到重心的距离
        res -= get(q, qt);              //?
        for (int kk = 0; kk < qt; kk++) //统计有一个点是重心的情况
        {
            if (q[kk] <= k)
                res++;
            p[pt++] = q[kk];
        }
    }
    res += get(p, pt);

    for (int i = h[u]; ~i; i = ne[i])
        res += calc(e[i]);
    return res;
}

void init()
{
    init_h;
    memset(st, 0, sizeof st);
}
int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    int StartTime = clock();
#endif
    while (scanf("%d%d", &n, &k), n || k)
    {
        init();
        for (int i = 0; i < n - 1; i++)
        {
            int a, b, c;
            scanf("%d%d%d", &a, &b, &c);
            add(a, b, c), add(b, a, c);
        }
        printf("%d\n", calc(0));
    }
#ifndef ONLINE_JUDGE
    printf("Run_Time = %d ms\n", clock() - StartTime);
#endif
    return 0;
}

2.Acwing. 权值

传送门

题意

求长度等于k的路径中,点数最少的点数。

分析

树上的统计答案问题,而且可以将大问题拆分成子问题。
可以用点分治做。

代码

#include <bits/stdc++.h>

using namespace std;
//-----pre_def----
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
#define fir(i, a, b) for (int i = (a); i <= (b); i++)
#define rif(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
#define init_h memset(h, -1, sizeof h), idx = 0;
#define lowbit(x) x &(-x)

//---------------
//距离等于k的点对:
//1.两点不在同一颗子树
//2.两点在同一颗子树
//3.一点是重心

const int N = 2e5 + 10;
int n, k;
int h[N], e[N << 1], w[N << 1], ne[N << 1], idx;
int f[1000010]; //f用于记录答案,类似dp。f[i]表示距离为i的点数,初始化成inf,可以转移
int ans = INF;
bool st[N];
PII q[N], p[N]; //大小数组模板?
void add(int a, int b, int c)
{
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx++;
}

int get_size(int u, int fa) //仅需要返回连通块点数就行了
{
    if (st[u])
        return 0;
    int res = 1;
    for (int i = h[u]; ~i; i = ne[i])
    {
        int t = e[i];
        if (t == fa)
            continue;
        res += get_size(t, u);
    }
    return res;
}

int get_wc(int u, int fa, int tot, int &wc) //得到重心点,并返回子树大小
{
    if (st[u])
        return 0;
    int sum = 1, ms = 0;
    for (int i = h[u]; ~i; i = ne[i])
    {
        int t = e[i];
        if (t == fa)
            continue;
        int tt = get_wc(t, u, tot, wc);
        sum += tt;
        ms = max(ms, tt);
    }
    ms = max(ms, tot - sum);
    if (ms <= tot / 2)
        wc = u;
    return sum;
}

void get_dist(int u, int fa, int dist, int bian, int &top)
{
    if (st[u] || dist > k)
        return;
    q[top++] = {dist, bian};
    for (int i = h[u]; ~i; i = ne[i])
    {
        int t = e[i];
        if (t == fa)
            continue;
        get_dist(t, u, dist + w[i], bian + 1, top);
    }
}

void calc(int u)
{
    if (st[u])
        return;
    get_wc(u, -1, get_size(u, -1), u); //找重心
    st[u] = true;
    //处理该层不同子树之间的答案信息
    int pt = 0;
    for (int i = h[u]; ~i; i = ne[i])
    {
        int t = e[i], qt = 0;
        get_dist(t, u, w[i], 1, qt); //对于该点所对应的子树,先在q数组中存储下
        fir(j, 0, qt - 1)
        {
            auto &tt = q[j];
            // 计算一个点是重心的答案
            if (tt.first == k)
                ans = min(ans, tt.second);
            //计算两点在不同子树之间的答案
            ans = min(ans, f[k - tt.first] + tt.second);
            p[pt++] = tt;
        }
        fir(j, 0, qt - 1) //利用q数组更新f数组,为下一颗子树做准备
        {
            auto &tt = q[j];
            f[tt.first] = min(f[tt.first], tt.second);
        }
    }
    // 利用大p数组,将f数组还原成全是inf的初始化状态(memset会超时)
    fir(i, 0, pt - 1)
    {
        f[p[i].first] = INF;
    }
    //处理子树内的答案信息
    for (int i = h[u]; ~i; i = ne[i])
    {
        calc(e[i]);
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    int StartTime = clock();
#endif
    init_h;
    scanf("%d%d", &n, &k);
    fir(i, 1, n - 1)
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
        add(b, a, c);
    }
    memset(f, 0x3f, sizeof f);
    calc(0);
    if (ans == INF)
        ans = -1;
    printf("%d\n", ans);
#ifndef ONLINE_JUDGE
    printf("Run_Time = %d ms\n", clock() - StartTime);
#endif
    return 0;
}

小结:
点分治用于处理树上答案,1.需要统计的答案的问题。2.可以转换成子问题的问题。
点分治给人感觉并不是一个特别优秀的算法。
每一层中,都要重新预处理出相关信息,处理答案在不同子树中的情况&&答案压在该层重心的情况。
但是因为重心的性质:整体的时间复杂度是log级的,递归函数熟练之后,写起来码量也不大。

ACM模板(个人代码集整理)(博客停止更新,内附github链接,会在github继续更新) 为方便区域赛打印pdf模板,所有代码已经搬家到了github中。 目录: SAM(*) SA(*) PAM(*) 树链剖分(*) 01Trie(*) ACAM(*) KMP(*) LCA(*) 主席树(*) 点分治(*) kd-Tree(*) 斜率优化DP 最大流Dicnic(*) 最小费用最大流(SPFA)(*) 线段树(*) dfs靠谱找环 靠谱找凸包(*)... 阅读详情

相关推荐

OI模板大全(普及~省选NOI)

hhh刚从某位大佬的洛谷首页偷到了一个好玩的东西 自己对照了一下原来我还有这么多东西没有学呜呜呜我好菜

繁凡さん的博客 2569

【点分治练习题·不虚就是要AK】点分治

【点分治练习题·不虚就是要AK】点分治 不虚就是要AK(czyak.c/.cpp/.pas) 2s 128M by zhb czy很火。因为又有人说他虚了。为了证明他不虚,他决定要在这次比赛AK。 现在他正在和别人玩一个游戏:在一棵树上随机取两个点,如果这两个点的距离是4的倍数,那么算czy赢,否则对方赢。现在czy想知道他能获胜的概率。 ...

qq_25768269的博客 248

华为CNA VRM搭建(使用vmware worfstartion搭建)

华为CNA和VRM在 vmware workstation安装使用

weixin_70595351的博客 1824

点分治 & 点分树 学习笔记

至此,我们已经了解了这道题中的点分治做法,可以归纳成下面几步:找重心,作为根;树形 dp+ 双指针求解每个询问;递归求解每个子树。而点分治的大多数问题,只是把第222步改一改,总体思路都是一样的。

RabbieWjy的博客 457

【Excel VBA 编程】表格内自动生成进度条

在表格中生成进度条,进度条需要自适应单元格的宽度,根据不同进度区间变换颜色,并且按照进度数据大小显示其长短

wei1019的专栏 1527

15、人工智能社会学:关系视角下的机器相遇

本文探讨了将人工智能视为社会主体的可能性,提出了一种关系视角下的人工智能社会学。通过结合卢西亚娜·帕里西、艾伦·图灵和乔治·赫伯特·米德的理论,强调不确定性在人工智能运行中的核心地位,并分析了人工智能如何通过与社会环境的互动催生新奇性,从而拓展社会学的研究范畴。文章还讨论了人工智能对社会结构和社会互动的影响,以及其作为社会主体所带来的理论和实践意义,为未来人工智能社会学的发展提供了方向。

pea55的博客 75

点分治模板+例题

1.找到树的重心,更新以重心为根节点的子树大小。 2.分治,从重心开始,dfs找每个点到根节点的距离,看是否存在题意路径。 3.把根节点删去,重复1 2 步骤 例题: 1.P3806 【模板】点分治1链接 给定一棵有n个点的树 询问树上距离为k的点对是否存在。 #include<iostream> #include<cstdio> #include<queue>...

weixin_43819578的博客 283

手把手教你学Simulink--控制策略与算法的DC-DC变换器领域仿真领域建模实例:基于Simulink实现一个双闭环控制Buck变换器的仿真建模

目录主要步骤1. 前期准备2. 构建Buck变换器模型3. 定义双闭环控制器4. 设置参考电压和反馈回路5. 实现双闭环控制器逻辑6. 仿真参数设置7. 运行仿真与结果分析示例整合代码片段1. Simulink模型2. 双闭环控制器参数调节3. 仿真结果分析总结双闭环控制是一种常见的控制策略,广泛应用于电力电子系统(如DC-DC变换器)中。它通过内外两个环路的协同工作,分别控制系统的动态性能和稳态性能。对于Buck变换器,通常采用电流内环和电压外环的双闭环控制结构。以下是一个手把手教程,帮助你基于Simul

MHD0815的博客 332

点分治学习/模板(5道例题)

感谢b站up大佬:不分解的AgOH。 点分治用于树上的大规模路径操作、统计。它的灵活性高,适用范围广。很多树形dp也可以用点分治搞。其实,树分治中,还有一个边分治,不过没有点分治常用。 基本步骤: 第一步 找树的重心。我们重心为根节点,然后按题目的不同情况统计树各个点到根节点的路径信息。 第二步 递归至每一个子树,重复第一步,直到分割至叶子节点。 非常简洁。 下面看一看具体的实现: 找重心函数: ...

平凡人Kalzn的博客 846

【Autoware】Autoware.universe安装过程与问题记录

Autoware.universe安装过程与问题记录

DevFrank的博客 2748

VMware系列:此平台不支持虚拟化 Intel-VT-x/EPT 或 AMD-V/RVI

VMware系列:此平台不支持虚拟化 Intel-VT-x/EPT 或 AMD-V/RVI

weixin_54626591的博客 1万+

数据结构——点分治(树分治)总结

点分治总结

x052xiao的博客 507

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

专题·点分治【including 点分治,洛谷P3806·【模板】点分治1及例题

初见安~几百年没写专题了来整理一波:) 点分治 1.概念 众所周知,分治是一种算法思想层面的东西【大雾。那么点分治是什么呢——通过静态的运算统计出树上一定条件下路径的一种算法。诸如在树上求路径长度<=K的路径数量之类的。 那么对于分治,这一思想上的体现在于——因为路径有直链和折链,假设我们要求的是路径长度不超过K的路径数量,并且在以1为我们统计的路径的LCA的状况下,我们是不是可以通...

樱狸✨愿携清风归来处 362

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

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

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

点分治 模板 1

自己整理模板,仅作模板保存使用 树上点分治模板代码 1 该模板有一巨大bug 在统计路径长度为单边长度时,会出错 #include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; #define inf 999...

我不想打铁 149

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

点分治 模板 2

自己整理模板,仅作模板保存使用 #include <iostream> #include<algorithm> #include<string.h> #include <stdio.h> using namespace std; const int inf=0x3f3f3f3f; const int maxn=2*1e5+10; int first...

我不想打铁 143

点分治 模板题

就明白了个模板题,先放个模板。 多做一些题后在来整理下。 #pragma GCC optimize(3,"Ofast","inline") //G++ #include<bits/stdc++.h> #define mem(a,x) memset(a,x,sizeof(a)) #define debug(x) cout << #x << ": " <...

1262934560的博客 183

BZOJ 2152 「国家集训队」聪聪可可(点分治)【BZOJ计划】

【BZOJ修复计划 #18】BZOJ 2152 聪聪可可 【国家集训队2011】

繁凡さん的博客 698

SDOI2019 省选前模板整理

目录 计算几何✔ DP 斜率优化✔ 四边形不等式✔ 轮廓线DP✘ 各种分治 CDQ分治✔ 点分治✔ 整体二分✔ 数据结构 线段树合并✔ ...

weixin_30642869的博客 397

Luogu P4178 Tree (点分治 + 树状数组)

整理的算法模板合集: ACM模板 点我看算法全家桶系列!!! 实际上是一个全新的精炼模板整合计划 Problem 给定一棵 nnn 个节点的树,每条边有边权,求出树上两点距离小于等于 kkk 的点对数量。 Solution 树上路径信息问题显然用点分治。 这道题统计的是树上两点距离小于等于 kkk 的点对数量,我们当然可以先算出距离等于 kkk 的点对数量,然后容斥即可。 但我不想动脑子( 我们显然可以开一个桶 bit[i] 表示距离小于等于 i 的点对的数量。 我们使用树状数组维护即可。 时间复杂度

繁凡さん的博客 540

临时模板整理

只有一些自己用起来习惯的板。其他的直接抄hdu或者红书即可 字符串 后缀数组 #include&lt;bits/stdc++.h&gt; using namespace std; #define maxn 100020 #define rep(i,l,r) for (register int i = l ; i &lt;= r ; i++) #define repd(i,r,l) for(regi...

执子之手,与子偕老 294

个人acm模板整理

acm模板自用

qq_31673493的博客 582

2019.7.17海量暑假集训Day12考试总结

对于代码和题目详见百度网盘,这只讲思路。 首先我要吐槽一下,这为何可以用点分治做,而且还有两道!都是模板,我不会啊!!!! T1,这是一道和换根DP的的模板非常的接近,只是加了以为,我们以图讲解: 对于这一张图,首先我们用一个f[i][j]表示i号点和其他点长度为j的个数,d[i][j]表示i号点这个子树里的到他距离为j的点的个数,显然,f[1][i]=d[1][i],而d数...

qq_40669010的博客 185
上一篇: CF38G Queue (区间splay)
下一篇: P5764 [CQOI2005]新年好(最短路+暴搜)
sancpp
博客等级 码龄7年 26粉丝 59原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值