网易2016年研发工程师编程题(1)

来源:互联网 发布:零基础学sql视频教程 编辑:程序博客网 时间:2024/05/17 23:58

要求一个小时完成的2个编程题,愣是被我搞了几个小时,真是惭愧死了,无颜面对江东父老啊。。。/(ㄒoㄒ)/~~
废话少说,还是好好总结吧~

题目一 : 路灯

一条长l的笔直的街道上有n个路灯,若这条街的起点为0,终点为l,第i个路灯坐标为ai,每盏灯可以覆盖到的最远距离为d,为了照明需求,所有灯的灯光必须覆盖整条街,但是为了省电,要是这个d最小,请找到这个最小的d。
输入描述:
每组数据第一行两个整数n和l(n大于0小于等于1000,l小于等于1000000000大于0)。第二行有n个整数(均大于等于0小于等于l),为每盏灯的坐标,多个路灯可以在同一点。
输出描述:
输出答案,保留两位小数。
输入例子:
7 1515 5 3 7 9 14 0
输出例子:
2.5
这个题目,我明明是做过的,也有清晰的思路,可搞来搞去,废了一堆时间!

分析

将题目描述转换为程序设计题,该题目就是求出一个数组序列中的两个连续元素之间的最大差值。考虑首尾的特殊性,以其与相邻元素差值的2倍来比较。

源码

#include <iostream>#include <cstdlib>#include <vector>#include <algorithm>using namespace std;int main(){int n, l;while (scanf("%d %d", &n, &l) != EOF){vector<int> arr(n, 0);for (int i = 0; i < n; ++i){scanf("%d", &arr[i]);}//forsort(arr.begin(), arr.end());/*考虑边缘情况*/int maxD = 0;maxD = max((arr[0] * 2), ((l - arr[n - 1]) * 2));for (int i = 1; i < n; ++i){int tmp = arr[i] - arr[i - 1];maxD = maxD > tmp ? maxD : tmp;}//forprintf("%.2f\n", (double)maxD / 2);arr.clear();}system("pause");return 0;}

题目二: 奖学金

小v今年有n门课,每门都有考试,为了拿到奖学金,小v必须让自己的平均成绩至少为avg。每门课由平时成绩和考试成绩组成,满分为r。现在他知道每门课的平时成绩为ai ,若想让这门课的考试成绩多拿一分的话,小v要花bi 的时间复习,不复习的话当然就是0分。同时我们显然可以发现复习得再多也不会拿到超过满分的分数。为了拿到奖学金,小v至少要花多少时间复习。
输入描述:
第一行三个整数n,r,avg(n大于等于1小于等于1e5,r大于等于1小于等于1e9,avg大于等于1小于等于1e6),接下来n行,每行两个整数ai和bi,均小于等于1e6大于等于1
输出描述:
一行输出答案。
输入例子:
5 10 90 59 18 10 19 100
输出例子:
43

分析

这道题其实也不难,那我败在哪儿了呢?哎,脑子不够用啊,明明用struct封装一个抽象数据类型就能解决的问题,偏偏开始没想到,一直纠结于如何维持两个序列的一致性,排序前后都能组成正确的《成绩,时间》元素对。

源码

#include <iostream>#include <vector>#include <algorithm>struct ScoreHour{int score;int hour;ScoreHour(int s, int h) :score(s), hour(h){}};/*以时间从小到大排列*/bool cmp(const ScoreHour a, const ScoreHour b){return a.hour < b.hour;}int minTime(int n, int r, int avg, std::vector<ScoreHour> sh){/*计算当前取得的分数*/long currentScore = 0;for (int i = 0; i < n; ++i){currentScore += sh[i].score;}//for/*计算还需要的分数*/long needScore = n * avg - currentScore;if (needScore <= 0){return 0;}//if/*对数组排序,按照复习时间*/sort(sh.begin(), sh.end(), cmp);long needTime = 0, idx = 0;while (idx < n && needScore > 0){if (needScore > (r- sh[idx].score)){needScore = needScore - (r - sh[idx].score);needTime = needTime + (r - sh[idx].score) * sh[idx].hour;}//ifelse{needTime = needTime + needScore * sh[idx].hour;needScore = 0;}//else++idx;}//whilereturn needTime;}int main(){int n, r, avg;while (scanf("%d %d %d", &n, &r, &avg) != EOF){std::vector<ScoreHour> sh(n, ScoreHour(0, 0));for (int i = 0; i < n; ++i){scanf("%d %d", &(sh[i].score), &(sh[i].hour));}//forprintf("%ld\n", minTime(n, r, avg, sh));sh.clear();}//while//system("pause");return 0;}


牛客网 -- 原题链接
1 0
原创粉丝点击