Swap Permutation


Problem Statement :


You are given an array A = [1, 2, 3, ..., n]:

1.How many sequences (S1) can you get after exact k adjacent swaps on A?

2.How many sequences (S2) can you get after at most k swaps on A?

An adjacent swap can be made between two elements of the Array A, A[i] and A[i+1] or A[i] and A[i-1].
A swap otherwise can be between any two elements of the array A[i] and A[j] ∀ 1 ≤ i, j ≤ N, i ≠ j.

Input Format

First and only line contains n and k separated by space.

Constraints

1 ≤ n ≤ 2500
1 ≤ k ≤ 2500

Output Format

Output S1 % MOD and S2 % MOD in one line, where MOD = 1000000007.



Solution :



title-img


                            Solution in C :

In C++ :





/*
*/

#pragma comment(linker, "/STACK:16777216")
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>
#include <memory.h>

#define y0 sdkfaslhagaklsldk
#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash

#define eps 1e-11
//#define M_PI 3.141592653589793
#define bs 1000000007
#define bsize 256

using namespace std;

long n,k,s[2600][2600],dp[2600][2600],lwr,upr,ts;
long long ans1,ans2;

int main(){
//freopen("trade.in","r",stdin);
//freopen("trade.out","w",stdout);
//freopen("C:/input.txt","r",stdin);
//freopen("C:/output.txt","w",stdout);
ios_base::sync_with_stdio(0);
//cin.tie(0);

cin>>n>>k;
dp[0][0]=1;
for (int i=0;i<=2500;i++)
 s[0][i]=1;
 
for (int i=0;i<n;i++)
{
 for (int j=0;j<=k;j++)
 {
  upr=j;
  lwr=j-(n-i-1);
  if (lwr<0)lwr=0;
  ts=s[i][upr];
  if (lwr>0)ts-=s[i][lwr-1];
  ts+=bs;
  ts%=bs;
  dp[i+1][j]=ts;
 }   
 for (int j=0;j<=k;j++)
 {
  s[i+1][j]=dp[i+1][j];
  if (j){s[i+1][j]=(s[i+1][j-1]+s[i+1][j])%bs;}
 }
}

ans1=0;
for (int i=k;i>=0;i-=2)
{ans1=(ans1+dp[n][i])%bs;}cout<<ans1;//<<endl;

for (int i=0;i<=n;i++)
 for (int j=0;j<=k;j++)
  dp[i][j]=s[i][j]=0;


dp[0][0]=1;
for (int i=0;i<=2500;i++)
 s[0][i]=1;
 
for (int i=0;i<n;i++)
{
 for (int j=0;j<=k;j++)
 {
  lwr=n-i-1;
  
  dp[i+1][j]=dp[i][j];
  if (j)dp[i+1][j]+=(1ll*dp[i][j-1]*lwr)%bs;
  dp[i+1][j]%=bs;
 }   
 for (int j=0;j<=k;j++)
 {
  s[i+1][j]=dp[i+1][j];
  if (j){s[i+1][j]=(s[i+1][j-1]+s[i+1][j])%bs;}
 }
}

ans1=0;
for (int i=0;i<=k;i++)
 ans1=(ans1+dp[n][i])%bs;
 cout<<" "<<ans1<<endl;
 
cin.get();cin.get();
return 0;}








In Java :





import java.io.*;
import java.util.Arrays;

public class Solution {

    final static long mod = 1000000007;

    public static void solve(Input in, PrintWriter out) throws IOException {
        int n = in.nextInt();
        int k = in.nextInt();
        long[] d = new long[k + 1];
        d[0] = 1;
        for (int it = 0; it < n; ++it) {
            long[] dd = new long[k + 1];
            long sum = 0;
            for (int i = 0; i <= k; ++i) {
                sum = (sum + d[i]) % mod;
                dd[i] = sum;
                if (i >= it) {
                    sum = (sum + mod - d[i - it]) % mod;
                }
            }
            d = dd;
        }
//        System.err.println(Arrays.toString(d));
        long ans1 = 0;
        for (int i = 0; i <= k; ++i) {
            if (i % 2 == k % 2) {
                ans1 = (ans1 + d[i]) % mod;
            }
        }
        long[] d1 = new long[n + 1];
        d1[0] = 1;
        for (int it = 0; it < n; ++it) {
            for (int i = n; i >= 1; --i) {
                d1[i] = (d1[i] * it + d1[i - 1]) % mod;
            }
            d1[0] = 0;
        }
//        System.err.println(Arrays.toString(d1));
        long ans2 = 0;
        for (int i = 1; i <= n; ++i) {
            if (n - i <= k) {
                ans2 = (ans2 + d1[i]) % mod;
            }
        }
        out.println(ans1 + " " + ans2);
    }

    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);
        solve(new Input(new BufferedReader(
        new InputStreamReader(System.in))), out);
        out.close();
    }

    static class Input {
        BufferedReader in;
        StringBuilder sb = new StringBuilder();

        public Input(BufferedReader in) {
            this.in = in;
        }

        public Input(String s) {
            this.in = new BufferedReader(new StringReader(s));
        }

        public String next() throws IOException {
            sb.setLength(0);
            while (true) {
                int c = in.read();
                if (c == -1) {
                    return null;
                }
                if (" \n\r\t".indexOf(c) == -1) {
                    sb.append((char)c);
                    break;
                }
            }
            while (true) {
                int c = in.read();
                if (c == -1 || " \n\r\t".indexOf(c) != -1) {
                    break;
                }
                sb.append((char)c);
            }
            return sb.toString();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }
    }
}








In C :




#include<stdio.h>

int i,j,k,n,mod;
long long ans1,ans2;
long long f[2600][2600],g[2600][2600];

main()
{
	mod=1000000007;
	scanf("%d%d",&n,&k);
	f[1][0]=1;
	for (i=2; i<=n; i++)
	{
		f[i][0]=1;
		for (j=1; j<=k && j<=i*(i-1)/2; j++)
		{
			f[i][j]=f[i][j-1];
			if (j<=(i-1)*(i-2)/2) f[i][j]=(f[i][j]+f[i-1][j])%mod;
			if (j>=i) f[i][j]=(f[i][j]-f[i-1][j-i]+mod)%mod;
		}
	}
	ans1=0;
	for (i=0; i<=k; i++)
		if ((k-i)%2==0) ans1=(ans1+f[n][i])%mod;
	g[1][1]=1;
	for (i=2; i<=n; i++)
	{
		g[i][1]=g[i-1][1]*(i-1)%mod;
		for (j=2; j<i; j++)
			g[i][j]=(g[i-1][j-1]+g[i-1][j]*(i-1)%mod)%mod;
		g[i][i]=1;
	}
	ans2=0;

	for (i=n; i>=n-k && i>=1; i--)
		ans2=(ans2+g[n][i])%mod;
	printf("%lld %lld\n",ans1,ans2);
}








In Python3 :





import sys
import math

def adjSwaps(n,k):
    if k==0:
        return 1
    else:
        #n==2:
        cntksteps = [1]*(k+1)
        #n>2:
        tmp = [0]*(k+1)
        for i in range(3,n+1):
            #0...i-1
            prefixSum = 0
            for j in range(min(i,k+1)):
                prefixSum+=cntksteps[j]
                prefixSum%=1000000007
                tmp[j] = prefixSum
            #i...k
            for j in range(i,k+1):
                prefixSum+=cntksteps[j]
                prefixSum-=cntksteps[j-i]
                tmp[j] = prefixSum
            for j in range(k+1):
                cntksteps[j] = tmp[j]
            #print(cntksteps)
        return cntksteps[k]%1000000007

def anySwaps(n,k):
    if k==0:
        return 1
    elif n<=k:
        return math.factorial(n)%1000000007
    else:

        tmp = [0]*(k+1)
        #n==2:
        cntksteps = [2]*(k+1)
        cntksteps[0] = 1
        #n>2:
        for i in range(3,n+1):
            #if i<k:
                #cntksteps[i] = cntksteps[i-1]*i
            for j in range(1,k+1):
                tmp[j] = (cntksteps[j]+(i-1)*cntksteps[j-1])%1000000007
            for j in range(1,k+1):
                cntksteps[j] = tmp[j]
            #cntksteps[0] = 1
            #print(cntksteps)
        return cntksteps[k]%1000000007
    
f = sys.stdin
tmp = f.readline().split()
n = int(tmp[0])
k = int(tmp[1])
print(adjSwaps(n,k), anySwaps(n,k))
                        








View More Similar Problems

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →