版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/102454810
Recently Vasya decided to improve his pistol shooting skills. Today his coach offered him the following exercise. He placed n cans in a row on a table. Cans are numbered from left to right from 1 to n. Vasya has to knock down each can exactly once to finish the exercise. He is allowed to choose the order in which he will knock the cans down.
Vasya knows that the durability of the i-th can is
. It means that if Vasya has already knocked x cans down and is now about to start shooting the i-th one, he will need (
⋅x+1)shots to knock it down. You can assume that if Vasya starts shooting the i-th can, he will be shooting it until he knocks it down.
Your task is to choose such an order of shooting so that the number of shots required to knock each of the n given cans down exactly once is minimum possible.
The first line of the input contains one integer n (2≤n≤1000) — the number of cans.
The second line of the input contains the sequence
,
,…,
(1≤
≤1000), where aiai is the durability of the i-th can.
In the first line print the minimum number of shots required to knock each of the n given cans down exactly once.
In the second line print the sequence consisting of n distinct integers from 1 to n — the order of indices of cans that minimizes the number of shots required. If there are several answers, you can print any of them.
3 20 10 20
43 1 3 2
4 10 10 10 10
64 2 1 4 3
6 5 4 5 4 4 5
69 6 1 3 5 2 4
2 1 4
3
2 1
In the first example Vasya can start shooting from the first can. He knocks it down with the first shot because he haven't knocked any other cans down before. After that he has to shoot the third can. To knock it down he shoots 20⋅1+1=21 times. After that only second can remains. To knock it down Vasya shoots 10⋅2+1=21 times. So the total number of shots is 1+21+21=43.
In the second example the order of shooting does not matter because all cans have the same durability.
题目大意是:给定n个罐子,第i个罐子a[i]需要射击 (a[i]*x+1) 次,问击倒n个罐子最少需要射击多少次,并输出罐子的初始编号。既然要求最少射击次数,那就用贪心算法吧。我们从需要射击最多次的罐子来开始。我太懒了 不想自定义结构体,然后我就用了一个pair,其中pair的first是击倒罐子所需的射击次数,second是罐子的初始编号,根据first来进行降序排列,然后用sum累加a[i]*x+1进行输出,最后再输出罐子的初始下标second即可。
#include<bits/stdc++.h>
using namespace std;
#define Up(i,a,b) for(int i = a; i <= b; i++)
#define P pair<int,int> //first是值,second是初始下标
#define mp(x,y) make_pair(x,y)
bool cmp(P p1, P p2)
{
return p1.first > p2.first;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
vector<P> v;
int n;
cin >> n;
Up(i,1,n)
{
int _;
cin >> _;
v.push_back(mp(_,i));
}
sort(v.begin(),v.end(),cmp);
int x = 0,sum = 0,sz = v.size()-1;
Up(i,0,sz)
{
sum += v[i].first*x+1;
x++;
}
cout << sum << endl;
Up(i,0,sz)
{
cout << v[i].second << (i==sz?"\n":" ");
}
return 0;
}