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; }
出处:http://www.cnblogs.com/lightsong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。