Skip to content

Choose two indices i j, then swap a[i] with a[j] and b[i] with b[j] simultaneously? #2

Description

@qnhat2004

You can swap the pair $(a_i, b_i)$ with $(a_j, b_j)$ simultanously using pair(is more optimistic) and map:

pair:

vector<pair<int, int>> v;
for (int i = 0; i < n; ++i)
   v.push_back({a[i], b[i]});
sort(v.begin(), v.end()); // Sort by first element (array a[])

// show array a[]
for (auto i : v) cout << i.first << ' ';
// show array b[]
for (auto i : v) cout << i.second<< ' ';

map:

map<int, int> mp;

for (int i = 0; i < n; ++i)
   mp[a[i]] = b[i]; // Mapping the value of a[i] to b[i]

// Change order:
sort(a, a + n);

// show two array after changing order:
for (int i = 0; i < n; ++i) 
   cout << a[i] << ' '; // array A
for (int i = 0; i < n; ++i) 
   cout << mp[a[i]] << ' '; // array B after change the order with each a[i]

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions