【贪心】排队接水

问题 E: 【贪心】排队接水
时间限制: 1 Sec 内存限制: 128 MB
[提交] [状态]
题目描述
有n个人在一个水龙头前排队接水,假如每个人接水的时间为Ti,请编程找出这n个人排队的一种顺序,使得n个人的平均等待时间最小。
输入
共两行,第一行为n;第二行分别表示第1个人到第n个人每人的接水时间T1,T2,…,Tn,每个数据之间有1个空格。
输出
有两行,第一行为一种排队顺序,即1到n的一种排列;第二行为这种排列方案下的平均等待时间(输出结果精确到小数点后两位)。
样例输入 Copy
10
56 12 1 99 1000 234 33 55 99 812
样例输出 Copy
3 2 7 8 1 4 9 6 10 5
291.90

注意C++对浮点数小数点的约束方式:

#include <iomanip>
cout<<fixed<<setprecision(2)<<sum/n<<endl;
//输出sum/n 的结果小数点保留两位

我的代码:

#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
const int MAXN = 1005;
struct node{int value,xu; }a[MAXN];
 
bool cmp(const node &x, const node &y)
{
    if(x.value == y.value)
        return x.xu < y.xu;
    else
        return x.value < y.value;
}
 
int main()
{
    int n;
    cin>>n;
    for(int i=1; i<=n; i++){
        cin>>a[i].value;
        a[i].xu = i;
    }
    sort(a+1, a+1+n, cmp);
    double sum = 0;
    for(int i = 1; i<=n; i++)
    {
        cout<<a[i].xu<<' ';
        sum += (n-i)*a[i].value;
    }
    cout<<endl;
    cout<<fixed<<setprecision(2)<<sum/n<<endl;
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章