前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >2021阿里笔试题

2021阿里笔试题

作者头像
全栈程序员站长
发布2022-08-31 19:36:03
发布2022-08-31 19:36:03
2040
举报

大家好,又见面了,我是你们的朋友全栈君。

n个人,初始序号为a[i],当某个人的序号是某个整数的平方时,则获胜。现在发放一定数量的券,每张券可以是自己的序号加一或减一。求让一半的人获胜至少需要多少张券。

// testali.cpp : 定义控制台应用程序的入口点。 //

#include “stdafx.h” #include <math.h> #include <iostream> #include <math.h> #include <vector> #include <algorithm> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int n ; cin >> n; int *a =new int[n]; int i =0; while(i<n){ cin>>a[i++];

} int ans = 0; //第一步:遍历数组所有成员,求出每一个数据使用的最少券数,记录到原数组中,之后从小到大排序,取一半的人数

for (int i =0;i <n;i++) { double c = sqrt((double)a[i]);

int tmp = (int) c; //cout<< “c== ” <<c <</* endl; //cout<<“tmp == ” << tmp << endl;*/

if(tmp*tmp != a[i]) { //求得每一个数据的最少使用券数量 a[i]= min((tmp+1)*(tmp+1)-a[i],a[i]-tmp*tmp);

} else{ a[i]=0; } } sort(a, a+n); for(int i =0;i <n/2;i++) { ans+=a[i]; } cout<< “ans == ” << ans<< endl; cout<< endl; system(“pause”); return 0; }

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/142574.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档