Friday 27 May 2016

C. Prime Swaps
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):
  • choose two indexes, i and j (1 ≤ i < j ≤ n(j - i + 1) is a prime number);
  • swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments:tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable).
You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.
Input
The first line contains integer n (1 ≤ n ≤ 105). The next line contains n distinct integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n).
Output
In the first line, print integer k (0 ≤ k ≤ 5n) — the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1 ≤ i < j ≤ n(j - i + 1) is a prime).
If there are multiple answers, you can print any of them.
Examples
input
3
3 2 1
output
1
1 3
input
2
1 2
output
0
input
4
4 2 3 1
output
3
2 4
1 2
2 4





  HERE WE GO THROUGH A GREEDY STRATEGY AND ALWAYS BRING THE NUMBER TO ITS NEAREST POSITION THAT CAN BE DONE USING A VALID SWAP. IT IS ALWAYS CORRECT BECAUSE WE CAN SWAP TWO NEIGHBORING NUMBERS ALWAYS SO THIS WILL LEAD TO A SOLUTION.

            LOOK AT THE EASY CODE
#include<bits/stdc++.h>
using namespace std;
#define ll long long int 
bool pr[100010];
#define ff first
#define ss second
#define mp make_pair
#define pb push_back
vector<int> v;
int l;
void pre()
{
   for(int i=2;i<=100000;i++)
   {
      if(!pr[i])
      {
        v.pb(i);
        for(int j=2*i;j<=100000;j+=i)
        {
              pr[j]=1;
  }
  }
}
l=v.size();
}
int pos[100010];
int a[100010];
int main()
{
    pre();
     int n;
     cin>>n;
     for(int i=1;i<=n;i++)
     {
       cin>>a[i];
       pos[a[i]]=i;
 }
 vector<pair<int,int> > res;
 
 for(int i=1;i<=n;i++)
 {
        while(pos[i]!=i)
        {
          int lst=pos[i];
       
             int shiftm=abs(pos[i]-i)+1;
   vector<int> ::iterator it;
   it=upper_bound(v.begin(),v.end(),shiftm);
it--;
int val=*it;
// cout<<"value "<<val<<endl;
     int idx=pos[i]+1-val;
//      cout<<"idx "<<idx<<endl;
     res.pb(mp(pos[i],idx));
     
     pos[a[idx]]=pos[i];
     pos[i]=idx;
     
    // cout<<"sert pos of "<<i<<" as "<<pos[i]<<" and pos of "<<a[idx]<<" = "<<pos[a[idx]]<<endl;
     swap(a[idx],a[lst]);
}
 
}
int sz=res.size();
cout<<sz<<endl;
for(int i=0;i<sz;i++)
cout<<min(res[i].ff,res[i].ss)<<" "<<max(res[i].ff,res[i].ss)<<endl;
 return 0;
 }


No comments:

Post a Comment