2582. When I sort…

Hairaa
#include <iostream>
#include <algorithm>
using namespace std;

struct A
{
    int num;
    int index;
    bool tag = 0;//用来保证严格按照字典序输出
}a[10001];

bool cmp(A a, A b)
{
    return a.num < b.num;
}

int main()
{
    int T, m, b[10001];
    cin >> T;
    while (T--)
    {
        cin >> m;
        for (int i = 0;i < m;i++) 
        {
            cin >> a[i].num;
            b[i] = a[i].num;
            a[i].tag = 0;
        }
        sort(a, a + m, cmp);
        for (int i = 0;i < m;i++) { a[i].index = i; }
        for (int i = 0;i < m;i++)
        {
            for (int j = 0;j < m;j++)
            {
                if (b[i]== a[j].num&&a[j].tag==0) { a[j].tag = 1;cout << a[j].index << " ";break; }
            }
        }
        cout << endl;
    }
}
LzQuarter

排序时记录原下标即可

#include<iostream>
#include<algorithm>
using namespace std;
typedef struct _{
    int val;
    int pos;
}node;

int sortFun(node a, node b){
    if(a.val != b.val){
        return a.val < b.val;
    }
    else{
        // important
        return a.pos < b.pos;
    }
}

int main(){
    int p[10000];
    int N;
    cin >> N;
    while(N--){
        int M;
        cin >> M;

        node A[10000];
        for(int m = 0; m < M; m++){
            cin >> A[m].val;
            A[m].pos = m;
        }

        sort(A, A + M, sortFun);

        for(int m = 0; m < M; m++){
            int frm = A[m].pos;
            int to = m;
            p[frm] = to;
        }

        for(int m = 0; m < M; m++){
            if(m){
                cout << " ";
            }
            cout << p[m];
        }

        cout << endl;
    }
    return 0;
}
你当前正在回复 博客/题目
存在问题!