有人可以解决这个问题 [英] Can someone solve this question

查看:69
本文介绍了有人可以解决这个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入:4

输入:4 2 3 6

输出:29

说明:排序数组然后加2 + 3 = 5现在我们有5 4 6

接下来我们加5 + 4 = 9现在我们有9和6

接下来我们加9 + 6 = 15最后我们返回29作为解决方案,总和为5 + 9 + 15 = 29

我必须为此编写代码。



我尝试过:



Input:4
Input: 4 2 3 6
Output :29
Explanation:sort the array and then add 2+3=5 now we have 5 4 6
Next we add 5+4=9 now we have 9 and 6
next we add 9+6=15 and finally we return 29 as solution which is sum of 5+9+15=29
I have to write a code for the same.

What I have tried:

<pre>#include<bits/stdc++.h>
using namespace std;
int main()
{
int num;
cin>>num;
vector<int> box;
for(int i=0;i<num;i++)
{
int temp;    
cin>>temp;
box.push_back(temp);
}
sort(box.begin(),box.end());
vector<int> res;
int sum=box[0];
if(box.size()==1)
{
cout<<sum;    
}
else{
for(int i=1;i<box.size();i++)
{
sum=sum+box[i];
res[i]=sum;
}
res[0]=0;
int result=0;
for(int i=0;i<res.size();i++)
{
result+=res[i];    
}
cout<<result;
}

    
}

推荐答案

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

int main()
{
  size_t num;
  cin >> num;
  vector<int> box;

  if (num < 1) return -1;

  box.resize(num);

  for(auto & x : box)
    cin >> x;

  sort(box.begin(), box.end());

  vector<int> res;

  int sum = box[0];

  for (size_t i=1; i<num; ++i)
  {
    sum += box[i];
    res.push_back(sum);
  }

  cout << accumulate(res.begin(), res.end(), 0) << endl;
}


这篇关于有人可以解决这个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆