UVa 10487 - Closest Sums

计组实验4 控制冒险与分支预测 目录前言实验内容背景知识分支预测技术⭐阻塞周期计算方法不开启 BTB开启 BTBpart 1 矩阵乘法与优化未开启 BTB 的分析开启 BTB 的分析part 2 设计代码使 BTB 无效part 3 循环展开优化矩阵乘法未开启 BTB开启 BTB结束语结论 前言 上一篇博客:计组实验3 mips冒险之流水线冒险 摸了半个月了。。。咕咕咕 今天来写计组实验 4 这个实验非常简单,就是有点难。 这个实验比较容易算错,或者是被模拟器出人意料的结果搞的神神叨叨的,所以今天来记录并且详细分析该实验。 注:请务必阅 阅读详情

算是简单题,先算出来所有俩数的和存起来,在用二分查找找出最接近的值 ~

代码如下:

#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>

using namespace std;

int cmp(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
}
int a[1000 + 2], b[25 + 2], s[1000000 + 10];
int main()
{
#ifdef test
    freopen("in.txt", "r", stdin);
#endif
    int  m, n, num = 0;
    while(cin >> m && m)
    {
        for(int i = 0; i < m; i++)
            cin >> a[i];
        qsort(a, m, sizeof(a[0]), cmp);
        cin >> n;
        for(int i = 0; i < n; i++)
            cin >> b[i];
        cout <<"Case "<<++num<<":"<<endl;
        int sum = -1;
        for(int i = 0; i < m; i++)
            for(int j = i + 1; j < m; j++)
                s[++sum] = a[i] + a[j];
        qsort(s, sum + 1, sizeof(s[0]), cmp);
        for(int i = 0; i < n; i++)
        {
            int max = sum + 1, min = 0, flag = 0;
            while(max > min)
            {
                int mid = (max + min) / 2;
                if(b[i] == s[mid])
                {
                    flag = 1;
                    break;
                }
                else if(b[i] > s[mid])
                    min = mid + 1;
                else
                    max = mid;
            }
            if(flag)
                cout<<"Closest sum to "<<b[i]<<" is "<<b[i]<<"."<<endl;
            else
            {
                int t = s[min];
                if(min + 1 <= sum)
                    t = abs(s[min + 1] - b[i]) > abs(s[max]- b[i]) ? s[max] : s[min + 1];
                if(min - 1 > -1)
                    t = abs(s[min - 1] - b[i]) > abs(t - b[i]) ? t : s[min - 1];
                cout<<"Closest sum to "<<b[i]<<" is "<<t<<"."<<endl;
            }
        }
    }
    return 0;
}

2026华为OD机试(JavaScript)真题【E卷+A卷+B卷+C卷+D卷】目录+在线OJ 华为OD机试真题题库【E卷+A卷+B卷+C卷+D卷】目录,JavaScript实现。 阅读详情

相关推荐

基于奥比中光Orbbec Astra Pro与ROS实现实时3D环境建模:orb_slam2实战指南

本文提供了一份详细的实战指南,介绍如何使用奥比中光Orbbec Astra Pro深度摄像头与ROS系统,部署并运行ORB-SLAM2算法,实现实时3D环境建模与定位。内容涵盖从驱动安装、环境配置、算法编译到摄像头标定与性能调优的全流程,旨在帮助开发者快速搭建一套高性价比的视觉SLAM系统。

weixin_29054399的博客 336

UVA10487二分查找上界和下界

注意二分查找,查找上界的时候,返回的是等于查找的数的第一个位置,如果没有,返回前面比他大那个数的位置, 如果全部数都比他大,则返回全部数的下一个坐标,注意这里。 查找下界的时候,返回的是小于等于b的最后一个元素,如果全部都小于,返回第一个数前面那个数的坐标。 #include #include #include #include #include #include #include #inc

ONE_PIECE的专栏 553

uva10487

题目大意: 给出的数中,任意两个数相加,找出最接近query的数。思路: 把任意两个数加起来之后,排序完之后,用lower_bound找到插入query的位置,然后找到它左右两边的与它最近的数。输出就可以了。代码:#include <iostream> #include <cstdio> using namespace std; #include <cstring> #include <algo

不努力只能看别人脸色。 441

Blender建模:对于模型布线的一些思考

Blender布线中一些问题的总结和思考,主要讲述原理和解决方法。

baidu_38797690的博客 1827

基于WebGL架构的3D可视化平台—平面图导航(一)

前言 利用CampusBuilder来搭建自己的虚拟世界过程有这样一个问题:如何快速聚焦到虚拟场景的某一位置。当然我们可以创建几个按钮对应查找我们需要去的位置(参照物)并聚焦,但是按钮并不是很炫酷也不能很好的反馈给我们一些信息。接下来我们就用平面导航图来解决这一问题。 第一步:使用CampusBuilder搭建模拟场景,CampusBuilder操作简单,分分钟就可以上手。 ...

nioooom的博客 4164

UVA10487

题意:给出一组数组a,再给出另一组数组b,求数组b中的各个元素,离数组a中随意两个元素相加的和最接近的那个元素 思路:先将数组a中出现的两者和求出,然后用二分查找 #include #include #include #include #include #define N 5001500 using namespace std; int a[N], c[N];

懒人一枚。 866

Ubuntu运行vmware时报错Vmware Unable to install all modules!Use shipped Linux kernel AIO access library解决。

Ubuntu运行vmware时报错Vmware Unable to install all modules! vmware --version 提示下面内容: [AppLoader] Use shipped Linux kernel AIO access library. An up-to-date "libaio" or "libaio1" package from your system is preferred. VMware Workstation 16.1.2 build-17966106

wto882dim的博客 2849

UVA 10487

不错的二分入门题,WA了一次,无意间写成了求比询问数小的最大数的位置了,完事后发现时

jinjiahao5299的专栏 530

Surface Go 2 变身 Linux 开发本:保姆级 Ubuntu 20.04 双系统安装与驱动配置全攻略

本文详细介绍了如何将 Surface Go 2 变身为高效的 Linux 开发本,涵盖 Ubuntu 20.04 双系统安装、专用内核配置、驱动优化等全流程。通过 linux-surface 内核安装和硬件驱动优化,确保 Surface Go 2 的触控、笔输入、摄像头等功能完美运行,适合开发者打造便携生产力工具。

weixin_30596165的博客 616

粒子群算法实战:用Matlab解决旅行商问题(TSP)的完整代码解析

本文提供了使用粒子群算法解决旅行商问题的完整Matlab实战指南。通过将连续空间的粒子群算法进行离散化改造,采用基于交换序的策略来更新粒子位置与速度,并给出了从问题定义、数据结构设计、核心函数实现到主迭代循环的详细代码解析。文章还探讨了参数调优、性能优化及处理复杂TSP变体的进阶思路,为物流规划、路径优化等领域的工程应用提供了可直接复用的解决方案。

m2n3o4p5的博客 350

UVA 10487 Closest Sums(二分)

UVA 10487 Closest Sums Given is a set of integers and then a sequence of queries. A query gives you a number and asks to find a sum of two distinct numbers from the set, which is closest to

总有那么一群人喜欢盯着我的博客看,估计这是他们见过最长的博客名,我必须得告诉他们博客名最长可以写多长 567

UVA10487 Closest Sums【暴力+二分】

Given is a set of integers and then a sequence of queries. A query gives you a number and asks to find a sum of two distinct numbers from the set, which is closest to the query number. Input Input con...

海岛Blog 534

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

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

UVa 10487 - Closest Sums

Problem D Closest Sums Input: standard input Output: standard output Time Limit: 3 seconds   Given is a set of integers and then a sequence of queries. A query gives you a number and asks to fin

ACM2272902662的专栏 943

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

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

UVA 10487 Closest Sums

UVA_10487     将所有和算出来之后进行排序,再二分查找即可。 #include&lt;stdio.h&gt;#include&lt;string.h&gt;#include&lt;stdlib.h&gt;int cmp(const void *_p,const void *_q){ int *p=(int *)_p; int *q=(int *)_q; ret...

weixin_34040079的博客 114

lwip-2.0.3

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

uva 10487 Closest Sums

简单题目,先将所有元素从小到大排序,找到第一个比待寻找的和大的数字,从这个数字到第一个数字间的数字进行两两组合,枚举可能的和,找到最接近的一个就行了,在寻找第一个比待寻找的和大的数字的时候,可以二分来找,效率还可以提高一点点,不过重点不在这里,顺序查找也可以ac,注意适当进行剪枝。 #include #include using namespace std; int arr[1005];

皓首不倦 不负少年 660

UVA - 10487 - Closest Sums (二分求解)

传送:UVA - 10487 10487 Closest Sums Given is a set of integers and then a sequence of queries. A query gives you a number and asks to find a sum of two distinct numbers from the set, which is

Never say never 707

UVa-10487-Closest Sums

AOAPC I: Beginning Algorithm Contests (Rujia Liu)::Volume 4. Algorithm Design // 10487 - Closest Sums #include <iostream> #include <cstdlib> using namespace std; int ma...

abu47643的博客 156

uva 10487 - Closest Sums

Problem D Closest Sums Input: standard input Output: standard output Time Limit: 3 seconds Given is a set of integers and then a sequence of queries. A query gives you a number and asks to find

uva code 2149

uva 10487 Closest Sums

Closest Sums Input: standard input Output: standard output Time Limit: 3 seconds   Given is a set of integers and then a sequence of queries. A query gives you a number and asks to find a sum of

risker_2013的专栏 676

UVA - 10487 Closest Sums

#include #include #include using namespace std; int main() { int n, m, cnt = 0, arr[1005]; while (scanf("%d", &n), n) { printf("Case %d:\n", ++cnt); for (int i = 0; i < n; i++) scanf("%d"

Bingo 1731

uva 10487 - Closest Sums

点击打开链接 题目意思: 先给定n个数字,现在要求算出这n个数字的两两之和保存到sum数组,然后在给定m个数,要求找到和每一个数最接近的sum[i],输出 解题思路: 1:二分查找 2:由于数据很大,所以直接硬搞肯定是不行的,那么我们选择二分查找。首先先求出这些元素组成的所有的和,保存到数组sum里面,然后对sum排序,最后进行二分查找,找到距离目标最近的sum[i]输出即可 ...

我是传奇 208
上一篇: ZOJ 3203 Light Bulb
下一篇: ZOJ 3501 Roman Order
GooMaple
博客等级 码龄14年 79粉丝 197原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值