#include<bits/stdc++.h>
using namespace std;

const int maxn=2e5+5;
long long a[maxn],b[maxn];
long long cnt1[maxn],cnt2[maxn],cnt[maxn];
long long pre[maxn],suf[maxn];

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n,K;
    cin>>n>>K;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        b[++b[0]]=a[i];
    }
    sort(b+1,b+b[0]+1);
    b[0]=unique(b+1,b+b[0]+1)-b-1;
    for(int i=1;i<=n;i++){
        int p=lower_bound(b+1,b+b[0]+1,a[i])-b;
        cnt[p]++;
    }
    for(int i=1;i<=b[0];i++){
        pre[i]=pre[i-1]+cnt[i]*b[i];
        cnt1[i]=cnt1[i-1]+cnt[i];
    }
    for(int i=b[0];i>=1;i--){
        suf[i]=suf[i+1]+cnt[i]*b[i];
        cnt2[i]=cnt2[i+1]+cnt[i];
    }
    long long res=0x3f3f3f3f3f3f3f3f;
    for(int i=1;i<=b[0];i++){
        int k=K-cnt[i];
        if(k<=0){
            res=0;
            break;
        }
        long long t1,t2;
        t1=cnt1[i-1]*b[i]-pre[i-1]-cnt1[i-1]+k;
        t2=suf[i+1]-cnt2[i+1]*b[i]-cnt2[i+1]+k;
        if(cnt1[i-1]>=k) res=min(res,t1);
        if(cnt2[i+1]>=k) res=min(res,t2);
        long long temp=b[i]*cnt1[i-1]-pre[i-1]+t2-cnt1[i-1];
        if(cnt1[i-1]<k) res=min(res,temp);
        temp=suf[i+1]-b[i]*cnt2[i+1]+t1-cnt2[i+1];
        if(cnt2[i+1]<k) res=min(res,temp);
    }
    cout<<res<<endl;
}


#include<bits/stdc++.h>
using namespace std;

const int maxn=2e5+5;
long long a[maxn],b[maxn];
long long cnt1[maxn],cnt2[maxn],cnt[maxn];
long long pre[maxn],suf[maxn];

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n,K;
    cin>>n>>K;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        b[++b[0]]=a[i];
    }
    sort(b+1,b+b[0]+1);
    b[0]=unique(b+1,b+b[0]+1)-b-1;
    for(int i=1;i<=n;i++){
        int p=lower_bound(b+1,b+b[0]+1,a[i])-b;
        cnt[p]++;
    }
    for(int i=1;i<=b[0];i++){
        pre[i]=pre[i-1]+cnt[i]*b[i];
        cnt1[i]=cnt1[i-1]+cnt[i];
    }
    for(int i=b[0];i>=1;i--){
        suf[i]=suf[i+1]+cnt[i]*b[i];
        cnt2[i]=cnt2[i+1]+cnt[i];
    }
    long long res=0x3f3f3f3f3f3f3f3f;
    for(int i=1;i<=b[0];i++){
        int k=K-cnt[i];
        if(k<=0){
            res=0;
            break;
        }

        long long t1,t2;
        t1=cnt1[i-1]*b[i]-pre[i-1]-cnt1[i-1]+k;
        t2=suf[i+1]-cnt2[i+1]*b[i]-cnt2[i+1]+k;
        if(cnt1[i-1]>=k) res=min(res,t1);
        else if(cnt2[i+1]>=k) res=min(res,t2);
        else{
            long long temp=b[i]*cnt1[i-1]-pre[i-1]+t2-cnt1[i-1];
            res=min(res,temp);
            temp=suf[i+1]-b[i]*cnt2[i+1]+t1-cnt2[i+1];
            res=min(res,temp);
        }
    }
    cout<<res<<endl;
}


#include<bits/stdc++.h>
using namespace std;

const int maxn=2e5+5;
int a[maxn],b[maxn];
long long cnt1[maxn],cnt2[maxn],cnt[maxn];
long long pre[maxn],suf[maxn];

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n,K;
    cin>>n>>K;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        b[++b[0]]=a[i];
    }
    sort(b+1,b+b[0]+1);
    b[0]=unique(b+1,b+b[0]+1)-b-1;
    for(int i=1;i<=n;i++){
        int p=lower_bound(b+1,b+b[0]+1,a[i])-b;
        cnt[p]++;
    }
    for(int i=1;i<=b[0];i++){
        pre[i]=pre[i-1]+cnt[i]*b[i];
        cnt1[i]=cnt1[i-1]+cnt[i];
    }
    for(int i=b[0];i>=1;i--){
        suf[i]=suf[i+1]+cnt[i]*b[i];
        cnt2[i]=cnt2[i+1]+cnt[i];
    }
    long long res=0x3f3f3f3f3f3f3f3f;
    for(int i=1;i<=b[0];i++){
        int k=K-cnt[i];
        if(k<=0) res=0;

        long long t1,t2;
        t1=cnt1[i-1]*b[i]-pre[i-1]-cnt1[i-1]+k;
        t2=suf[i+1]-cnt2[i+1]*b[i]-cnt2[i+1]+k;
        if(cnt1[i-1]>=k) res=min(res,t1);
        else if(cnt2[i+1]>=k) res=min(res,t2);
        else{
            long long temp=b[i]*cnt1[i-1]-pre[i-1]+t2-cnt1[i-1];
            res=min(res,temp);
            temp=suf[i+1]-b[i]*cnt2[i+1]+t1-cnt2[i+1];
            res=min(res,temp);
        }
    }
    cout<<res<<endl;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define P pair<ll,ll>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define lowbit(n) n&-n
#define mem(i) memset(i,0,sizeof(i))
#define bcnt(x) __builtin_popcount(x)
#define bcntz(x) __builtin_ctz(x)
#define fo(i,a,b) for(int i=a,_e=b;i<=_e;++i)
#define fd(i,a,b) for(int i=b,_e=a;i>=_e;--i)
#define ff(i,a,b) for(int i=a,_e=b;i<_e;++i)
#define Cout(a,l,r) fo(i,l,r) cout<<a[i]<<' ';cout<<endl
using namespace std;
const int maxn=200010;
typedef long long ll;
typedef long double ld;
int n,m;
int gi(){
    char a=getchar();int b=0;
    while(a<'0'||a>'9')a=getchar();
    while(a>='0'&&a<='9')b=b*10+a-'0',a=getchar();
    return b;
}

ll a[maxn],pre[maxn];
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	ll k;
	cin>>n>>k;
	fo(i,1,n) cin>>a[i];
	sort(a+1,a+1+n);
	fo(i,1,n) pre[i]=pre[i-1]+a[i];
	ll ans=1e18;
	if(k>(n+1)/2){
		fo(i,1,n){
			ll tans=0;
			//cout<<i<<endl;
			tans+=a[i]*i-pre[i];
			//cout<<tans<<endl;
			tans+=pre[n]-pre[i]-(ll)(n-i)*a[i];
			ans=min(ans,tans-(n-k));
			//cout<<tans<<endl;
		}
	}
	else {
		ans=min(ans,a[k]*k-pre[k]);
		ans=min(ans,pre[n]-pre[n-k]-a[n-k]*(ll)k);
	}
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define P pair<ll,ll>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define lowbit(n) n&-n
#define mem(i) memset(i,0,sizeof(i))
#define bcnt(x) __builtin_popcount(x)
#define bcntz(x) __builtin_ctz(x)
#define fo(i,a,b) for(int i=a,_e=b;i<=_e;++i)
#define fd(i,a,b) for(int i=b,_e=a;i>=_e;--i)
#define ff(i,a,b) for(int i=a,_e=b;i<_e;++i)
#define Cout(a,l,r) fo(i,l,r) cout<<a[i]<<' ';cout<<endl
using namespace std;
const int maxn=200010;
typedef long long ll;
typedef long double ld;
int n,m;
int gi(){
    char a=getchar();int b=0;
    while(a<'0'||a>'9')a=getchar();
    while(a>='0'&&a<='9')b=b*10+a-'0',a=getchar();
    return b;
}

ll a[maxn],pre[maxn];
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	int k;
	cin>>n>>k;
	fo(i,1,n) cin>>a[i];
	sort(a+1,a+1+n);
	fo(i,1,n) pre[i]=pre[i-1]+a[i];
	ll ans=1e18;
	if(k>n/2){
		fo(i,1,n){
			ll tans=0;
			//cout<<i<<endl;
			tans+=a[i]*i-pre[i];
			//cout<<tans<<endl;
			tans+=pre[n]-pre[i]-(n-i)*a[i];
			ans=min(ans,tans-(n-k));
			//cout<<tans<<endl;
		}
	}
	else {
		ans=min(ans,a[k]*k-pre[k]);
		ans=min(ans,pre[n]-pre[n-k]-a[n-k]*k);
	}
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define P pair<ll,ll>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define lowbit(n) n&-n
#define mem(i) memset(i,0,sizeof(i))
#define bcnt(x) __builtin_popcount(x)
#define bcntz(x) __builtin_ctz(x)
#define fo(i,a,b) for(int i=a,_e=b;i<=_e;++i)
#define fd(i,a,b) for(int i=b,_e=a;i>=_e;--i)
#define ff(i,a,b) for(int i=a,_e=b;i<_e;++i)
#define Cout(a,l,r) fo(i,l,r) cout<<a[i]<<' ';cout<<endl
using namespace std;
const int maxn=200010;
typedef long long ll;
typedef long double ld;
int n,m;
int gi(){
    char a=getchar();int b=0;
    while(a<'0'||a>'9')a=getchar();
    while(a>='0'&&a<='9')b=b*10+a-'0',a=getchar();
    return b;
}
//map<ll,int> cnt;
ll a[maxn],pre[maxn];
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	ll k;
	cin>>n>>k;
	fo(i,1,n) cin>>a[i];
	sort(a+1,a+1+n);
	fo(i,1,n) pre[i]=pre[i-1]+a[i];
	ll ans=1e18;
	if(k>(n+1)/2){
		fo(i,1,n){
			ll tans=0;
			//cout<<i<<endl;
			tans+=a[i]*i-pre[i];
			//cout<<tans<<endl;
			tans+=pre[n]-pre[i]-(ll)(n-i)*a[i];
			ans=min(ans,tans-(n-k));
			//cout<<tans<<endl;
		}
	}
	else {
		int l=k,r=n-k+1;
		while(a[l]==a[k]) l++;
		while(a[r]==a[n-k+1]) r--;
		//cout<<l<<endl;
		ans=min(ans,a[k]*k-pre[k]-(l-1-k));
		ans=min(ans,pre[n]-pre[n-k]-a[n-k+1]*(ll)k-(n-k+1-r-1));
	}
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define P pair<ll,ll>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define lowbit(n) n&-n
#define mem(i) memset(i,0,sizeof(i))
#define bcnt(x) __builtin_popcount(x)
#define bcntz(x) __builtin_ctz(x)
#define fo(i,a,b) for(int i=a,_e=b;i<=_e;++i)
#define fd(i,a,b) for(int i=b,_e=a;i>=_e;--i)
#define ff(i,a,b) for(int i=a,_e=b;i<_e;++i)
#define Cout(a,l,r) fo(i,l,r) cout<<a[i]<<' ';cout<<endl
using namespace std;
const int maxn=200010;
typedef long long ll;
typedef long double ld;
int n,m;
int gi(){
    char a=getchar();int b=0;
    while(a<'0'||a>'9')a=getchar();
    while(a>='0'&&a<='9')b=b*10+a-'0',a=getchar();
    return b;
}
map<ll,int> cnt;
ll a[maxn],pre[maxn];
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	ll k;
	cin>>n>>k;
	int mx=0;
	fo(i,1,n){
		cin>>a[i];
		cnt[a[i]]++;
		mx=max(mx,cnt[a[i]]);
	}
	if(mx>=k){
		cout<<"0"<<endl;
		return 0;
	}
	sort(a+1,a+1+n);
	fo(i,1,n) pre[i]=pre[i-1]+a[i];
	ll ans=1e18;
	{
		fo(i,1,n){
			ll tans=0;
			//cout<<i<<endl;
			tans+=a[i]*i-pre[i];
			//cout<<tans<<endl;
			tans+=pre[n]-pre[i]-(ll)(n-i)*a[i];
			ans=min(ans,tans-(n-k));
			//cout<<tans<<endl;
		}
		int l=k,r=n-k+1;
		while(a[l]==a[k]) l++;
		while(a[r]==a[n-k+1]) r--;
		//cout<<l<<endl;
		ans=min(ans,a[k]*k-pre[k]-(l-1-k));
		ans=min(ans,pre[n]-pre[n-k]-a[n-k+1]*(ll)k-(n-k+1-r-1));
	}
	cout<<ans<<endl;
	return 0;
}
/*
8 6
1 2 3 3 3 4 5 5
*/


#include<bits/stdc++.h>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define P pair<ll,ll>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define lowbit(n) n&-n
#define mem(i) memset(i,0,sizeof(i))
#define bcnt(x) __builtin_popcount(x)
#define bcntz(x) __builtin_ctz(x)
#define fo(i,a,b) for(int i=a,_e=b;i<=_e;++i)
#define fd(i,a,b) for(int i=b,_e=a;i>=_e;--i)
#define ff(i,a,b) for(int i=a,_e=b;i<_e;++i)
#define Cout(a,l,r) fo(i,l,r) cout<<a[i]<<' ';cout<<endl
using namespace std;
const int maxn=100010;
typedef long long ll;
typedef long double ld;
int n,m;
int gi(){
    char a=getchar();int b=0;
    while(a<'0'||a>'9')a=getchar();
    while(a>='0'&&a<='9')b=b*10+a-'0',a=getchar();
    return b;
}

ll a[maxn],pre[maxn];
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	int k;
	cin>>n>>k;
	fo(i,1,n) cin>>a[i];
	sort(a+1,a+1+n);
	fo(i,1,n) pre[i]=pre[i-1]+a[i];
	ll ans=1e18;
	if(k>n/2){
		fo(i,1,n){
			ll tans=0;
			//cout<<i<<endl;
			tans+=a[i]*i-pre[i];
			//cout<<tans<<endl;
			tans+=pre[n]-pre[i]-(n-i)*a[i];
			ans=min(ans,tans-(n-k));
			//cout<<tans<<endl;
		}
	}
	else {
		ans=min(ans,a[k]*k-pre[k]);
		ans=min(ans,pre[n]-pre[n-k]-a[n-k]*k);
	}
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define P pair<ll,ll>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define lowbit(n) n&-n
#define mem(i) memset(i,0,sizeof(i))
#define bcnt(x) __builtin_popcount(x)
#define bcntz(x) __builtin_ctz(x)
#define fo(i,a,b) for(int i=a,_e=b;i<=_e;++i)
#define fd(i,a,b) for(int i=b,_e=a;i>=_e;--i)
#define ff(i,a,b) for(int i=a,_e=b;i<_e;++i)
#define Cout(a,l,r) fo(i,l,r) cout<<a[i]<<' ';cout<<endl
using namespace std;
const int maxn=200010;
typedef long long ll;
typedef long double ld;
int n,m;
int gi(){
    char a=getchar();int b=0;
    while(a<'0'||a>'9')a=getchar();
    while(a>='0'&&a<='9')b=b*10+a-'0',a=getchar();
    return b;
}
map<ll,int> cnt;
ll a[maxn],pre[maxn];
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	ll k;
	cin>>n>>k;
	int mx=0;
	fo(i,1,n){
		cin>>a[i];
		cnt[a[i]]++;
		mx=max(mx,cnt[a[i]]);
	}
	if(mx>=k){
		cout<<"0"<<endl;
		return 0;
	}
	sort(a+1,a+1+n);
	fo(i,1,n) pre[i]=pre[i-1]+a[i];
	ll ans=1e18;
	if(k>(n+1)/2){
		fo(i,1,n){
			ll tans=0;
			//cout<<i<<endl;
			tans+=a[i]*i-pre[i];
			//cout<<tans<<endl;
			tans+=pre[n]-pre[i]-(ll)(n-i)*a[i];
			ans=min(ans,tans-(n-k));
			//cout<<tans<<endl;
		}
	}
	else {
		int l=k,r=n-k+1;
		while(a[l]==a[k]) l++;
		while(a[r]==a[n-k+1]) r--;
		//cout<<l<<endl;
		ans=min(ans,a[k]*k-pre[k]-(l-1-k));
		ans=min(ans,pre[n]-pre[n-k]-a[n-k+1]*(ll)k-(n-k+1-r-1));
	}
	cout<<ans<<endl;
	return 0;
}
/*
9 4
1 5 9 14 20 20 20 22 22
*/


#include<bits/stdc++.h>
#define fi first
#define se second
#define mk make_pair
#define pb push_back
#define P pair<ll,ll>
#define INF 0x3f3f3f3f
#define mod 1000000007
#define lowbit(n) n&-n
#define mem(i) memset(i,0,sizeof(i))
#define bcnt(x) __builtin_popcount(x)
#define bcntz(x) __builtin_ctz(x)
#define fo(i,a,b) for(int i=a,_e=b;i<=_e;++i)
#define fd(i,a,b) for(int i=b,_e=a;i>=_e;--i)
#define ff(i,a,b) for(int i=a,_e=b;i<_e;++i)
#define Cout(a,l,r) fo(i,l,r) cout<<a[i]<<' ';cout<<endl
using namespace std;
const int maxn=200010;
typedef long long ll;
typedef long double ld;
int n,m;
int gi(){
    char a=getchar();int b=0;
    while(a<'0'||a>'9')a=getchar();
    while(a>='0'&&a<='9')b=b*10+a-'0',a=getchar();
    return b;
}

ll a[maxn],pre[maxn];
int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	ll k;
	cin>>n>>k;
	fo(i,1,n) cin>>a[i];
	sort(a+1,a+1+n);
	fo(i,1,n) pre[i]=pre[i-1]+a[i];
	ll ans=1e18;
	if(k>(n+1)/2){
		fo(i,1,n){
			ll tans=0;
			//cout<<i<<endl;
			tans+=a[i]*i-pre[i];
			//cout<<tans<<endl;
			tans+=pre[n]-pre[i]-(ll)(n-i)*a[i];
			ans=min(ans,tans-(n-k));
			//cout<<tans<<endl;
		}
	}
	else {
		ans=min(ans,a[k]*k-pre[k]);
		ans=min(ans,pre[n]-pre[n-k]-a[n-k+1]*(ll)k);
	}
	cout<<ans<<endl;
	return 0;
}


//Wan Hong 3.1
//home
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
typedef unsigned un;
typedef std::pair<ll,ll> pll;
typedef std::string str;
#define INF (1ll<<58)
ll read()
{
	ll x=0,f=1;
	char c;
	do
	{
		c=getchar();
		if(c=='-')f=-1;
	}while(c<'0'||c>'9');
	do
	{
		x=x*10+c-'0';
		c=getchar();
	}while(c>='0'&&c<='9');
	return f*x;
}
ll min(ll a,ll b)
{
	return a<b?a:b;
}
ll max(ll a,ll b)
{
	return a>b?a:b;
}
bool umin(ll &a,ll b)
{
	if(b<a)return a=b,1;
	return 0;
}
bool umax(ll &a,ll b)
{
	if(b>a)return a=b,1;
	return 0;
}
/**********/
#define MAXN 200011
ll a[MAXN],fx[MAXN],c[MAXN],nn;
ll place(ll val)
{
    return std::lower_bound(fx+1,fx+nn+1,val)-fx;
}
int main()
{
    ll n=read(),k=read();
    for(ll i=1;i<=n;++i)fx[i]=a[i]=read();
    std::sort(fx+1,fx+n+1);
    nn=std::unique(fx+1,fx+n+1)-fx-1;
    for(ll i=1;i<=n;++i)++c[place(a[i])];
    ll ans=INF,cnt=0,costl=0,costr=0;
    for(ll i=1;i<=nn;++i)costr+=fx[i]*c[i];
    for(ll i=1;i<=nn;++i)
    {
        costl+=cnt*(fx[i]-fx[i-1]);costr-=(n-cnt)*(fx[i]-fx[i-1]);
        cnt+=c[i];
        if(cnt>=k)
        {
            umin(ans,costl-min(cnt-k,cnt-c[i]));
            continue;
        }
        umin(ans,costl+costr-min(n-k,n-c[i]));
    }
    cnt=0;
    for(ll i=nn;i;--i)
    {
        costr+=cnt*(fx[i+1]-fx[i]);costl-=(n-cnt)*(fx[i+1]-fx[i]);
        cnt+=c[i];
        if(cnt>=k)
        {
            umin(ans,costr-min(cnt-k,cnt-c[i]));
            continue;
        }
        umin(ans,costl+costr-min(n-k,n-c[i]));
    }
    printf("%lld",ans);
    return 0;
}


//Wan Hong 3.1
//home
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
typedef unsigned un;
typedef std::pair<ll,ll> pll;
typedef std::string str;
#define INF (1ll<<58)
ll read()
{
	ll x=0,f=1;
	char c;
	do
	{
		c=getchar();
		if(c=='-')f=-1;
	}while(c<'0'||c>'9');
	do
	{
		x=x*10+c-'0';
		c=getchar();
	}while(c>='0'&&c<='9');
	return f*x;
}
ll min(ll a,ll b)
{
	return a<b?a:b;
}
ll max(ll a,ll b)
{
	return a>b?a:b;
}
bool umin(ll &a,ll b)
{
	if(b<a)return a=b,1;
	return 0;
}
bool umax(ll &a,ll b)
{
	if(b>a)return a=b,1;
	return 0;
}
/**********/
#define MAXN 200011
ll a[MAXN],fx[MAXN],c[MAXN],nn;
ll place(ll val)
{
    return std::lower_bound(fx+1,fx+nn+1,val)-fx;
}
int main()
{
    ll n=read(),k=read();
    for(ll i=1;i<=n;++i)fx[i]=a[i]=read();
    std::sort(fx+1,fx+n+1);
    nn=std::unique(fx+1,fx+n+1)-fx-1;
    for(ll i=1;i<=n;++i)++c[place(a[i])];
    for(ll i=1;i<=n;++i)
        if(c[i]>=k)
        {
            puts("0");return;
        }
    ll ans=INF,cnt=0,costl=0,costr=0;
    for(ll i=1;i<=nn;++i)costr+=fx[i]*c[i];
    for(ll i=1;i<=nn;++i)
    {
        costl+=cnt*(fx[i]-fx[i-1]);costr-=(n-cnt)*(fx[i]-fx[i-1]);
        cnt+=c[i];
        if(cnt>=k)
        {
            umin(ans,costl-min(cnt-k,cnt-c[i]));
            continue;
        }
        umin(ans,costl+costr-min(n-k,n-c[i]));
    }
    cnt=0;
    for(ll i=nn;i;--i)
    {
        costr+=cnt*(fx[i+1]-fx[i]);if(i<nn)costl-=(n-cnt)*(fx[i+1]-fx[i]);
        cnt+=c[i];
        if(cnt>=k)
        {
            umin(ans,costr-min(cnt-k,cnt-c[i]));
            continue;
        }
        umin(ans,costl+costr-min(n-k,n-c[i]));
    }
    printf("%lld",ans);
    return 0;
}


//Wan Hong 3.1
//home
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
typedef unsigned un;
typedef std::pair<ll,ll> pll;
typedef std::string str;
#define INF (1ll<<58)
ll read()
{
	ll x=0,f=1;
	char c;
	do
	{
		c=getchar();
		if(c=='-')f=-1;
	}while(c<'0'||c>'9');
	do
	{
		x=x*10+c-'0';
		c=getchar();
	}while(c>='0'&&c<='9');
	return f*x;
}
ll min(ll a,ll b)
{
	return a<b?a:b;
}
ll max(ll a,ll b)
{
	return a>b?a:b;
}
bool umin(ll &a,ll b)
{
	if(b<a)return a=b,1;
	return 0;
}
bool umax(ll &a,ll b)
{
	if(b>a)return a=b,1;
	return 0;
}
/**********/
#define MAXN 200011
ll a[MAXN],fx[MAXN],c[MAXN],nn;
ll place(ll val)
{
    return std::lower_bound(fx+1,fx+nn+1,val)-fx;
}
int main()
{
    ll n=read(),k=read();
    for(ll i=1;i<=n;++i)fx[i]=a[i]=read();
    std::sort(fx+1,fx+n+1);
    nn=std::unique(fx+1,fx+n+1)-fx-1;
    for(ll i=1;i<=n;++i)++c[place(a[i])];
    for(ll i=1;i<=n;++i)
        if(c[i]>=k)
        {
            puts("0");return 0;
        }
    ll ans=INF,cnt=0,costl=0,costr=0;
    for(ll i=1;i<=nn;++i)costr+=fx[i]*c[i];
    for(ll i=1;i<=nn;++i)
    {
        costl+=cnt*(fx[i]-fx[i-1]);costr-=(n-cnt)*(fx[i]-fx[i-1]);
        cnt+=c[i];
        if(cnt>=k)
        {
            umin(ans,costl-min(cnt-k,cnt-c[i]));
            continue;
        }
        umin(ans,costl+costr-min(n-k,n-c[i]));
    }
    cnt=0;
    for(ll i=nn;i;--i)
    {
        costr+=cnt*(fx[i+1]-fx[i]);if(i<nn)costl-=(n-cnt)*(fx[i+1]-fx[i]);
        cnt+=c[i];
        if(cnt>=k)
        {
            umin(ans,costr-min(cnt-k,cnt-c[i]));
            continue;
        }
        umin(ans,costl+costr-min(n-k,n-c[i]));
    }
    printf("%lld",ans);
    return 0;
}


//Wan Hong 3.1
//home
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
typedef unsigned un;
typedef std::pair<ll,ll> pll;
typedef std::string str;
#define INF (1ll<<58)
ll read()
{
	ll x=0,f=1;
	char c;
	do
	{
		c=getchar();
		if(c=='-')f=-1;
	}while(c<'0'||c>'9');
	do
	{
		x=x*10+c-'0';
		c=getchar();
	}while(c>='0'&&c<='9');
	return f*x;
}
ll min(ll a,ll b)
{
	return a<b?a:b;
}
ll max(ll a,ll b)
{
	return a>b?a:b;
}
bool umin(ll &a,ll b)
{
	if(b<a)return a=b,1;
	return 0;
}
bool umax(ll &a,ll b)
{
	if(b>a)return a=b,1;
	return 0;
}
/**********/
#define MAXN 200011
ll a[MAXN],fx[MAXN],c[MAXN],nn;
ll place(ll val)
{
    return std::lower_bound(fx+1,fx+nn+1,val)-fx;
}
int main()
{
    ll n=read(),k=read();
    for(ll i=1;i<=n;++i)fx[i]=a[i]=read();
    std::sort(fx+1,fx+n+1);
    nn=std::unique(fx+1,fx+n+1)-fx-1;
    for(ll i=1;i<=n;++i)++c[place(a[i])];
    ll ans=INF,cnt=0,costl=0,costr=0;
    for(ll i=1;i<=nn;++i)costr+=fx[i]*c[i];
    for(ll i=1;i<=nn;++i)
    {
        costl+=cnt*(fx[i]-fx[i-1]);costr-=(n-cnt)*(fx[i]-fx[i-1]);
        cnt+=c[i];
        if(cnt>=k)
        {
            umin(ans,costl-min(cnt-k,cnt-c[i]));
            continue;
        }
        umin(ans,costl+costr-min(n-k,n-c[i]));
    }
    cnt=0;
    for(ll i=nn;i;--i)
    {
        costr+=cnt*(fx[i+1]-fx[i]);if(i<nn)costl-=(n-cnt)*(fx[i+1]-fx[i]);
        cnt+=c[i];
        if(cnt>=k)
        {
            umin(ans,costr-min(cnt-k,cnt-c[i]));
            continue;
        }
        umin(ans,costl+costr-min(n-k,n-c[i]));
    }
    printf("%lld",ans);
    return 0;
}


#include<cstdio>
#include<algorithm>

using namespace std;

namespace IO
{
    static char buf[1<<20],*fs,*ft;
    inline char gc()
    {
        if(fs==ft)
        {
			ft=(fs=buf)+fread(buf,1,1<<20,stdin);
			if(fs==ft)return EOF;
        }
        return *fs++;
    }
    #define gc() getchar()
	inline int read()
	{
		int x=0,f=1;char s=gc();
		while(s<'0'||s>'9'){if(s=='-')f=-f;s=gc();}
		while(s>='0'&&s<='9'){x=x*10+s-'0';s=gc();}
		return x*f;
	}
}using IO::read;

const int N=200100;

int n,k;

int a[N];

int m,num[N],cnt[N];

long long pre[N],suf[N];
long long pcnt[N],scnt[N];

long long ans=1e18;

int main()
{
	n=read(),k=read();

	for(int i=1;i<=n;i++)
		a[i]=read();

	sort(a+1,a+1+n);

	int S=0;

	for(int i=1;i<=n;i++)
	{
		S++;
		if(a[i]!=a[i+1])
		{
			m++;
			num[m]=a[i],cnt[m]=S;
			S=0;
		}
	}

	for(int i=2;i<=m;i++)
	{
		pre[i]=pre[i-1]+pcnt[i-1]*(num[i]-num[i-1])+cnt[i-1]*(num[i]-num[i-1]-1);
		pcnt[i]=pcnt[i-1]+cnt[i-1];
	}

	for(int i=m-1;i>=1;i--)
	{
		suf[i]=suf[i+1]+scnt[i+1]*(num[i+1]-num[i])+cnt[i+1]*(num[i+1]-num[i]-1);
		scnt[i]=scnt[i+1]+cnt[i+1];
	}

	for(int i=1;i<=m;i++)
	{
		int res=k-cnt[i];

		if(res<=0)
		{
			puts("0");
			return 0;
		}

		if(i>1&&i<m)
			ans=min(ans,pre[i]+suf[i]+res);

		if(i>1&&pcnt[i]>=res)
			ans=min(ans,pre[i]+res);

		if(i<m&&scnt[i]>=res)
			ans=min(ans,suf[i]+res);
	}

	printf("%lld\n",ans);

	return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
long long a[200005];
long long qian[200005],hou[200005],ans;
int main(){
	int n,k;
	cin>>n>>k;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	sort(a+1,a+n+1);
	for(int i=1;i<=n;i++){
		qian[i]=qian[i-1]+a[i];
	}
	for(int i=n;i>=1;i--){
		hou[i]=hou[i+1]+a[i];
	}
	for(long long i=1;i<=n;i++){
		long long ansnow;
		if(i>=k) ansnow=i*a[i]-qian[i]-(i-k);
		else ansnow=i*a[i]-qian[i]+hou[i]-(n-i+1)*a[i]-(n-k);
		if(n-i+1>=k) ansnow=min(ansnow,hou[i]-(n-i+1)*a[i]-(n-i+1-k));
		else ansnow=min(ansnow,hou[i]-(n-i+1)*a[i]+i*a[i]-qian[i]-(n-k));
		if(i==1) ans=ansnow;
		else ans=min(ansnow,ans);
	}
	cout<<ans<<endl;
}


#include<iostream>
#include<algorithm>
#include<cstring>
#include<stdio.h>
#define MAXN 200010
#define ll long long
using namespace std;
int n;
ll a[MAXN],sum[MAXN];

int getl(int id){
	int i=id;
	while(a[i]==a[id]&&i>0) i--;
	i++;return i;
}

int getr(int id){
	int i=id;
	while(a[i]==a[id]&&i<=n) i++;
	i--;return i;
}

int k;

int main(){
	cin>>n>>k;
	for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
	sort(a+1,a+n+1);
	for(int i=1;i<=n;i++){
		sum[i]=sum[i-1]+a[i];
	}
	ll ans=(1ll<<60);
	for(int i=1;i<=n;i++){
		ll l=getl(i),r=getr(i);
		ll tmp=1ll<<60,goal=k-(r-l+1);ll x=a[i];
		if(goal<=0){
			puts("0");
			exit(0);
		}
		if(goal<=l-1){
			tmp=min(tmp,(x-1)*(l-1)-sum[l-1]+goal);
		}
		if(goal<=n-r){
			tmp=min(tmp,sum[n]-sum[r]-(x+1)*(n-r)+goal);
		}
		tmp=min(tmp,sum[n]-sum[r]-(x+1)*(n-r)+(x-1)*(l-1)-sum[l-1]+goal);
		ans=min(ans,tmp);
		i=r;
	}
	cout<<ans<<endl;

}


#include<iostream>
#include<algorithm>
#include<cstring>
#include<stdio.h>
#define MAXN 200010
#define ll long long
using namespace std;
int n;
ll a[MAXN],sum[MAXN];

int getl(int id){
	int i=id;
	while(a[i]==a[id]&&i>0) i--;
	i++;return i;
}

int getr(int id){
	int i=id;
	while(a[i]==a[id]&&i<=n) i++;
	i--;return i;
}

int k;

int main(){
	cin>>n>>k;
	for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
	sort(a+1,a+n+1);
	for(int i=1;i<=n;i++){
		sum[i]=sum[i-1]+a[i];
	}
	ll ans=(1ll<<60);
	for(int i=1;i<=n;i++){
		ll l=getl(i),r=getr(i);
		ll tmp=1ll<<60,goal=k-(r-l+1);ll x=a[i];
		if(goal<=0){
			puts("0");
			exit(0);
		}
		if(goal<=l-1){
			tmp=min(tmp,(x-1)*(l-1)-sum[l-1]+goal);
		}
		if(goal<=n-r){
			tmp=min(tmp,sum[n]-sum[r]-(x+1)*(n-r)+goal);
		}
		tmp=min(tmp,sum[n]-sum[r]-(x+1)*(n-r)+(x-1)*(l-1)-sum[l-1]+goal);
		ans=min(ans,tmp);
	}
	cout<<ans<<endl;
}


#include<bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
const int N=1e6+50,inf=1e9+7;
int n,k,a[N],suf[N],pre[N],num[N],cnt[N],ans=inf;
int main(){
//	freopen("input.in","r",stdin);
//	freopen("output.out","w",stdout);
	scanf("%d%d",&n,&k);
	rep(i,1,n) scanf("%d",&a[i]);
	sort(a+1,a+n+1);
	rep(i,1,n) pre[i]=pre[i-1]+a[i];
	rep(i,1,n) pre[i]=i*a[i]-pre[i];
	per(i,n,1) suf[i]=suf[i+1]+a[i];
	per(i,n,1) suf[i]-=(n-i+1)*a[i];
	rep(i,1,n) cnt[i]=(a[i]==a[i-1]?cnt[i-1]+1:1);
	rep(i,1,n) if(cnt[i]>=k) { puts("0"); return 0; }
	rep(i,1,n){
		if(i<k) ans=min(ans,pre[i]+suf[i]-(n-k));
		else ans=min(ans,pre[i]-(i-k));
		if((n-i+1)<k) ans=min(ans,pre[i]+suf[i]-(n-k));
		else ans=min(ans,suf[i]-(n-i+1-k));
	}
	printf("%d\n",ans);
	return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
int a[200005];
long long qian[200005],hou[200005],ans;
int main(){
	int n,k;
	cin>>n>>k;
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	sort(a+1,a+n+1);
	for(int i=1;i<=n;i++){
		qian[i]=qian[i-1]+a[i];
	}
	for(int i=n;i>=1;i--){
		hou[i]=hou[i+1]+a[i];
	}
	for(int i=1;i<=n;i++){
		long long ansnow;
		if(i>=k) ansnow=i*a[i]-qian[i]-(i-k);
		else ansnow=i*a[i]-qian[i]+hou[i]-(n-i+1)*a[i]-(n-k);
		if(n-i+1>=k) ansnow=min(ansnow,hou[i]-(n-i+1)*a[i]-(n-i+1-k));
		else ansnow=min(ansnow,hou[i]-(n-i+1)*a[i]+i*a[i]-qian[i]-(n-k));
		if(i==1) ans=ansnow;
		else ans=min(ansnow,ans);
	}
	cout<<ans<<endl;
}


#include<cstdio>
#include<iostream>
#include<cstring>
#include <map>
#include <queue>
#include <set>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <time.h>

#define ll long long
#define ull unsigned ll
#define _min(x, y) ((x)>(y)?(y):(x))
#define _max(x, y) ((x)>(y)?(x):(y))
#define max3(x, y, z) ( max( (x), max( (y), (z) ) ) )
#define min3(x, y, z) ( min( (x), min( (y), (z) ) ) )
#define pr(x, y) (make_pair((x), (y)))

#pragma GCC optimize(2)

using namespace std;
const int N = 2e5+5;
const ll inf = 0x3f3f3f3f3f3f3f3f;
ll su[N], st[N];
struct Node
{
    int l, r;
    int mx, mi;
}tr[N<<2];
void build(int p, int l, int r)
{
    tr[p].l = l; tr[p].r = r;
    if (l == r)
    {
        tr[p].mx = tr[p].mi = su[l];
        return;
    }
    int mid =(l + r) >> 1;
    build(p<<1, l, mid);
    build(p<<1|1, mid+1, r);
    tr[p].mx = _max(tr[p<<1].mx, tr[p<<1|1].mx);
    tr[p].mi = _min(tr[p<<1].mi, tr[p<<1|1].mi);
}
ll askmx(int p, int l, int r)
{
    if (l <= tr[p].l && tr[p].r <= r)
        return tr[p].mx;
    int mid = (tr[p].l + tr[p].r) >> 1;
    ll val = -1;
    if (l <= mid) val = askmx(p<<1, l, r);
    if (r > mid) val = max(val, askmx (p<<1|1, l, r));
    return val;
}
ll askmi(int p, int l, int r)
{
    if (l <= tr[p].l && tr[p].r <= r)
        return tr[p].mi;
    int mid = (tr[p].l + tr[p].r) >> 1;
    ll val = inf;
    if (l <= mid) val = askmi(p<<1, l, r);
    if (r > mid) val =min(val, askmi (p<<1|1, l, r));
    return val;
}
int main()
{
    int n, k;
    ll ans = inf;
    cin >> n >> k;
    for (int i = 1; i <= n; i++)
        scanf("%lld", &su[i]);
    sort(su+1, su+n+1);
    build(1, 1, n);
    for (int i = 1; i <= n; i++) su[i] += su[i-1];
    for (int i = 0; i <= k; i++)
    {
        ll tb = -su[i] + (su[n] - su[n - (k - i)]);
        ll hou = k - i;
        ll tt;
        if (i >= hou)
            tt = askmi(1, i ? i : 1, n - (k - i - 1));
        else
            tt = askmx(1,  i ? i : 1, n-(k-i-1));
        ans = min(ans, tb + (i - hou) * tt);
    }
    printf("%lld\n", ans);
    return 0;
}


#include<cstdio>
#include<iostream>
#include<cstring>
#include <map>
#include <queue>
#include <set>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <time.h>

#define ll long long
#define ull unsigned ll
#define int ll
#define _min(x, y) ((x)>(y)?(y):(x))
#define _max(x, y) ((x)>(y)?(x):(y))
#define max3(x, y, z) ( max( (x), max( (y), (z) ) ) )
#define min3(x, y, z) ( min( (x), min( (y), (z) ) ) )
#define pr(x, y) (make_pair((x), (y)))

#pragma GCC optimize(2)

using namespace std;
const int N = 2e5+5;
const int inf = 0x3f3f3f3f3f3f3f3f;
int su[N], sum[N];
signed main()
{
    int n, k; cin >> n >> k;
    for (int i = 1; i <= n; i++)
        scanf("%lld", &su[i]);
    sort(su+1, su+n+1);
    for (int i = 1; i <= n; i++)
        sum[i] = sum[i-1] + su[i];
    int anss = inf;
    for (int i = 1; i <= n; i++)
    {
        int te = su[i];
        int l = lower_bound(su+1, su+n+1, te) - su;
        int r = upper_bound(su+1, su+n+1, te) - su - 1;
        int t = k - (r - l + 1);
        int ln = l - 1;
        int rn = n - r;
        int ans = sum[n] - sum[r] - rn * (te+1) + ln * (te - 1) - sum[l-1] + t;
        if (ln >= t)
            ans = min(ans, ln * (te - 1) - sum[l-1] + t);
        if (rn >= t)
            ans = min(ans, sum[n] - sum[r] - rn * (te+1) + t);
        anss = min(anss, ans);
    }
    printf("%lld\n", anss);
    return 0;
}


#include<cstdio>
#include<iostream>
#include<cstring>
#include <map>
#include <queue>
#include <set>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <time.h>

#define ll long long
#define ull unsigned ll
#define int ll
#define _min(x, y) ((x)>(y)?(y):(x))
#define _max(x, y) ((x)>(y)?(x):(y))
#define max3(x, y, z) ( max( (x), max( (y), (z) ) ) )
#define min3(x, y, z) ( min( (x), min( (y), (z) ) ) )
#define pr(x, y) (make_pair((x), (y)))

#pragma GCC optimize(2)

using namespace std;
const int N = 2e5+5;
const int inf = 0x3f3f3f3f3f3f3f3f;
int su[N], sum[N];
signed main()
{
    int n, k; cin >> n >> k;
    for (int i = 1; i <= n; i++)
        scanf("%lld", &su[i]);
    sort(su+1, su+n+1);
    for (int i = 1; i <= n; i++)
        sum[i] = sum[i-1] + su[i];
    int anss = inf;
    for (int i = 1; i <= n; i++)
    {
        int te = su[i];
        int l = lower_bound(su+1, su+n+1, te) - su;
        int r = upper_bound(su+1, su+n+1, te) - su - 1;
        int t = k - (r - l + 1);
        if (t <= 0)
        {
            anss = 0;
            continue;
        }
        int ln = l - 1;
        int rn = n - r;
        int ans = sum[n] - sum[r] - rn * (te+1) + ln * (te - 1) - sum[l-1] + t;
        if (ln >= t)
            ans = min(ans, ln * (te - 1) - sum[l-1] + t);
        if (rn >= t)
            ans = min(ans, sum[n] - sum[r] - rn * (te+1) + t);
        anss = min(anss, ans);
    }
    printf("%lld\n", anss);
    return 0;
}


#include<cstdio>
#include<iostream>
#include<cstring>
#include <map>
#include <queue>
#include <set>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <time.h>

#define ll long long
#define ull unsigned ll
#define _min(x, y) ((x)>(y)?(y):(x))
#define _max(x, y) ((x)>(y)?(x):(y))
#define max3(x, y, z) ( max( (x), max( (y), (z) ) ) )
#define min3(x, y, z) ( min( (x), min( (y), (z) ) ) )
#define pr(x, y) (make_pair((x), (y)))

#pragma GCC optimize(2)

using namespace std;
const int N = 2e5+5;
const ll inf = 0x3f3f3f3f3f3f3f3f;
ll su[N];
struct Node
{
    int l, r;
    ll mx, mi;
}tr[N<<2];
void build(int p, int l, int r)
{
    tr[p].l = l; tr[p].r = r;
    if (l == r)
    {
        tr[p].mx = tr[p].mi = su[l];
        return;
    }
    int mid =(l + r) >> 1;
    build(p<<1, l, mid);
    build(p<<1|1, mid+1, r);
    tr[p].mx = _max(tr[p<<1].mx, tr[p<<1|1].mx);
    tr[p].mi = _min(tr[p<<1].mi, tr[p<<1|1].mi);
}
ll askmx(int p, int l, int r)
{
    if (l <= tr[p].l && tr[p].r <= r)
        return tr[p].mx;
    int mid = (tr[p].l + tr[p].r) >> 1;
    ll val = -1;
    if (l <= mid) val = askmx(p<<1, l, r);
    if (r > mid) val = max(val, askmx (p<<1|1, l, r));
    return val;
}
ll askmi(int p, int l, int r)
{
    if (l <= tr[p].l && tr[p].r <= r)
        return tr[p].mi;
    int mid = (tr[p].l + tr[p].r) >> 1;
    ll val = inf;
    if (l <= mid) val = askmi(p<<1, l, r);
    if (r > mid) val =min(val, askmi (p<<1|1, l, r));
    return val;
}
int main()
{
    int n, k;
    ll ans = inf;
    cin >> n >> k;
    for (int i = 1; i <= n; i++)
        scanf("%lld", &su[i]);
    sort(su+1, su+n+1);
    build(1, 1, n);
    for (int i = 1; i <= n; i++) su[i] += su[i-1];
    for (int i = 0; i <= k; i++)
    {
        ll tb = -su[i] + (su[n] - su[n - (k - i)]);
        ll hou = k - i;
        ll tt;
        if (i >= hou)
            tt = su[i] - su[i-1];
        else
            tt = su[n - (k - i - 1)] - su[n - (k - i - 1) - 1];
        ans = min(ans, tb + (i - hou) * tt);
    }
    printf("%lld\n", ans);
    return 0;
}


#include<cstdio>
#include<iostream>
#include<cstring>
#include <map>
#include <queue>
#include <set>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <time.h>

#define ll long long
#define ull unsigned ll
#define _min(x, y) ((x)>(y)?(y):(x))
#define _max(x, y) ((x)>(y)?(x):(y))
#define max3(x, y, z) ( max( (x), max( (y), (z) ) ) )
#define min3(x, y, z) ( min( (x), min( (y), (z) ) ) )
#define pr(x, y) (make_pair((x), (y)))

#pragma GCC optimize(2)

using namespace std;
const int N = 2e5+5;
const ll inf = 0x3f3f3f3f3f3f3f3f;
ll su[N];
struct Node
{
    int l, r;
    ll mx, mi;
}tr[N<<2];
void build(int p, int l, int r)
{
    tr[p].l = l; tr[p].r = r;
    if (l == r)
    {
        tr[p].mx = tr[p].mi = su[l];
        return;
    }
    int mid =(l + r) >> 1;
    build(p<<1, l, mid);
    build(p<<1|1, mid+1, r);
    tr[p].mx = _max(tr[p<<1].mx, tr[p<<1|1].mx);
    tr[p].mi = _min(tr[p<<1].mi, tr[p<<1|1].mi);
}
ll askmx(int p, int l, int r)
{
    if (l <= tr[p].l && tr[p].r <= r)
        return tr[p].mx;
    int mid = (tr[p].l + tr[p].r) >> 1;
    ll val = -1;
    if (l <= mid) val = askmx(p<<1, l, r);
    if (r > mid) val = max(val, askmx (p<<1|1, l, r));
    return val;
}
ll askmi(int p, int l, int r)
{
    if (l <= tr[p].l && tr[p].r <= r)
        return tr[p].mi;
    int mid = (tr[p].l + tr[p].r) >> 1;
    ll val = inf;
    if (l <= mid) val = askmi(p<<1, l, r);
    if (r > mid) val =min(val, askmi (p<<1|1, l, r));
    return val;
}
int main()
{
    int n, k;
    ll ans = inf;
    cin >> n >> k;
    for (int i = 1; i <= n; i++)
        scanf("%lld", &su[i]);
    sort(su+1, su+n+1);
    build(1, 1, n);
    for (int i = 1; i <= n; i++) su[i] += su[i-1];
    for (int i = 0; i <= k; i++)
    {
        ll tb = -su[i] + (su[n] - su[n - (k - i)]);
        ll hou = k - i;
        ll tt;
        if (i >= hou)
            tt = askmi(1, i ? i : 1,   (n - (k - i - 1) == n+1 ? n : n-(k-i-1))   );
        else
            tt = askmx(1,  i ? i : 1,  (n - (k - i - 1) == n+1 ? n : n-(k-i-1))  );
        ans = min(ans, tb + (i - hou) * tt);
    }
    printf("%lld\n", ans);
    return 0;
}


#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
//#define endl '\n'
#define all(A) (A).begin(),(A).end()
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define PER(I, A, B) for (int I = (A); I >= (B); --I)
#define lson k*2
#define rson k*2+1
#define fi first
#define se second
#define DB(A) cout<<(A)<<endl
#define DB1(A,B,C) cout<<(A)<<" "<<(B)<<" "<<(C)<<"!"<<endl
#define PB push_back
#define Pair pair<int,int>
#define MP make_pair
#define LL long long
#define int LL
using namespace std;
const int maxn=1000+10;
const int MAX=1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
//head
int n,k;
signed main()
{
	SIS;
	cin>>n>>k;
	vector<int>a(n+1,0);
	FOR(i,1,n)
	{
		cin>>a[i];
	}
	sort(all(a));
	FOR(i,1,n-k+1)
	{
		if (a[i]==a[i+k-1])
		{
			return DB(0),0;
		}
	}
	int ansl=0,ansr=0,ansmid=0;
	FOR(i,1,k-1)
	{
		ansl+=a[k]-a[i];
	}
	FOR(i,k+1,n) if (a[i]==a[i-1]) ansl--;else break;

	PER(i,n,n-k+2)
	{
		ansr+=a[i]-a[n-k+1];
	}
	PER(i,n-k,1) if (a[i]==a[i+1]) ansr--;else break;

	FOR(i,1,n)
	{
		int j=n-i+1;
		if (i>=j) break;
		ansmid+=a[j]-a[i];
	}
	ansmid-=(n-k);
	DB(min(ansmid,min(ansl,ansr)));
}


#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
//#define endl '\n'
#define all(A) (A).begin(),(A).end()
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define PER(I, A, B) for (int I = (A); I >= (B); --I)
#define lson k*2
#define rson k*2+1
#define fi first
#define se second
#define DB(A) cout<<(A)<<endl
#define DB1(A,B,C) cout<<(A)<<" "<<(B)<<" "<<(C)<<"!"<<endl
#define PB push_back
#define Pair pair<int,int>
#define MP make_pair
#define LL long long
#define int LL
using namespace std;
const int maxn=1000+10;
const int MAX=1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
//head
int n,k;
signed main()
{
	SIS;
	cin>>n>>k;
	vector<int>a(n+1,0);
	FOR(i,1,n)
	{
		cin>>a[i];
	}
	sort(all(a));
	int ansl=0,ansr=0,ansmid=0;
	FOR(i,1,k-1)
	{
		ansl+=a[k]-a[i];
	}
	FOR(i,k,n) if (a[i]==a[i-1]) ansl--;

	PER(i,n,n-k+2)
	{
		ansr+=a[i]-a[n-k+1];
	}
	FOR(i,1,n-k) if (a[i]==a[i+1]) ansr--;

	FOR(i,1,n)
	{
		int j=n-i+1;
		if (i>=j) break;
		ansmid+=a[j]-a[i];
	}
	ansmid-=(n-k);
	DB(min(ansmid,min(ansl,ansr)));
}


#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
//#define endl '\n'
#define all(A) (A).begin(),(A).end()
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define PER(I, A, B) for (int I = (A); I >= (B); --I)
#define lson k*2
#define rson k*2+1
#define fi first
#define se second
#define DB(A) cout<<(A)<<endl
#define DB1(A,B,C) cout<<(A)<<" "<<(B)<<" "<<(C)<<"!"<<endl
#define PB push_back
#define Pair pair<int,int>
#define MP make_pair
#define LL long long
#define int LL
using namespace std;
const int maxn=1000+10;
const int MAX=1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
//head
int n,k;
signed main()
{
	SIS;
	cin>>n>>k;
	vector<int>a(n+1,0);
	FOR(i,1,n)
	{
		cin>>a[i];
	}
	sort(all(a));
	FOR(i,1,n-k+1)
	{
		if (a[i]==a[i+k-1])
		{
			return DB(0),0;
		}
	}
	int ansl=0,ansr=0,ansmid=0;
	FOR(i,1,k-1)
	{
		ansl+=a[k]-a[i];
	}
	FOR(i,k+1,n) if (a[i]==a[i-1]) ansl--;

	PER(i,n,n-k+2)
	{
		ansr+=a[i]-a[n-k+1];
	}
	FOR(i,1,n-k) if (a[i]==a[i+1]) ansr--;

	FOR(i,1,n)
	{
		int j=n-i+1;
		if (i>=j) break;
		ansmid+=a[j]-a[i];
	}
	ansmid-=(n-k);
	ansmid=max(ansmid,0ll);
	DB(min(ansmid,min(ansl,ansr)));
}


#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
//#define endl '\n'
#define all(A) (A).begin(),(A).end()
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define PER(I, A, B) for (int I = (A); I >= (B); --I)
#define lson k*2
#define rson k*2+1
#define fi first
#define se second
#define DB(A) cout<<(A)<<endl
#define DB1(A,B,C) cout<<(A)<<" "<<(B)<<" "<<(C)<<"!"<<endl
#define PB push_back
#define Pair pair<int,int>
#define MP make_pair
#define LL long long
#define int LL
using namespace std;
const int maxn=1000+10;
const int MAX=1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
//head
int n,k;
signed main()
{
	SIS;
	cin>>n>>k;
	vector<int>a(n+1,0);
	FOR(i,1,n)
	{
		cin>>a[i];
	}
	sort(all(a));
	FOR(i,1,n-k+1)
	{
		if (a[i]==a[i+k-1])
		{
			return DB(0),0;
		}
	}
	int ansl=0,ansr=0,ansmid=0;
	FOR(i,1,k-1)
	{
		ansl+=a[k]-a[i];
	}
	FOR(i,k,n) if (a[i]==a[i-1]) ansl--;

	PER(i,n,n-k+2)
	{
		ansr+=a[i]-a[n-k+1];
	}
	FOR(i,1,n-k) if (a[i]==a[i+1]) ansr--;

	FOR(i,1,n)
	{
		int j=n-i+1;
		if (i>=j) break;
		ansmid+=a[j]-a[i];
	}
	ansmid-=(n-k);
	DB(min(ansmid,min(ansl,ansr)));
}


#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
//#define endl '\n'
#define all(A) (A).begin(),(A).end()
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define PER(I, A, B) for (int I = (A); I >= (B); --I)
#define lson k*2
#define rson k*2+1
#define fi first
#define se second
#define DB(A) cout<<(A)<<endl
#define DB1(A,B,C) cout<<(A)<<" "<<(B)<<" "<<(C)<<"!"<<endl
#define PB push_back
#define Pair pair<int,int>
#define MP make_pair
#define LL long long
#define int LL
using namespace std;
const int maxn=4e5+10;
const int MAX=1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
//head
int n,m;
int f[maxn];
int a[maxn];
int c[maxn];
int cc[maxn];
int b[maxn];
int ff[maxn];
int ori[maxn];
int ans=1e15;
void update(int k)
{
	if (k<ans) ans=k;
}
signed main()
{
	SIS;
	cin>>n>>m;
	FOR(i,1,n)
	{
		cin>>a[i];
	}
	sort(a+1,a+1+n);
	int tot=0;
	FOR(i,1,n) if (a[i]!=a[i-1]) b[++tot]=a[i],ori[tot]=1;
	else ori[tot]++;//number
	FOR(i,1,tot) c[i]=c[i-1]+ori[i];
	FOR(i,1,tot)
	{
		f[i]=f[i-1]+c[i-1]*(b[i]-b[i-1]);
	}

	PER(i,tot,1) cc[i]=cc[i+1]+ori[i];
	PER(i,tot,1)
	{
		ff[i]=ff[i+1]+cc[i+1]*(b[i+1]-b[i]);
	}

	FOR(i,1,tot)
	{
		int sum=0;
		if (ori[i]>=m)
		{
			return DB(0),0;
		}
		int del=m-ori[i];
//		sum=ff[i+1]+ff[i-1];
		int dis1=b[i]-b[i-1];
		int dis2=b[i+1]-b[i];
		if (dis1>dis2)// prefer 2
		{
			sum+=ff[i+1];
			if (cc[i+1]>=del)
			{
				sum+=dis2*del;
				update(sum);
			}
			else
			{
				sum+=dis2*cc[i+1];
				del-=cc[i+1];
				sum+=f[i-1];
				sum+=dis1*del;
				update(sum);
			}
		}
		else // prefer 2
		{
			sum+=f[i-1];
			if (c[i-1]>=del)
			{
				sum+=dis1*del;
				update(sum);
			}
			else
			{
				sum+=dis1*c[i-1];
				del-=c[i-1];
				sum+=ff[i+1];
				sum+=dis2*del;
				update(sum);
			}
		}
	}
	DB(ans);
}


#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
//#define endl '\n'
#define all(A) (A).begin(),(A).end()
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define PER(I, A, B) for (int I = (A); I >= (B); --I)
#define lson k*2
#define rson k*2+1
#define fi first
#define se second
#define DB(A) cout<<(A)<<endl
#define DB1(A,B,C) cout<<(A)<<" "<<(B)<<" "<<(C)<<"!"<<endl
#define PB push_back
#define Pair pair<int,int>
#define MP make_pair
#define LL long long
#define int LL
using namespace std;
const int maxn=4e5+10;
const int MAX=1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
//head
int n,m;
int f[maxn];
int a[maxn];
int c[maxn];
int cc[maxn];
int b[maxn];
int ff[maxn];
int ori[maxn];
int ans=1e15;
void update(int k)
{
	if (k<ans) ans=k;
}
signed main()
{
	SIS;
	cin>>n>>m;
	FOR(i,1,n)
	{
		cin>>a[i];
	}
	sort(a+1,a+1+n);
	int tot=0;
	FOR(i,1,n) if (a[i]!=a[i-1]) b[++tot]=a[i],ori[tot]=1;
	else ori[tot]++;//number
	FOR(i,1,tot) c[i]=c[i-1]+ori[i];
	FOR(i,1,tot)
	{
		f[i]=f[i-1]+c[i-1]*(b[i]-b[i-1]);
	}

	PER(i,tot,1) cc[i]=cc[i+1]+ori[i];
	PER(i,tot,1)
	{
		ff[i]=ff[i+1]+cc[i+1]*(b[i+1]-b[i]);
	}

	FOR(i,1,tot)
	{

		if (ori[i]>=m)
		{
			return DB(0),0;
		}
		int dis1=b[i]-b[i-1];
		int dis2=b[i+1]-b[i];
		int del=m-ori[i];
		int sum=0;
//		if (dis1>dis2)// prefer 2
		{
			sum+=ff[i+1];
			if (cc[i+1]>=del)
			{
				sum+=dis2*del;
				update(sum);
			}
			else
			{
				sum+=dis2*cc[i+1];
				del-=cc[i+1];
				sum+=f[i-1];
				sum+=dis1*del;
				update(sum);
			}
		}
		del=m-ori[i];
		sum=0;
//		else // prefer 1
		{
			sum+=f[i-1];
			if (c[i-1]>=del)
			{
				sum+=dis1*del;
				update(sum);
			}
			else
			{
				sum+=dis1*c[i-1];
				del-=c[i-1];
				sum+=ff[i+1];
				sum+=dis2*del;
				update(sum);
			}
		}
	}
	DB(ans);
}


#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
//#define endl '\n'
#define all(A) (A).begin(),(A).end()
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define PER(I, A, B) for (int I = (A); I >= (B); --I)
#define lson k*2
#define rson k*2+1
#define fi first
#define se second
#define DB(A) cout<<(A)<<endl
#define DB1(A,B,C) cout<<(A)<<" "<<(B)<<" "<<(C)<<"!"<<endl
#define PB push_back
#define Pair pair<int,int>
#define MP make_pair
#define LL long long
#define int LL
using namespace std;
const int maxn=1000+10;
const int MAX=1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
//head
int n,k;
signed main()
{
	SIS;
	cin>>n>>k;
	vector<int>a(n+1,0);
	FOR(i,1,n)
	{
		cin>>a[i];
	}
	sort(all(a));
	FOR(i,1,n-k+1)
	{
		if (a[i]==a[i+k-1])
		{
			return DB(0),0;
		}
	}
	int ansl=0,ansr=0,ansmid=0;
	FOR(i,1,k-1)
	{
		ansl+=a[k]-a[i];
	}
	FOR(i,k+1,n) if (a[i]==a[i-1]) ansl--;else break;

	PER(i,n,n-k+2)
	{
		ansr+=a[i]-a[n-k+1];
	}
	FOR(i,1,n-k) if (a[i]==a[i+1]) ansr--;else break;

	FOR(i,1,n)
	{
		int j=n-i+1;
		if (i>=j) break;
		ansmid+=a[j]-a[i];
	}
	ansmid-=(n-k);
	ansmid=max(ansmid,0ll);
	DB(min(ansmid,min(ansl,ansr)));
}


#include <bits/stdc++.h>
#pragma GCC diagnostic error "-std=c++11"
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
//#define endl '\n'
#define all(A) (A).begin(),(A).end()
#define FOR(I, A, B) for (int I = (A); I <= (B); ++I)
#define PER(I, A, B) for (int I = (A); I >= (B); --I)
#define lson k*2
#define rson k*2+1
#define fi first
#define se second
#define DB(A) cout<<(A)<<endl
#define DB1(A,B,C) cout<<(A)<<" "<<(B)<<" "<<(C)<<"!"<<endl
#define PB push_back
#define Pair pair<int,int>
#define MP make_pair
#define LL long long
#define int LL
using namespace std;
const int maxn=1000+10;
const int MAX=1000;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
//head
int n,k;
signed main()
{
	SIS;
	cin>>n>>k;
	vector<int>a(n+1,0);
	FOR(i,1,n)
	{
		cin>>a[i];
	}
	FOR(i,1,n-k+1)
	{
		if (a[i]==a[i+k-1])
		{
			return DB(0),0;
		}
	}
	sort(all(a));
	int ansl=0,ansr=0,ansmid=0;
	FOR(i,1,k-1)
	{
		ansl+=a[k]-a[i];
	}
	FOR(i,k,n) if (a[i]==a[i-1]) ansl--;

	PER(i,n,n-k+2)
	{
		ansr+=a[i]-a[n-k+1];
	}
	FOR(i,1,n-k) if (a[i]==a[i+1]) ansr--;

	FOR(i,1,n)
	{
		int j=n-i+1;
		if (i>=j) break;
		ansmid+=a[j]-a[i];
	}
	ansmid-=(n-k);
	DB(min(ansmid,min(ansl,ansr)));
}


//CF1328F
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
ll raw[maxn],pre[maxn],suf[maxn],cnt;
ll ans = 1e17;
int main(){
	int n,k;
	scanf("%d%d",&n,&k);
	for(int i = 1;i <= n;i++)scanf("%lld",&raw[i]);
	sort(raw+1,raw+n+1);
	for(int i = 1;i <= n;i++){
		if(raw[i] != raw[i-1]){
			if(cnt >= k){
				printf("0");
				return 0;
			}
			cnt = 1;
		}
		else cnt++;
	}
	for(int i = 1;i <= n;i++)pre[i] = pre[i-1]+raw[i];
	for(int i = n;i >= 1;i--)suf[i] = suf[i+1]+raw[i];
	for(int i = 1;i <= n;i++){
		if(i <= k)ans = min(ans,i*raw[i] - pre[i] + suf[i] - (n-i+1)*raw[i] - (n-k));
		else ans = min(ans,i*raw[i] - pre[i] - (i-k));
		if(n-i+1 <= k)ans = min(ans,suf[i] - (n-i+1)*raw[i] + i*raw[i] - pre[i] - (n-k));
		else ans = min(ans,suf[i] - (n-i+1)*raw[i] - (n-i+1-k));
	}
	cout << max(ans,0ll);
	return 0;
}


//CF1328F
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
ll raw[maxn],pre[maxn],suf[maxn];
ll ans = 1e17;
int main(){
	int n,k;
	scanf("%d%d",&n,&k);
	for(int i = 1;i <= n;i++)scanf("%lld",&raw[i]);
	sort(raw+1,raw+n+1);
	for(int i = 1;i <= n;i++)pre[i] = pre[i-1]+raw[i];
	for(int i = n;i >= 1;i--)suf[i] = suf[i+1]+raw[i];
	for(int i = 1;i <= n;i++){
		if(i <= k)ans = min(ans,i*raw[i] - pre[i] + suf[i] - (n-i+1)*raw[i] - (n-k));
		else ans = min(ans,i*raw[i] - pre[i] - (i-k));
	}
	cout << ans;
	return 0;
}


//CF1328F
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
ll raw[maxn],pre[maxn],suf[maxn],cnt;
ll ans = 1e17;
int main(){
	int n,k;
	scanf("%d%d",&n,&k);
	for(int i = 1;i <= n;i++)scanf("%lld",&raw[i]);
	sort(raw+1,raw+n+1);
	for(int i = 1;i <= n;i++){
		if(raw[i] != raw[i-1]){
			if(cnt >= k){
				printf("0");
				return 0;
			}
			cnt = 1;
		}
		else cnt++;
	}
	for(int i = 1;i <= n;i++)pre[i] = pre[i-1]+raw[i];
	for(int i = n;i >= 1;i--)suf[i] = suf[i+1]+raw[i];
	for(int i = 1;i <= n;i++){
		if(i < k)ans = min(ans,i*raw[i] - pre[i] + suf[i] - (n-i+1)*raw[i] - (n-k));
		else ans = min(ans,i*raw[i] - pre[i] - (i-k));
		if(n-i+1 < k)ans = min(ans,suf[i] - (n-i+1)*raw[i] + i*raw[i] - pre[i] - (n-k));
		else ans = min(ans,suf[i] - (n-i+1)*raw[i] - (n-i+1-k));
	}
	cout << max(ans,0ll);
	return 0;
}


n,m,k=map(int,raw_input().split())
for _ in range(n):
    raw_input()
print (m)*(m-1)/2
for i in range(1,m):
    for j in range(i+1,m+1):
        if k==0:
            print i,j
        else:
            print j,i


n,m,k=map(int,raw_input().split())
A=[map(int,raw_input().split()) for i in range(n)]
se=set()
for l in A:
    s=sorted(l,reverse=k)
    for i in range(len(l)):
        if s[i]==l[i]:
            continue
        index=l.index(s[i])
        t=l[index]
        l[index]=l[i]
        l[i]=t
        se.add( (i,index) )
print len(se)
for x in se:
    print x[0]+1,x[1]+1


n,m,k=map(int,raw_input().split())
for _ in range(n):
    raw_input()
print (m-1)*(m-2)/2
for i in range(1,m-1):
    for j in range(i+1,m):
        if k==0:
            print i,j
        else:
            print j,i


n,m,k=map(int,raw_input().split())
for _ in range(n):
    raw_input()
print m*(m-1)/2
for i in range(1,m-1):
    for j in range(i+1,m):
        if k==0:
            print i,j
        else:
            print j,i


n,m,k=map(int,raw_input().split())
print m*(m-1)/2
for i in range(1,m+1):
    for j in range(i+1,m+1):
        if not k:
            print j,i
        else:
            print i,j


n,m,k=map(int,raw_input().split())
print m*(m-1)/2
for i in range(1,m+1):
    for j in range(i+1,m+1):
        if k:
            print j,i
        else:
            print j,i


n,m,k=map(int,raw_input().split())
print m*(m-1)/2
for i in range(1,m+1):
    for j in range(i+1,m+1):
        if k:
            print j,i
        else:
            print i,j


n,m,k=map(int,raw_input().split())
print m*(m-1)/2
for i in range(1,m+1):
    for j in range(i+1,m+1):
        if not k:
            print j,i
        else:
            print j,i


lst=[]
lst2=[]
n,m,k=map(int,raw_input().split())
for i in range(n):
    arr=map(int,raw_input().split())
    lst.append(arr)
if(k==0):
    for i in range(0,m-1):
        for j in range(i+1,m):
            for p in range(0,n):
                if(lst[p][i]>lst[p][j]):
                    tu=(i+1,j+1)
                    if tu not in lst2:
                        lst2.append(tu)
                    temp=lst[p][i]
                    lst[p][i]=lst[p][j]
                    lst[p][j]=temp
if(k==1):
    for i in range(0,m-1):
        for j in range(i+1,m):
            for p in range(0,n):
                if(lst[p][i]<lst[p][j]):
                    tu=(i+1,j+1)
                    if tu not in lst2:
                        lst2.append(tu)
                    temp=lst[p][i]
                    lst[p][i]=lst[p][j]
                    lst[p][j]=temp
print len(lst2)
for i in range(0,len(lst2)):
    print lst2[i][0],lst2[i][1]


lst=[]
lst2=[]
n,m,k=map(int,raw_input().split())
for i in range(n):
    arr=map(int,raw_input().split())
    lst.append(arr)
print m * (m - 1) / 2
if(k==0):
    for i in range(1,m+1):
        for j in range(i+1,m+1):
            print i,j

if(k==1):
    for i in range(1,m+1):
        for j in range(i+1,m+1):
            print j,i


lst=[]
lst2=[]
n,m,k=map(int,raw_input().split())
for i in range(n):
    arr=map(int,raw_input().split())
    lst.append(arr)
if(k==0):
    for i in range(0,m-1):
        for j in range(i+1,m):
            for p in range(0,n):
                if(lst[p][i]>lst[p][j]):
                    tu=(i+1,j+1)
                    if tu not in lst2:
                        lst2.append(tu)
                    temp=lst[p][i]
                    lst[p][i]=lst[p][j]
                    lst[p][j]=temp
if(k==1):
    for i in range(0,m-1):
        for j in range(i+1,m):
            for p in range(0,n):
                if(lst[p][i]<lst[p][j]):
                    tu=(i+1,j+1)
                    if tu not in lst2:
                        lst2.append(tu)
                    temp=lst[p][i]
                    lst[p][i]=lst[p][j]
                    lst[p][j]=temp
print len(lst2)
for i in range(0,len(lst2)):
    print lst2[i][1],lst2[i][0]


n,m,k=map(int,raw_input().split())
print m*(m-1)/2
for i in range(1,m+1):
  for j in range(i+1,m+1):
    print '%d %d'%((j,i) if k else (i,j))


import sys

[n,m,k] = map(int, sys.stdin.readline().strip().split())

for i in range(0,n):
    sys.stdin.readline()

l = []

for i in range(1,m+1):
    for j in range(i+1,m+1):
        if (k==0):
            l.append([i,j])
        else:
            l.append([j,i])

print m*(m-1) / 2
for p in l:
    print ' '.join(map(str, p))


(n,m,k) = map(int,raw_input ( ).split())
print (m*(m-1)/2)
if not k:
    for i in range(m-1, -1, -1):
        for j in range(i):
              print j+1, j+2
else:
    for i in range(m):
        for j in range(m-i-1):
            print m-j, m-j-1


def read_ints():
    return map(int, raw_input().split(' '))

n, m, k = read_ints()
print m * (m - 1) / 2
a = map(lambda i: zip([i] * (i - 1), range(1, i)), range(2, m + 1))
a = [item for sublist in a for item in sublist]

def swap(seq):
    x, y = seq
    return (y, x)

if k == 0:
    a = map(swap, a)
a = sorted(a)
for i in a:
    print "%d %d" % i


#!/usr/bin/env python

def get_sort_arr(arrs, m, desc):
    print m * (m - 1) / 2
    for i in range(1, m + 1):
        for j in range(i + 1, m + 1):
            x, y = i, j
            if desc:
                x, y = y, x
            print '%s %s' % (x, y)

if __name__ == '__main__':
    n, m, k = map(int, raw_input().split())
    arrs = []
    for i in range(n):
        arrs.append(map(int, raw_input().split()))
    get_sort_arr(arrs, m, k)


import sys

(n, m, k) = map(int, raw_input().split())
x = raw_input()
x = raw_input()
print (m*(m+1)/2)
for i in xrange(m):
	for j in xrange(i+1, m):
		if k == 0:
			print str(i+1) + ' ' + str(j+1)
		else:
			print str(j+1) + ' ' + str(i+1)


import sys

(n, m, k) = map(int, raw_input().split())
print (m*(m-1)/2)
for i in xrange(m):
	for j in xrange(i+1, m):
		if k == 0:
			print str(i+1) + ' ' + str(j+1)
		else:
			print str(j+1) + ' ' + str(i+1)


import sys

(n, m, k) = map(int, raw_input().split())
x = raw_input()
x = raw_input()
print (m*(m-1)/2)
for i in xrange(m):
	for j in xrange(i+1, m):
		if k == 0:
			print str(i+1) + ' ' + str(j+1)
		else:
			print str(j+1) + ' ' + str(i+1)


n,m,k = map(int, raw_input().split())
a = []
for i in xrange(n):
	a.append(map(int, raw_input().split()))

print m*(m-1)/2
for i in xrange(m):
	for j in xrange(m-1, i, -1):
		print j, j+1


n,m,k = map(int, raw_input().split())
a = []
for i in xrange(n):
	a.append(map(int, raw_input().split()))

if k == 0:
	print m*(m-1)/2
	for i in xrange(m):
		for j in xrange(m-1, i, -1):
			print j, j+1
else:
	print m*(m-1)/2
	for i in xrange(m):
		for j in xrange(m-1, i, -1):
			print m-j+1, m-j


n,m,k = map(int, raw_input().split())
a = []
for i in xrange(n):
	a.append(map(int, raw_input().split()))

if k == 0:
	print m*(m-1)/2
	for i in xrange(m):
		for j in xrange(m-1, i, -1):
			print j, j+1
else:
	print m*(m-1)/2
	for i in xrange(m):
		for j in xrange(m-1, i, -1):
			print m-1-i+1, m-1-i


n,m,k = map(int, raw_input().split())
a = []
for i in xrange(n):
	a.append(map(int, raw_input().split()))

if k == 0:
	print m*(m-1)/2
	for i in xrange(m):
		for j in xrange(m-1, i, -1):
			print j, j+1
else:
	print m*(m-1)/2
	for i in xrange(m):
		for j in xrange(m-1, i, -1):
			print m-1-j+1, m-1-j


I = lambda: map(int, raw_input().split())
m, n, k = I()
print n*(n-1)/2
for i in xrange(1, n+1):
  for j in xrange(i+1, n+1):
    if k: print j, i
    else: print i, j


n, m, k = map(int, raw_input().split(" "))

for i in xrange(n):
  raw_input()

print m * (m - 1) / 2
if k == 0:
  for i in xrange(m - 1):
    for j in xrange(i):
      print j + 1, j + 2
else:
  for i in xrange(m - 1):
    for j in xrange(i):
      print j + 2, j + 1


n, m, k = map(int, raw_input().split(" "))

for i in xrange(n):
  raw_input()

print m * (m - 1) / 2
if k == 0:
  for i in xrange(m - 1, -1, -1):
    for j in xrange(i):
      print j + 1, j + 2
else:
  for i in xrange(m - 1, -1, -1):
    for j in xrange(i):
      print j + 2, j + 1


n, m, k = map(int, raw_input().split(" "))

for i in xrange(n):
  raw_input()

if k == 0:
  for i in xrange(m - 1):
    for j in xrange(i):
      print j + 1, j + 2
else:
  for i in xrange(m - 1):
    for j in xrange(i):
      print j + 2, j + 1


import sys
s = (raw_input())
n = int(s.split(" ")[0])
m = int(s.split(" ")[1])
k = int(s.split(" ")[2])
for z in range(n):
	s = (raw_input())

#0 ascending
p = m*(m-1)/2
print p
for i in xrange(0,m):
	for j in xrange(1,m):
		if i<j:
			if not k:
				print (i+1),(j+1)
			else:
				print (j+1),(i+1)

# 2 5 1
# 1 3 2 5 4
# 1 4 3 2 5


#!/usr/bin/python

n, m, k = map(int, raw_input().split())
A = [map(int, raw_input().split()) for i in range(n)]

def relation(x, y, k) :
    if k == 0 :
        return x <= y
    else :
        return x >= y

options = []

for i in range(1, m) :
    for j in range(m-i) :
        flag = False
        for r in range(n) :
            if not relation(A[r][j], A[r][j+1], k) :
                flag = True
                tmp = A[r][j]
                A[r][j] = A[r][j+1]
                A[r][j+1] = tmp
        if flag :
            if k == 0 :
                options.append((j, j+1))
            else :
                options.append((j+1, j))

print len(options)
for i,j in options :
    print "%d %d" % (i+1, j+1)


#!/usr/bin/python

n, m, k = map(int, raw_input().split())
A = [map(int, raw_input().split()) for i in range(n)]

def relation(x, y, k) :
    if k == 0 :
        return x <= y
    else :
        return x >= y

options = []

for i in range(1, m) :
    for j in range(m-i) :
        if all([relation(A[r][j], A[r][j+1], k) for r in range(n)]) :
            pass
        else :
            if k == 0 :
                options.append((j, j+1))
            else :
                options.append((j+1, j))
            for r in range(n) :
                if not relation(A[r][j], A[r][j+1], k) :
                    tmp = A[r][j]
                    A[r][j] = A[r][j+1]
                    A[r][j+1] = tmp

print len(options)
for i,j in options :
    print "%d %d" % (i+1, j+1)


n,m,k=map(int,raw_input().split())
print m*(m-1)/2
for i in range(1,m+1):
  for j in range(i+1,m+1):
    print '%d %d'%((j,i) if k else (i,j))


import os
import sys
n, m, k = map(int, raw_input().split())
a = []
for i in range(n):
    s = sys.stdin.readline()
    a += [map(int, s.split())]
b = [sorted(a[i]) for i in range(n)]

if k == 1:
    for i in range(n): b[i] = b[i][::-1]

p = 0
#si, sj = [], []
res = []
for j in range(m - 1):
    for i in range(n):
        for t in range(j + 1, m):
           if a[i][t] == b[i][j] and a[i][j] != b[i][j]:
               p += 1
               if a[i][t] > a[i][j]:
                   res += [str(t+1) + ' ' + str(j + 1)]
                   #si += [t]
                   #sj += [j]
                   for x in range(i, n):
                       if a[x][t] > a[x][j]: a[x][t], a[x][j] = a[x][j], a[x][t]
               else:
                   #si += [j]
                   #sj += [t]
                   res += [str(j+1) + ' ' + str(t + 1)]
                   for x in range(i, n):
                       if a[x][t] < a[x][j]: a[x][t], a[x][j] = a[x][j], a[x][t]

print p
for i in range(p):
    #sys.stdout.write(' '.join([str(si[i] + 1), str(sj[i] + 1)]))
    sys.stdout.write(res[i])
    sys.stdout.write('\n')


n, m, k = map(int, raw_input().split())

a = [map(int, raw_input().split()) for i in range(n)]
b = [sorted(a[i]) for i in range(n)]

if k == 1:
    for i in range(n): b[i] = b[i][::-1]

p = 0
si, sj = [], []

for j in range(m - 1):
    for i in range(n):
        for t in range(j + 1, m):
           if a[i][t] == b[i][j] and a[i][j] != b[i][j]:
               p += 1
               if a[i][t] > a[i][j]:
                   si += [t]
                   sj += [j]
                   for x in range(n):
                       if a[x][t] > a[x][j]: a[x][t], a[x][j] = a[x][j], a[x][t]
               else:
                   si += [j]
                   sj += [t]
                   for x in range(n):
                       if a[x][t] < a[x][j]: a[x][t], a[x][j] = a[x][j], a[x][t]

print p
for i in range(p): print si[i] + 1, sj[i] + 1


import os
import sys
n, m, k = map(int, raw_input().split())

a = [map(int, raw_input().split()) for i in range(n)]
b = [sorted(a[i]) for i in range(n)]

if k == 1:
    for i in range(n): b[i] = b[i][::-1]

p = 0
si, sj = [], []

for j in range(m - 1):
    for i in range(n):
        for t in range(j + 1, m):
           if a[i][t] == b[i][j] and a[i][j] != b[i][j]:
               p += 1
               if a[i][t] > a[i][j]:
                   si += [t]
                   sj += [j]
                   for x in range(n):
                       if a[x][t] > a[x][j]: a[x][t], a[x][j] = a[x][j], a[x][t]
               else:
                   si += [j]
                   sj += [t]
                   for x in range(n):
                       if a[x][t] < a[x][j]: a[x][t], a[x][j] = a[x][j], a[x][t]

print p
for i in range(p):
    sys.stdout.write(' '.join([str(si[i] + 1), str(sj[i] + 1)]))
    sys.stdout.write('\n')


import os
import sys
n, m, k = map(int, raw_input().split())
a = []
for i in range(n):
    s = sys.stdin.readline()
    a += [map(int, s.split())]
b = [sorted(a[i]) for i in range(n)]

if k == 1:
    for i in range(n): b[i] = b[i][::-1]

p = 0
si, sj = [], []

for j in range(m - 1):
    for i in range(n):
        for t in range(j + 1, m):
           if a[i][t] == b[i][j] and a[i][j] != b[i][j]:
               p += 1
               if a[i][t] > a[i][j]:
                   si += [t]
                   sj += [j]
                   for x in range(n):
                       if a[x][t] > a[x][j]: a[x][t], a[x][j] = a[x][j], a[x][t]
               else:
                   si += [j]
                   sj += [t]
                   for x in range(n):
                       if a[x][t] < a[x][j]: a[x][t], a[x][j] = a[x][j], a[x][t]

print p
for i in range(p):
    sys.stdout.write(' '.join([str(si[i] + 1), str(sj[i] + 1)]))
    sys.stdout.write('\n')


import os
import sys
n, m, k = map(int, raw_input().split())
p = m * (m - 1)/2
res = []
for j in range(1, m):
   for t in range(j + 1, m + 1):
       if k == 0: res += [str(j) +  ' ' + str(t)]
       else: res += [str(t) + ' ' + str(j)]
print p
for i in range(p):
    #sys.stdout.write(' '.join([str(si[i] + 1), str(sj[i] + 1)]))
    sys.stdout.write(res[i])
    sys.stdout.write('\n')


#!/usr/bin/python
import sys

line=raw_input()
line=line.split(' ')
n=int(line[0])
m=int(line[1])
k=int(line[2])

s=[[]]*n
ret=[]

for i in range(n):
    s[i]=[]
    line=raw_input().split(' ')
    for j in range(len(line)):
        s[i].append(int(line[j]))

def mySwap(s,level,n,i,j):
    global ret
    if i==j:
        return
    if s[level][i]==s[level][j]:
        return
    if s[level][i]>s[level][j]:
        ret.append((i+1,j+1))
        for k in range(level,n):
            if s[k][i]>s[k][j]:
                tmp=s[k][i]
                s[k][i]=s[k][j]
                s[k][j]=tmp
    else:
        ret.append((j+1,i+1))
        for k in range(level,n):
            if s[k][i]<s[k][j]:
                tmp=s[k][i]
                s[k][i]=s[k][j]
                s[k][j]=tmp

def myQsort(k,s,level,n,begin,end):

    if (begin+1>=end):
        return

    i=begin+1
    j=end-1
    a=s[level]
    while True:
        while i<end:
            if k==0 and a[i]>a[begin]:
                break
            elif k==1 and a[i]<a[begin]:
                break
            i+=1
        if i==end:
            mySwap(s,level,n,begin,end-1)
            return myQsort(k,s,level,n,begin,end-1)

        while j>begin:
            if k==0 and not a[j]>a[begin]:
                break
            elif k==1 and not a[j]<a[begin]:
                break
            j-=1
        if j==begin:
            return myQsort(k,s,level,n,begin+1,end)

        if i>j:
            mySwap(s,level,n,begin,i-1)
            myQsort(k,s,level,n,begin,i-1)
            myQsort(k,s,level,n,i,end)
            return
        mySwap(s,level,n,i,j)
        i+=1
        j-=1
    return

for i in range(n):
    myQsort(k,s,i,n,0,m)
print len(ret)
for e in ret:
    sys.stdout.write(str(e[0]))
    sys.stdout.write(' ')
    sys.stdout.write(str(e[1]))
    sys.stdout.write('\n')


#!/usr/bin/python
import sys

line=raw_input()
line=line.split(' ')
n=int(line[0])
m=int(line[1])
k=int(line[2])

s=[[]]*n
ret=[]

for i in range(n):
    s[i]=[]
    line=raw_input().split(' ')
    for j in range(len(line)):
        s[i].append(int(line[j]))

def mySwap(s,level,n,i,j):
    global ret
    if i==j:
        return
    if s[level][i]==s[level][j]:
        return
    if s[level][i]>s[level][j]:
        ret.append((i+1,j+1))
        for k in range(level,n):
            if s[k][i]>s[k][j]:
                tmp=s[k][i]
                s[k][i]=s[k][j]
                s[k][j]=tmp
    else:
        ret.append((j+1,i+1))
        for k in range(level,n):
            if s[k][i]<s[k][j]:
                tmp=s[k][i]
                s[k][i]=s[k][j]
                s[k][j]=tmp

def myQsort(k,s,level,n,begin,end):

    if (begin+1>=end):
        return

    i=begin+1
    j=end-1
    a=s[level]
    while True:
        while i<end:
            if k==0 and a[i]>a[begin]:
                break
            elif k==1 and a[i]<a[begin]:
                break
            i+=1
        if i==end:
            mySwap(s,level,n,begin,end-1)
            return myQsort(k,s,level,n,begin,end-1)

        while j>begin:
            if k==0 and not a[j]>a[begin]:
                break
            elif k==1 and not a[j]<a[begin]:
                break
            j-=1
        if j==begin:
            return myQsort(k,s,level,n,begin+1,end)

        if i>j:
            mySwap(s,level,n,begin,i-1)
            myQsort(k,s,level,n,begin,i-2)
            myQsort(k,s,level,n,i,end)
            return
        mySwap(s,level,n,i,j)
        i+=1
        j-=1
    return

for i in range(n):
    myQsort(k,s,i,n,0,m)
print len(ret)
for e in ret:
    sys.stdout.write(str(e[0]))
    sys.stdout.write(' ')
    sys.stdout.write(str(e[1]))
    sys.stdout.write('\n')


#!/usr/bin/python
import sys

line=raw_input()
line=line.split(' ')
n=int(line[0])
m=int(line[1])
k=int(line[2])

s=[[]]*n
ret=[]

for i in range(n):
    s[i]=[]
    line=raw_input().split(' ')
    for j in range(len(line)):
        s[i].append(int(line[j]))

def mySwap(s,level,n,i,j):
    global ret
    if i==j:
        return
    if s[level][i]==s[level][j]:
        return
    if s[level][i]>s[level][j]:
        ret.append((i+1,j+1))
        for k in range(level,n):
            if s[k][i]>s[k][j]:
                tmp=s[k][i]
                s[k][i]=s[k][j]
                s[k][j]=tmp
    else:
        ret.append((j+1,i+1))
        for k in range(level,n):
            if s[k][i]<s[k][j]:
                tmp=s[k][i]
                s[k][i]=s[k][j]
                s[k][j]=tmp

def myQsort(k,s,level,n,begin,end):

    if (begin+1>=end):
        return

    i=begin+1
    j=end-1
    a=s[level]
    while True:
        while i<end:
            if k==0 and a[i]>a[begin]:
                break
            elif k==1 and a[i]<a[begin]:
                break
            i+=1
        if i==end:
            mySwap(s,level,n,begin,end-1)
            return myQsort(k,s,level,n,begin,end-1)

        while j>begin:
            if k==0 and not a[j]>a[begin]:
                break
            elif k==1 and not a[j]<a[begin]:
                break
            j-=1
        if j==begin:
            return myQsort(k,s,level,n,begin+1,end)

        if i>j:
            mySwap(s,level,n,begin,i-1)
            myQsort(k,s,level,n,begin,i-1)
            myQsort(k,s,level,n,i,end)
            return
        mySwap(s,level,n,i,j)
        i+=1
        j-=1
    return
def isOK(a,m,k):
    i=1
    while i<m:
        if k==0 and a[i]<a[i-1]:
            return False
        elif k==1 and a[i]>a[i-1]:
            return False
        i+=1
    return True

for i in range(n):
    if not isOK(s[i],m,k):
        myQsort(k,s,i,n,0,m)

print len(ret)
for e in ret:
    sys.stdout.write(str(e[0]))
    sys.stdout.write(' ')
    sys.stdout.write(str(e[1]))
    sys.stdout.write('\n')


def ascend(m):
    answers = ""
    answer = 0
    for i in range(1,m):
        for j in range(i+1, m+1):
            answers+="%d %d\n"%(i,j)
            answer += 1

    return str(answer)+'\n'+ answers[:-1]

def descend(m):
    answers = ""
    answer = 0
    for i in range(1,m):
        for j in range(i+1, m+1):
            answers+="%d %d\n"%(j,i)
            answer += 1

    return str(answer)+'\n'+ answers[:-1]

def main():
    n, m, k = [int(i) for i in raw_input().split()]
    if k == 0:
        answer = ascend(m)
    else:
        answer = descend(m)
    return answer

if __name__=='__main__':
    print main()


m = int(raw_input().split()[1])
print (m * (m - 1)) / 2
for i in range(1, m + 1):
  for j in range(i + 1, m + 1):
    print i, j


from itertools import combinations
n, m, k = map(int, raw_input().split())
l = [range(1, m + 1), range(m, 0, -1)][k]
ans = list(combinations(l, 2))
print len(ans)
for i, j in ans:
  print i, j


#include <stdio.h>

int main(void)
{
    int n, m, k;
    scanf("%d %d %d", &n, &m, &k);
    printf("%d\n", m * (m - 1) / 2);
    for (int i = 1; i < m; i++)
        for (int j = i + 1; j <= m; j++)
            printf("%d %d\n", k ? j : i, k ? i : j);
}


//Author: Nikhil_Medam
//Language: C
//Assignment 6 Question 2
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	int n,m,k,x;
	scanf("%d%d%d",&n,&m,&k);
	for(int i=0;i<n*m;i++)
		scanf("%d",&x);
	for(int i=1;i<=m;i++)
		for(int j=i+1;j<=m;j++)
		{
			if(!k)
				printf("%d %d\n",i,j);
			else
				printf("%d %d\n",j,i);
		}
	return 0;
}


//Author: Nikhil_Medam
//Language: C
//Assignment 6 Question 2
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
	int n,m,k,x;
	scanf("%d%d%d",&n,&m,&k);
	for(int i=0;i<n*m;i++)
		scanf("%d",&x);
	printf("%d\n",m*(m-1)/2);
	for(int i=1;i<=m;i++)
		for(int j=i+1;j<=m;j++)
		{
			if(!k)
				printf("%d %d\n",i,j);
			else
				printf("%d %d\n",j,i);
		}
	return 0;
}


#include<stdio.h>
#define R(i,a,n)    for(int i=a;i<n;i++)
#define cin(x)  scanf("%lld",&x)
typedef long long int ll;

int main()  {
    ll m,n,t;
    cin(m),cin(n),cin(t);
    ll A[m][n];
    R(i,0,m)
        R(j,0,n)
            cin(A[i][j]);

    ll Z[n*(n-1)/2];
    ll z =0,a;

    if(t)   {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[k][j]<A[k][j+1])
                        a = A[k][j], A[k][j] =A[k][j+1], A[k][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }
    else    {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[k][j]>A[k][j+1])
                        a = A[k][j], A[k][j] =A[k][j+1], A[k][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }

    printf("%lld\n",z);
    if(!t)
    R(i,0,z)
        printf("%lld %lld\n",Z[i]+1,Z[i]);
    else
        R(i,0,z)
            printf("%lld %lld\n",Z[i]+1,Z[i]+2);
    return 0;
}


#include<stdio.h>
#define R(i,a,n)    for(int i=a;i<n;i++)
#define cin(x)  scanf("%lld",&x)
typedef long long int ll;

int main()  {
    ll m,n,t;
    cin(m),cin(n),cin(t);
    ll A[m][n];
    R(i,0,m)
        R(j,0,n)
            cin(A[i][j]);

    ll Z[n*(n-1)/2];
    ll z =0,a;

    if(t)   {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[k][j]>A[k][j+1])
                        a = A[i][j], A[i][j] =A[i][j+1], A[i][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }
    else    {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[k][j]>A[k][j+1])
                        a = A[i][j], A[i][j] =A[i][j+1], A[i][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }
    printf("%lld\n",z);
    if(t)
    R(i,0,z)
        printf("%lld %lld\n",Z[i]+1,Z[i]);
    else
        R(i,0,z)
            printf("%lld %lld\n",Z[i]+1,Z[i]+2);
    return 0;
}


#include<stdio.h>
#define R(i,a,n)    for(int i=a;i<n;i++)
#define cin(x)  scanf("%lld",&x)
typedef long long int ll;

int main()  {
    ll m,n,t;
    cin(m),cin(n),cin(t);
    ll A[m][n];
    R(i,0,m)
        R(j,0,n)
            cin(A[i][j]);

    ll Z[n*(n-1)/2];
    ll z =0,a;

    if(t)   {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[k][j]<A[k][j+1])
                        a = A[k][j], A[k][j] =A[k][j+1], A[k][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }
    else    {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[k][j]>A[k][j+1])
                        a = A[k][j], A[k][j] =A[k][j+1], A[k][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }

    printf("%lld\n",z);
    if(t)
    R(i,0,z)
        printf("%lld %lld\n",Z[i]+1,Z[i]);
    else
        R(i,0,z)
            printf("%lld %lld\n",Z[i]+1,Z[i]+2);
    return 0;
}


#include<stdio.h>
#define R(i,a,n)    for(int i=a;i<n;i++)
#define cin(x)  scanf("%lld",&x)
typedef long long int ll;

int main()  {
    ll m,n,t;
    cin(m),cin(n),cin(t);
    ll A[m][n];
    R(i,0,m)
        R(j,0,n)
            cin(A[i][j]);

    ll Z[n*(n-1)/2];
    ll z =0,a;

    if(t)   {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[i][j]>A[i][j+1])
                        a = A[i][j], A[i][j] =A[i][j+1], A[i][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }
    else    {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[i][j]>A[i][j+1])
                        a = A[i][j], A[i][j] =A[i][j+1], A[i][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }
    printf("%lld\n",z);
    if(t)
    R(i,0,z)
        printf("%lld %lld\n",Z[i]+1,Z[i]);
    else
        R(i,0,z)
            printf("%lld %lld\n",Z[i]+1,Z[i]+2);
    return 0;
}


#include<stdio.h>
#define R(i,a,n)    for(int i=a;i<n;i++)
#define cin(x)  scanf("%lld",&x)
typedef long long int ll;

int main()  {
    ll m,n,t;
    cin(m),cin(n),cin(t);
    ll A[m][n];
    R(i,0,m)
        R(j,0,n)
            cin(A[i][j]);

    ll Z[n*(n-1)/2];
    ll z =0,a;

    if(t)   {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[k][j]<A[k][j+1])
                        a = A[k][j], A[k][j] =A[k][j+1], A[k][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }
    else    {
        R(i,0,n)
            R(j,0,n-i-1)    {
                ll count =0;
                R(k,0,m)
                    if(A[k][j]>A[k][j+1])
                        a = A[k][j], A[k][j] =A[k][j+1], A[k][j+1] = a,count++;
            if(count)   Z[z++] = j+1;
            }
    }

    printf("%lld\n",z);
    if(t)
    R(i,0,z)
        printf("%lld %lld\n",Z[i]+1,Z[i]);
    else
        R(i,0,z)
            printf("%lld %lld\n",Z[i],Z[i]+1);
    return 0;
}


/* Coached by Dukkha */
#include <stdio.h>

int main() {
	int n, m, k, i, j;

	scanf("%d%d%d", &n, &m, &k);
	printf("%d\n", m * (m - 1) / 2);
	for (i = 0; i < m; i++)
		for (j = i + 1; j < m; j++)
			if (k == 0)
				printf("%d %d\n", i + 1, j + 1);
			else
				printf("%d %d\n", j + 1, i + 1);
	return 0;
}


/*
#include<stdio.h>
int ans[1005], total[1005], count;

void descension(int n,  int m, int arr[n][m])
{
    count = 0;
    int k = 0;
    for(int I = 0;I < n; ++I)
    {
        for(int i = 0;i < m; ++i)
        {
            int temp = i;
            for(int j = 0;j < m; ++j)
            {
                if((arr[I][i] > arr[I][j]) && i > j)
                {
                    temp = j;
                }
                else if((arr[I][j] > arr[I][i]) && j > i)
                {
                    temp = j;
                }
            }
            if(temp != i)
            {
                printf("In array %d: ", I + 1);
                printf("%d %d are swapped\n", i + 1, temp + 1);
                total[k++] = i + 1;
                total[k++] = temp + 1;
                int t = arr[I][i];
                arr[I][i] = arr[I][temp];
                arr[I][temp] = t;
                ++count;

            }
        }
    }
}

void ascension(int n,  int m, int arr[n][m])
{
    count = 0;
    int k = 0;
    for(int I = 0;I < n; ++I)
    {
        for(int i = 0;i < m; ++i)
        {
            int temp = i;
            for(int j = 0;j < m; ++j)
            {
                if((arr[I][i] > arr[I][j]) && i < j)
                {
                    temp = j;
                }
                else if((arr[I][j] > arr[I][i]) && j < i)
                {
                    temp = j;
                }
            }
            if(temp != i)
            {
                printf("In array %d: ", I + 1);
                printf("%d %d are swapped\n", i + 1, temp + 1);
                total[k++] = i + 1;
                total[k++] = temp + 1;
                int t = arr[I][i];
                arr[I][i] = arr[I][temp];
                arr[I][temp] = t;
                ++count;

            }
        }
    }
}

int main()
{
    int n, m, k;
    scanf("%d%d%d", &n,&m,&k);
    int arr[n][m];
    for(int i = 0;i < n; ++i)
    {
        for(int j = 0;j < m; ++j)
        {
            scanf("%d", &arr[i][j]);
        }
    }

    if(k == 0)
        ascension(n, m, arr);
    else
        descension(n, m, arr);
    for(int i = 0;i < n; ++i)
    {
        for(int j = 0;j < m; ++j)
        {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    printf("%d\n", count);
    for(int K = 0;K < count * 2; K += 2)
    {
        printf("%d %d\n", total[K], total[K + 1]);
    }

}

*/

#include <stdio.h>

int m;
int a[1000][1000], b[1000][1000];

int main()
{
    int n, m, k;
    scanf("%d %d %d", &n, &m, &k);

    for(int i=0; i<n; i++)
        for(int j=0; j<m; j++)
            scanf("%d", &a[i][j]);

    printf("%d\n", (m*(m-1))/2);
    if(!k)
    {
        for(int i=1; i<m; i++)
            for(int j=i+1; j<=m; j++)
                printf("%d %d\n", i, j);
    }
    else
    {
        for(int i=1; i<m; i++)
            for(int j=i+1; j<=m; j++)
                printf("%d %d\n", j, i);
    }

    return 0;
}


#include<stdio.h>
int ans[1005], total[1005], count;

void descension(int n,  int m, int arr[n][m])
{
    count = 0;
    int k = 0;
    for(int I = 0;I < n; ++I)
    {
        for(int i = 0;i < m; ++i)
        {
            int temp = i;
            for(int j = 0;j < m; ++j)
            {
                if((arr[I][i] > arr[I][j]) && i > j)
                {
                    temp = j;
                }
                else if((arr[I][j] > arr[I][i]) && j > i)
                {
                    temp = j;
                }
            }
            if(temp != i)
            {
                printf("In array %d: ", I + 1);
                printf("%d %d are swapped\n", i + 1, temp + 1);
                total[k++] = i + 1;
                total[k++] = temp + 1;
                int t = arr[I][i];
                arr[I][i] = arr[I][temp];
                arr[I][temp] = t;
                ++count;

            }
        }
    }
}

void ascension(int n,  int m, int arr[n][m])
{
    count = 0;
    int k = 0;
    for(int I = 0;I < n; ++I)
    {
        for(int i = 0;i < m; ++i)
        {
            int temp = i;
            for(int j = 0;j < m; ++j)
            {
                if((arr[I][i] > arr[I][j]) && i < j)
                {
                    temp = j;
                }
                else if((arr[I][j] > arr[I][i]) && j < i)
                {
                    temp = j;
                }
            }
            if(temp != i)
            {
                printf("In array %d: ", I + 1);
                printf("%d %d are swapped\n", i + 1, temp + 1);
                total[k++] = i + 1;
                total[k++] = temp + 1;
                int t = arr[I][i];
                arr[I][i] = arr[I][temp];
                arr[I][temp] = t;
                ++count;

            }
        }
    }
}

int main()
{
    int n, m, k;
    scanf("%d%d%d", &n,&m,&k);
    int arr[n][m];
    for(int i = 0;i < n; ++i)
    {
        for(int j = 0;j < m; ++j)
        {
            scanf("%d", &arr[i][j]);
        }
    }

    if(k == 0)
        ascension(n, m, arr);
    else
        descension(n, m, arr);
    for(int i = 0;i < n; ++i)
    {
        for(int j = 0;j < m; ++j)
        {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    printf("%d\n", count);
    for(int K = 0;K < count * 2; K += 2)
    {
        printf("%d %d\n", total[K], total[K + 1]);
    }

}


#include<stdio.h>
int main()
{
	int n,m,k,x;
	scanf("%d%d%d",&n,&m,&k);
	for(int i=0;i<(n*m);i++)
		scanf("%d",&x);
	printf("%d\n",(m*(m-1))/2);
	for(int i=1;i<=m;i++)
	{
		for(int j=i+1;j<=m;j++)
		{
			if(!k)
				printf("%d %d\n",i,j);
			else
				printf("%d %d\n",j,i);
		}
	}
}


#include <stdio.h>
#include <stdlib.h>

typedef struct IndicesPair
{
	int indexA;
	int indexB;
	struct IndicesPair *next;
} *IndicesPair;

typedef struct IndicesPairQueue
{
	int count;
	struct IndicesPair *head;
	struct IndicesPair *tail;
} *IndicesPairQueue;

int** receiveData(int n, int m, int k);
IndicesPair constructIndicesPair(int a, int b);
void diposeIndicesPair(IndicesPair pair);
void enqueue(IndicesPairQueue queue, IndicesPair pair);
IndicesPair dequeue(IndicesPairQueue queue);
IndicesPairQueue sortMultipleArray(int **toSort, int n, int m, int k);

int main()
{
	int n, m, k;

	scanf("%d %d %d", &n, &m, &k);

	IndicesPairQueue queue = sortMultipleArray(receiveData(n, m, k), n, m, k);

	printf("%d\n", queue->count);

	IndicesPair pair;

	while (1)
	{
		pair = dequeue(queue);
		if (pair == NULL)
			break;
		printf("%d %d\n", pair->indexA, pair->indexB);
	}

	return 0;
}

int** receiveData(int n, int m, int k)
{

	int **toSort = malloc(sizeof(int*)*n);
	int i;

	for (i = 0; i < n; i++)
		toSort[i] = malloc(sizeof(int)*m);

	int j;

	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			scanf("%d", toSort[i]+j);

	return toSort;
}

IndicesPair constructIndicesPair(int a, int b)
{
	IndicesPair pair = malloc(sizeof(struct IndicesPair));

	pair->indexA = a;
	pair->indexB = b;

	return pair;
}

void diposeIndicesPair(IndicesPair pair)
{
	free(pair);
}

void enqueue(IndicesPairQueue queue, IndicesPair pair)
{
	if (queue->tail != NULL)
	{
		queue->tail->next = pair;
		queue->count++;
	}
	queue->tail = pair;

	if (queue->head == NULL)
	{
		queue->count = 1;
		queue->head = queue->tail;
	}
}

IndicesPair dequeue(IndicesPairQueue queue)
{
	IndicesPair res = queue->head;

	if (queue->head != NULL)
	{
		queue->head = queue->head->next;
		queue->count--;
	}
	else
		queue->tail = queue->head;

	return res;
}

IndicesPairQueue sortMultipleArray(int **toSort, int n, int m, int k)
{
	int row, col, pos, ptrRow;
	int maxOrMinPos, tmp;
	IndicesPairQueue queue = malloc(sizeof(struct IndicesPairQueue));

	for (row = 0; row < n; row++)
	{
		for (col = 0; col < m; col++)
		{
			maxOrMinPos = col;

			for (pos = col+1; pos < m; pos ++)
			{
				if ((!k && toSort[row][pos] < toSort[row][maxOrMinPos]) || \
					   	(k && toSort[row][pos] > toSort[row][maxOrMinPos]))
					maxOrMinPos = pos;
			}

			if (col == maxOrMinPos)
				continue;

			tmp = toSort[row][col];
			toSort[row][col] = toSort[row][maxOrMinPos];
			toSort[row][maxOrMinPos] = tmp;

			enqueue(queue, constructIndicesPair(col+1, maxOrMinPos+1));

			for (ptrRow = row + 1; ptrRow < n; ptrRow++)
			{
				if (((k) && (toSort[ptrRow][col] < toSort[ptrRow][maxOrMinPos])) || \
						((!k) && (toSort[ptrRow][col] > toSort[ptrRow][maxOrMinPos])))
				{
					tmp = toSort[ptrRow][col];
					toSort[ptrRow][col] = toSort[ptrRow][maxOrMinPos];
					toSort[ptrRow][maxOrMinPos] = tmp;
				}
			}
		}

	}

	return queue;
}


#include <stdio.h>
#include <stdlib.h>

typedef struct IndicesPair
{
	int indexA;
	int indexB;
	struct IndicesPair *next;
} *IndicesPair;

typedef struct IndicesPairQueue
{
	int count;
	struct IndicesPair *head;
	struct IndicesPair *tail;
} *IndicesPairQueue;

int** receiveData(int n, int m, int k);
IndicesPair constructIndicesPair(int a, int b);
void diposeIndicesPair(IndicesPair pair);
void enqueue(IndicesPairQueue queue, IndicesPair pair);
IndicesPair dequeue(IndicesPairQueue queue);
void initQueue(IndicesPairQueue queue);
IndicesPairQueue sortMultipleArray(int **toSort, int n, int m, int k);

int main()
{
	int n, m, k;

	scanf("%d %d %d", &n, &m, &k);

	IndicesPairQueue queue = sortMultipleArray(receiveData(n, m, k), n, m, k);

	printf("%d\n", queue->count);

	IndicesPair pair;

	while (1)
	{
		pair = dequeue(queue);
		if (pair == NULL)
			break;
		printf("%d %d\n", pair->indexA, pair->indexB);
	}

	return 0;
}

int** receiveData(int n, int m, int k)
{

	int **toSort = malloc(sizeof(int*)*n);
	int i;

	for (i = 0; i < n; i++)
		toSort[i] = malloc(sizeof(int)*m);

	int j;

	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			scanf("%d", toSort[i]+j);

	return toSort;
}

IndicesPair constructIndicesPair(int a, int b)
{
	IndicesPair pair = malloc(sizeof(struct IndicesPair));

	pair->indexA = a;
	pair->indexB = b;

	return pair;
}

void diposeIndicesPair(IndicesPair pair)
{
	free(pair);
}

void enqueue(IndicesPairQueue queue, IndicesPair pair)
{
	if (queue->tail != NULL)
	{
		queue->tail->next = pair;
		queue->count++;
	}
	queue->tail = pair;

	if (queue->head == NULL)
	{
		queue->count = 1;
		queue->head = queue->tail;
	}
}

IndicesPair dequeue(IndicesPairQueue queue)
{
	IndicesPair res = queue->head;

	if (queue->head != NULL)
	{
		queue->head = queue->head->next;
		queue->count--;
	}
	else
		queue->tail = queue->head;

	return res;
}

void initQueue(IndicesPairQueue queue)
{
	queue->count = 0;
	queue->head = NULL;
	queue->tail = NULL;
}

IndicesPairQueue sortMultipleArray(int **toSort, int n, int m, int k)
{
	int row, col, pos, ptrRow;
	int maxOrMinPos, tmp;
	IndicesPairQueue queue = malloc(sizeof(struct IndicesPairQueue));
	initQueue(queue);

	for (row = 0; row < n; row++)
	{
		for (col = 0; col < m; col++)
		{
			maxOrMinPos = col;

			for (pos = col+1; pos < m; pos ++)
			{
				if ((!k && toSort[row][pos] < toSort[row][maxOrMinPos]) || \
					   	(k && toSort[row][pos] > toSort[row][maxOrMinPos]))
					maxOrMinPos = pos;
			}

			if (col == maxOrMinPos)
				continue;

			tmp = toSort[row][col];
			toSort[row][col] = toSort[row][maxOrMinPos];
			toSort[row][maxOrMinPos] = tmp;

			if (!k)
				enqueue(queue, constructIndicesPair(col+1, maxOrMinPos+1));
			else if (k)
				enqueue(queue, constructIndicesPair(maxOrMinPos+1, col+1));

			for (ptrRow = row + 1; ptrRow < n; ptrRow++)
			{
				if (((k) && (toSort[ptrRow][col] < toSort[ptrRow][maxOrMinPos])) || \
						((!k) && (toSort[ptrRow][col] > toSort[ptrRow][maxOrMinPos])))
				{
					tmp = toSort[ptrRow][col];
					toSort[ptrRow][col] = toSort[ptrRow][maxOrMinPos];
					toSort[ptrRow][maxOrMinPos] = tmp;
				}
			}
		}

	}

	return queue;
}


#include <stdio.h>
#include <stdlib.h>

typedef struct IndicesPair
{
	int indexA;
	int indexB;
	struct IndicesPair *next;
} *IndicesPair;

typedef struct IndicesPairQueue
{
	int count;
	struct IndicesPair *head;
	struct IndicesPair *tail;
} *IndicesPairQueue;

int** receiveData(int n, int m, int k);
IndicesPair constructIndicesPair(int a, int b);
void diposeIndicesPair(IndicesPair pair);
void enqueue(IndicesPairQueue queue, IndicesPair pair);
IndicesPair dequeue(IndicesPairQueue queue);
void initQueue(IndicesPairQueue queue);
IndicesPairQueue sortMultipleArray(int **toSort, int n, int m, int k);

int main()
{
	int n, m, k;

	scanf("%d %d %d", &n, &m, &k);

	IndicesPairQueue queue = sortMultipleArray(receiveData(n, m, k), n, m, k);

	printf("%d\n", queue->count);

	IndicesPair pair;

	while (1)
	{
		pair = dequeue(queue);
		if (pair == NULL)
			break;
		printf("%d %d\n", pair->indexA, pair->indexB);
	}

	return 0;
}

int** receiveData(int n, int m, int k)
{

	int **toSort = malloc(sizeof(int*)*n);
	int i;

	for (i = 0; i < n; i++)
		toSort[i] = malloc(sizeof(int)*m);

	int j;

	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++)
			scanf("%d", toSort[i]+j);

	return toSort;
}

IndicesPair constructIndicesPair(int a, int b)
{
	IndicesPair pair = malloc(sizeof(struct IndicesPair));

	pair->indexA = a;
	pair->indexB = b;

	return pair;
}

void diposeIndicesPair(IndicesPair pair)
{
	free(pair);
}

void enqueue(IndicesPairQueue queue, IndicesPair pair)
{
	if (queue->tail != NULL)
	{
		queue->tail->next = pair;
		queue->count++;
	}
	queue->tail = pair;

	if (queue->head == NULL)
	{
		queue->count = 1;
		queue->head = queue->tail;
	}
}

IndicesPair dequeue(IndicesPairQueue queue)
{
	IndicesPair res = queue->head;

	if (queue->head != NULL)
	{
		queue->head = queue->head->next;
		queue->count--;
	}
	else
		queue->tail = queue->head;

	return res;
}

void initQueue(IndicesPairQueue queue)
{
	queue->count = 0;
	queue->head = NULL;
	queue->tail = NULL;
}

IndicesPairQueue sortMultipleArray(int **toSort, int n, int m, int k)
{
	int row, col, pos, ptrRow;
	int maxOrMinPos, tmp;
	IndicesPairQueue queue = malloc(sizeof(struct IndicesPairQueue));
	initQueue(queue);

	for (row = 0; row < n; row++)
	{
		for (col = 0; col < m; col++)
		{
			maxOrMinPos = col;

			for (pos = col+1; pos < m; pos ++)
			{
				if ((!k && toSort[row][pos] < toSort[row][maxOrMinPos]) || \
					   	(k && toSort[row][pos] > toSort[row][maxOrMinPos]))
					maxOrMinPos = pos;
			}

			if (col == maxOrMinPos)
				continue;

			tmp = toSort[row][col];
			toSort[row][col] = toSort[row][maxOrMinPos];
			toSort[row][maxOrMinPos] = tmp;

			enqueue(queue, constructIndicesPair(col+1, maxOrMinPos+1));

			for (ptrRow = row + 1; ptrRow < n; ptrRow++)
			{
				if (((k) && (toSort[ptrRow][col] < toSort[ptrRow][maxOrMinPos])) || \
						((!k) && (toSort[ptrRow][col] > toSort[ptrRow][maxOrMinPos])))
				{
					tmp = toSort[ptrRow][col];
					toSort[ptrRow][col] = toSort[ptrRow][maxOrMinPos];
					toSort[ptrRow][maxOrMinPos] = tmp;
				}
			}
		}

	}

	return queue;
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	reader = bufio.NewReader(os.Stdin)
)

func main() {
	var n, m, k int
	fmt.Fscan(reader, &n, &m, &k)
	fmt.Println(m * (m - 1) / 2)
	if k == 0 {
		for i := 0; i < m; i++ {
			for j := 0; j < m-i-1; j++ {
				fmt.Println(j+1, j+2)
			}
		}
	} else {
		for i := 0; i < m; i++ {
			for j := m - 1; j >= 1+i; j-- {
				fmt.Println(j+1, j)
			}
		}
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	reader = bufio.NewReader(os.Stdin)
)

func main() {
	var n, m, k int
	fmt.Fscan(reader, &n, &m, &k)
	fmt.Println(m * (m - 1) / 2)
	if k == 0 {
		for i := 0; i < m; i++ {
			for j := i; j+1 < m; j++ {
				fmt.Println(j+1, j+2)
			}
		}
	} else {
		for i := m - 1; i >= 0; i-- {
			for j := i; j >= 1; j-- {
				fmt.Println(j+1, j)
			}
		}
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
)

var (
	reader = bufio.NewReader(os.Stdin)
)

func main() {
	var n, m, k int
	fmt.Fscan(reader, &n, &m, &k)
	fmt.Println(m * (m - 1) / 2)
	if k == 0 {
		for i := 0; i < m; i++ {
			for j := 0; j < m-i; j++ {
				fmt.Println(j+1, j+2)
			}
		}
	} else {
		for i := 0; i < m; i++ {
			for j := m - 1; j >= 1+i; j-- {
				fmt.Println(j+1, j)
			}
		}
	}
}


package main
import "fmt"

func main(){
	var n,m,k int
	fmt.Scan(&n,&m,&k)
	s:=make([]int,n)
	for i:=0;i<n;i++ { fmt.Scan(&s[i])}

	fmt.Println(m*(m-1)/2)
	for u:=1; u<=m; u++ {
		for i:= u+1; i<=m; i++{
			if k==0 {
				fmt.Println(u,"",i)
			}else{
				fmt.Println(i,"",u)
			}
		}
	}

}


package main
import "fmt"

func main(){
	var n,m,k int
	fmt.Scan(&n,&m,&k)
	s:=make([]int,n)
	for i:=0;i<n;i++ { fmt.Scan(&s[i])}

	fmt.Println(m*(m-1)/2)
	for u:=1; u<=m; u++ {
		for i:= u+1; i<=m; i++{
			if k==0 {
				fmt.Println(u,i)
			}else{
				fmt.Println(i,u)
			}
		}
	}

}


package main
import "fmt"

func main(){
	var n,m,k int
	fmt.Scan(&n,&m,&k)
	s:=make([]int,n)
	for i:=0;i<n;i++ { fmt.Scan(&s[i])}

	fmt.Println(m*(m-1)/2)
	for u:=0; u<=m; u++ {
		for i:= u+1; i<=m; i++{
			if k==0 {
				fmt.Println(u,"",i)
			}else{
				fmt.Println(i,"",u)
			}
		}
	}

}


// 384B
package main

import (
	"fmt"
)

func main() {
	var n, m, k int
	fmt.Scan(&n, &m, &k)
	fmt.Println((m - 1) * (m) / 2)
	for i := 1; i <= m; i++ {
		for j := i + 1; j <= m; j++ {
			if k == 0 {
				fmt.Println(i, j)
			} else {
				fmt.Println(j, i)
			}
		}
	}
}


<?php
error_reporting("off");
//384B: Multitasking
list($n, $m, $k) = explode(" ", trim(fgets(STDIN)));
echo $m * ($m - 1) / 2;
echo "\n";
for ($i = 1; $i <= $m; $i++) {
    for ($j = $i + 1; $j <= $m; $j++) {
        echo $i." ".$j."\n";
    }
}
?>


def s(n,m,k):
	print(m*(m-1)//2)
	for i in range(1,m):
		for j in range(i+1,m+1):
			if k:
				print(j,i)
			else:
				print(i,j)
s(*map(int,input().split()))


from sys import stdin,stdout
import math
from collections import Counter,deque
L=lambda:list(map(int, stdin.readline().strip().split()))
M=lambda:map(int, stdin.readline().strip().split())
I=lambda:int(stdin.readline().strip())
IN=lambda:stdin.readline().strip()
C=lambda:stdin.readline().strip().split()
mod=1000000007
#Keymax = max(Tv, key=Tv.get)
def s(a):print(" ".join(list(map(str,a))))
#______________________-------------------------------_____________________#
#I_am_pavan
def solve():
    n,m,k=M()
    print(m*(m-1)//2)
    for i in range(1,m+1):
        for j in range(i+1,m+1):
            if k:
                print(j,i)
            else:print(i,j)
for i in range(1):
    solve()


from collections import *
from math import *

n,m,k = map(int,input().split())
a = []
if(k == 0):
	for i in range(m):
		for j in range(i+1,m):
			a.append([i+1,j+1])
else:
	for i in range(m-1,-1,-1):
		for j in range(i-1,-1,-1):
			a.append([i+1,j+1])
print(len(a))
for i in a:
	print(*i)


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

n,m,o=value()
a=[]
for i in range(n):
    a.append(array())

ans=[]
for i in range(1,m+1):
    for j in range(1,m+1):

        ok=False
        for k in range(n):
            if(a[k][i-1]>a[k][j-1] and o==1):
                ok=True
            if(a[k][i-1]<a[k][j-1] and o==0):
                ok=True
        if(ok and (j,i) not in ans):
            ans.append((i,j))

print(len(ans))
for i in ans:
    print(*i)


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=1000000007
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

n,m,o=value()
for i in range(n):
    input()

print(m*(m-1)//2)
for i in range(1,m+1):
    for j in range(i+1,m+1):
        if(o==0):
            print(i,j)
        else:
            print(m-i+1,m-j+1)