Stay Hungry,Stay Foolish!

C - Sort

C - Sort

https://atcoder.jp/contests/abc350/tasks/abc350_c

 

思路

开辟一个map,

对于输入排列数组,记录每个值所在的位置 (因为后面做位置替换的时候,需要快速找到 当前位置上 值 对应位置)

 

遍历数组,如果当前位置i,存放的就是当前位置值i,则跳过,

否则,在map中查询当前位置i 存储的 位置值 j 对应的数组位置,与当前位置i的值做交换,并更新map

 

Code

https://atcoder.jp/contests/abc350/submissions/52591089

int n;

int a[200005];

int main()
{
    cin >> n;

    map<int, int> pos;

    for(int i=1; i<=n; i++){
        cin >> a[i];
        
        pos[a[i]] = i;
    }

    vector<vector<int>> cache;
    
    for(int i=1; i<=n; i++){
        if (a[i] == i){
            continue;
        }
        
        int curpos = i;
        int curval = a[i];

        int destpos = pos[i];

        a[i] = i;
        pos[i] = i;
        
        a[destpos] = curval;
        pos[curval] = destpos;
        
//        cout << i << " " << destpos << endl;
        vector<int> one;
        one.push_back(i);
        one.push_back(destpos);
        
        cache.push_back(one);
    }

    cout << cache.size() << endl;
    
    for(int i=0; i<cache.size(); i++){
        cout << cache[i][0] << " " << cache[i][1] << endl;
    }

    return 0;
}

 

posted @ 2024-04-20 23:10  lightsong  阅读(6)  评论(0编辑  收藏  举报
Life Is Short, We Need Ship To Travel