按多个属性排序

时间:2018-10-23 03:15:32

标签: c++ arrays sorting

我的任务是

1)按已解决任务的数量降序排列

2)当已解决的任务数量相等时–惩罚时间按升序排列

3)当已解决任务的数量和惩罚时间相等时–按团队的升序排列。

输入文件将如下所示:

第一行包含自然数n(1≤n≤105)–参加比赛的团队数量。

接下来的n行包含两个数字S –第i个团队的已完成任务的数量(0≤S≤100)和惩罚时间T(1≤T≤1000000)。

示例:

  

6

     

3 50

     

5 720

     

1 7

     

0 0

     

8500

     

8500

因此输出文件将是:

  

5 6 2 1 3 4

#include <iostream> 
using namespace std;

void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void printArray(int A[],int B[], int size)
{
    int i,xx;
    for (i = size-1; i >= 0; i--) {
        for (int x = 0; x < size; x++) {
            if (A[i] == B[x]) {
                cout << x+1 << " ";
                //break;
            }
        }

    }


}
int main()
{

    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);

    int qarray, largest;

    cin >> qarray;
    int *task = new int[qarray];
    int *newtask = new int[qarray];
    int *time = new int[qarray];
    for (int i = 0; i < qarray; i++)
    {
        cin >> task[i];
        cin >> time[i];
    }

    for (int i = 0; i <= qarray - 1; i++) {
        newtask[i] = task[i];
    }

    int i, j;
    for (i = 0; i < qarray - 1; i++) {

    // Last i elements are already in place    
        for (j = 0; j < qarray - i - 1; j++) {
            if (task[j] > task[j + 1]) {
            swap(&task[j], &task[j + 1]);
        }
        }

}

    printArray(task, newtask,qarray);


    return 0;

}

简而言之,我一团糟

1 个答案:

答案 0 :(得分:0)

标准库解决方案(您可以使用自己的sort函数替换std :: sort):

#include <iostream>
#include <vector>
#include <algorithm>


struct Team
{
   std::uint32_t number;
   std::uint32_t quantity;
   std::uint32_t penalty;

   bool operator < (const Team& other) const
   {
       bool isEqQuantity = quantity == other.quantity;
       bool isEqPenalty  = penalty == other.penalty;

       return quantity > other.quantity 
           || (isEqQuantity && penalty < other.penalty)
           || (isEqQuantity && isEqPenalty && number < other.number);
   }
};


int main()
{
    std::vector<Team> teams;

    //Read teams from file
    //....

    //Or use other sort
    std::sort(teams.begin(), teams.end(), [](const Team& t1, const Team& t2)
    {
        return t1 < t2;
    });

    for (auto& t : teams)
    {
        std::cout << t.number << " ";
    }

    return 0;
}