//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (2000010)
int n,h[N]{INF},d[N],s[N],tp,l[N],m,b[N],b2[N];
vector<int>q[N];
long long ans,cnt;
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)d[i]=Rd(h[i]);
	sort(d+1,d+n+1),m=unique(d+1,d+n+1)-d-1;
	Frn1(i,1,n)if((h[i+n]=h[i]=lower_bound(d+1,d+m+1,h[i])-d)==m)++cnt;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		l[i]=s[tp],s[++tp]=i;
		if(i>n&&l[i]>i-n)++ans;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		++b[h[i]];
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=b[h[i]]-1,q[min(i+n,s[tp])-1].push_back(i);
		}
		s[++tp]=i;
	}
	Frn1(i,1,n<<1){
		++b2[h[i]];
		for(int j:q[i])ans+=b2[h[j]]-b[h[j]];
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]==m-1)++cnt;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (1000010)
#define M ((l+r)>>1)
int n,h[N]{INF},rt[N],sz,s[N],tp,ans,mx,cnt,mx2;
struct{int ls,rs,v;}t[N<<3];
int mdf(int u,int l,int r,int k);
int qry(int u,int v,int l,int r,int k);
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)(h[i+n]=Rd(h[i]))>mx?(mx=h[i],cnt=1):h[i]==mx?++cnt:0;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		rt[i]=mdf(rt[i-1],0,n<<1,s[tp]);
		s[++tp]=i;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=qry(rt[i],rt[min(s[tp],i+n)-1],1,n<<1,i);
		}
		s[++tp]=i;
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]<mx)h[i]>mx2?(mx2=h[i],cnt=1):h[i]==mx2?++cnt:0;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}
int mdf(int u,int l,int r,int k){
	int re(++sz);t[re]=t[u];
	if(l==r){++t[re].v;return re;}
	k<=M?t[re].ls=mdf(t[u].ls,l,M,k):t[re].rs=mdf(t[u].rs,M+1,r,k);
	t[re].v=t[t[re].ls].v+t[t[re].rs].v;
	return re;
}
int qry(int u,int v,int l,int r,int k){
	if(r<=k)return t[v].v-t[u].v;
	if(l>k||t[u].v==t[v].v)return 0;
	return qry(t[u].ls,t[v].ls,l,M,k)+qry(t[u].rs,t[v].rs,M+1,r,k);
}


//This program is written by Brian Peng.
#pragma GCC optimize("Ofast","inline","no-stack-protector")
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define Rd(a) (a=read())
#define Gc(a) (a=getchar())
#define Pc(a) putchar(a)
int read(){
	register int x;register char c(getchar());register bool k;
	while(!isdigit(c)&&c^'-')if(Gc(c)==EOF)exit(0);
	if(c^'-')k=1,x=c&15;else k=x=0;
	while(isdigit(Gc(c)))x=(x<<1)+(x<<3)+(c&15);
	return k?x:-x;
}
void wr(register int a){
	if(a<0)Pc('-'),a=-a;
	if(a<=9)Pc(a|'0');
	else wr(a/10),Pc((a%10)|'0');
}
signed const INF(0x3f3f3f3f),NINF(0xc3c3c3c3);
long long const LINF(0x3f3f3f3f3f3f3f3fLL),LNINF(0xc3c3c3c3c3c3c3c3LL);
#define Ps Pc(' ')
#define Pe Pc('\n')
#define Frn0(i,a,b) for(register int i(a);i<(b);++i)
#define Frn1(i,a,b) for(register int i(a);i<=(b);++i)
#define Frn_(i,a,b) for(register int i(a);i>=(b);--i)
#define Mst(a,b) memset(a,b,sizeof(a))
#define File(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout)
#define N (2000010)
int n,h[N]{INF},s[N],tp,l[N],m,b[N],b2[N],ans,cnt;
struct D{int a,i,b;}d[N];
vector<int>q[N];
signed main(){
	h[Rd(n)<<1|1]=INF;
	Frn1(i,1,n)d[i]={read(),i};
	sort(d+1,d+n+1,[](D a,D b){return a.a<b.a;});
	Frn1(i,1,n)d[i].b=d[i].a>d[i-1].a?++m:m;
	sort(d+1,d+n+1,[](D a,D b){return a.i<b.i;});
	Frn1(i,1,n)if((h[i+n]=h[i]=d[i].b)==m)++cnt;
	Frn1(i,1,n<<1){
		while(h[i]>=h[s[tp]])--tp;
		l[i]=s[tp],s[++tp]=i;
		if(i>n&&l[i]>i-n)++ans;
	}
	s[tp=0]=n<<1|1;
	Frn_(i,n<<1,1){
		++b[h[i]];
		while(h[i]>=h[s[tp]])--tp;
		if(i<=n){
			if(s[tp]<i+n)++ans;
			ans+=b[h[i]]-1,q[min(i+n,s[tp])-1].push_back(i);
		}
		s[++tp]=i;
	}
	Frn1(i,1,n<<1){
		++b2[h[i]];
		for(int j:q[i])ans+=b2[h[j]]-b[h[j]];
	}
	if(cnt==1){
		cnt=0;
		Frn1(i,1,n)if(h[i]==m-1)++cnt;
		ans-=cnt;
	}else ans-=(cnt*(cnt-1))>>1;
	wr(ans),exit(0);
}


#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=1000000+7;
int n,h[maxn],l[maxn],r[maxn],c[maxn];
int main(){
    //freopen("in","r",stdin);
    scanf("%d",&n);
    int maxs=-1,maxi;
    for(int i=0;i<n;++i){
      scanf("%d",&h[i]);
      if(h[i]>maxs){
        maxs=h[i];maxi=i;
      }
    }
    reverse(h,h+maxi);
    reverse(h+maxi,h+n);
    reverse(h,h+n);
    h[n]=maxs;
    for(int i=1;i<n;++i){
      l[i]=i-1;
      while(l[i]>0&&h[i]>=h[l[i]]){
        l[i]=l[l[i]];
      }
    }
    for(int i=n-1;i>=0;--i){
      r[i]=i+1;
      while(r[i]<n&&h[i]>h[r[i]]){
        r[i]=r[r[i]];
      }
      if(r[i]<n&&h[i]==h[r[i]]){
        c[i]=c[r[i]]+1;
        r[i]=r[r[i]];
      }
    }
    long long ans=0;
    for(int i=1;i<n;++i){
        ans+=c[i];
        ans+=2;
        if(l[i]==0&&r[i]==n)ans--;
    }
    cout<<ans;
}


#include <cstdio>
#include <set>
#include <algorithm>
using namespace std;
const int maxn=1000000+7;
int n,h[maxn],l[maxn],r[maxn],c[maxn];
int main(){
    //freopen("in","r",stdin);
    scanf("%d",&n);
    int maxs=-1,maxi;
    for(int i=0;i<n;++i){
      scanf("%d",&h[i]);
      if(h[i]>maxs){
        maxs=h[i];maxi=i;
      }
    }
    reverse(h,h+maxi);
    reverse(h+maxi,h+n);
    reverse(h,h+n);
    h[n]=maxs;
    for(int i=1;i<n;++i){
      l[i]=i-1;
      while(l[i]>0&&h[i]>=h[l[i]]){
        l[i]=l[l[i]];
      }
    }
    for(int i=n-1;i>=0;--i){
      r[i]=i+1;
      while(r[i]<n&&h[i]>h[r[i]]){
        r[i]=r[r[i]];
      }
      if(r[i]<n&&h[i]==h[r[i]]){
        c[i]=c[r[i]]+1;
        r[i]=r[r[i]];
      }
    }
    long long ans=0;
    for(int i=1;i<n;++i){
        ans+=c[i];
        ans+=2;
        if(l[i]==0&&r[i]==n)ans--;
    }
    printf("%l64d",ans)  ;
}


#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=1000000+7;
int n,h[maxn],l[maxn],r[maxn],c[maxn],th[maxn];
int main(){
    //freopen("in","r",stdin);
    cin>>n;
    int maxs=-1,maxi;
    for(int i=0;i<n;++i){
      cin>>th[i];
      if(h[i]>maxs){
        maxs=th[i];maxi=i;
      }
    }
    h[n]=maxs;
    for(int i=0;i<n;++i){
      h[i]=th[maxi++];
      maxi%=n;
    }
    for(int i=1;i<n;++i){
      l[i]=i-1;
      while(l[i]>0&&h[i]>=h[l[i]]){
        l[i]=l[l[i]];
      }
    }
    for(int i=n-1;i>=0;--i){
      r[i]=i+1;
      while(r[i]<n&&h[i]>h[r[i]]){
        r[i]=r[r[i]];
      }
      if(r[i]<n&&h[i]==h[r[i]]){
        c[i]=c[r[i]]+1;
        r[i]=r[r[i]];
      }
    }
    long long ans=0;
    for(int i=1;i<n;++i){
        ans+=c[i];
        ans+=2;
        if(l[i]==0&&r[i]==n)ans--;
    }
    cout<<ans;
}


#include<stdio.h>
int main()
{int n,str[205],ans=0;
scanf("%d",&n);
for(int i=1;i<=2*n;i++)
	scanf("%d",&str[i]);
for(int i=1;i<2*n;i+=2)
for(int j=i+1;j<=2*n;j++)
if(str[j]==str[i])
	{for(int k=j;k>i+1;k--)
	str[k]=str[k-1];
str[i+1]=str[i];
ans+=j-i-1;
}
printf("%d",ans);}


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <set>
#include <math.h>
#include <vector>
#include <algorithm>

#define MAXN 205

typedef long long ll;

using namespace std;

int A[MAXN];

int main()
{
	//freopen("in.txt", "r", stdin);

	int n;
	scanf("%d", &n);
	n *= 2;

	for (int i = 1; i <= n; i++)scanf("%d", &A[i]);

	int res = 0;
	for (int i = 1; i <= n; i += 2){
		for (int j = i + 1; j <= n; j++){
			if (A[j] == A[i]){
				res += (j - i - 1);
				for (int k = j - 1; k > i; k--){
					swap(A[k], A[k + 1]);
				}
			}
		}
	}

	printf("%d\n", res);

	return 0;
}


#define _USE_MATH_DEFINES
#include <assert.h>
#include <math.h>
#include <algorithm>
#include <vector>
#include <string>
#include <list>
#include <set>
#include <map>
#include <unordered_map>
#include <queue>
#include <sstream>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;
typedef long long     ll;
typedef unsigned int  UInt;
#define ALL(a)          (a).begin(), (a).end()
#define FOR(i,a,b)      for(int i = a;   i <  (int)(b); ++i)
#define FOR_REV(i,a,b)  for(int i = b-1; i >= (int)(a); --i)
#define FOR_EACH(it,a)  for(remove_reference<decltype(a)>::type::iterator it = (a).begin(); it != (a).end(); ++it)
#define FOR_EACH_REV(it,a) for(remove_reference<decltype(a)>::type::reverse_iterator it = (a).rbegin(); it != (a).rend(); ++it)
#define FOR_EACH_CONST(it,a) for(remove_reference<decltype(a)>::type::const_iterator it = (a).begin(); it != (a).end(); ++it)
#define FOR_EACH_CONST_REV(it,a) for(remove_reference<decltype(a)>::type::const_reverse_iterator it = (a).rbegin(); it != (a).rend(); ++it)
template<class T> inline T   sqr(T v)  { return v * v; }
template<class T> inline int sign(T v) { return v == 0 ? 0 : (v > 0 ? 1 : -1); }
template<class T> inline int get_bit(T v, int bit_index) { return (v >> bit_index) & 1; } //return {0,1}
template<class T> inline T   gcd(T a, T b) { while(b) { T t = b; b   = a % b; a   = t; } return a; }

#define IN_INT(a)            int a;       is >> a;
#define IN_INT2(a,b)         int a,b;     is >> a >> b;
#define IN_INT3(a,b,c)       int a,b,c;   is >> a >> b >> c;
#define IN_INT4(a,b,c,d)     int a,b,c,d; is >> a >> b >> c >> d;
#define IN_LL(a)             ll a;        is >> a;
#define IN_LL2(a,b)          ll a,b;      is >> a >> b;
#define IN_LL3(a,b,c)        ll a,b,c;    is >> a >> b >> c;
#define IN_LL4(a,b,c,d)      ll a,b,c,d;  is >> a >> b >> c >> d;
#define IN_STR(s)            string s;    is >> s;

//////////////////////////////////////////////////////////////////////////

istream& input(bool release_tie = false)
{
  ios_base::sync_with_stdio(false);
#ifdef INPUT_FROM_FILE
  static ifstream is("CodeForces/input.txt");
  return is;
#endif
  if (release_tie)
    cin.tie(NULL);
  return cin;
}

ostream& output(bool release_tie = false)
{
  cout << setprecision(15);
  if (release_tie)
    cout.tie(NULL);
  return cout;
}

template <typename T>
void init_v2(vector<vector<T>>& v, int lx, int ly, const T& val = T())
{
  v.resize(lx);
  FOR (i,0,lx)
    v[i].resize(ly, val);
};

//////////////////////////////////////////////////////////////////////////

template <typename T>
class Point2
{
public:
  Point2(){}
  Point2(T x_, T y_):x(x_), y(y_) {}

  bool       operator ==(const Point2<T>&) const;
  bool       operator !=(const Point2<T>&) const;

  Point2<T>& operator +=(const Point2<T>&);
  Point2<T>& operator -=(const Point2<T>&);
  Point2<T>& operator /=(T);
  Point2<T>& operator *=(T);

  T length() const;
  T length_square() const;

public:
  T x;
  T y;
};

template<class T>
inline bool Point2<T>::operator == (const Point2<T>& p) const
{
  return x == p.x && y == p.y;
}

template<class T>
inline bool Point2<T>::operator != (const Point2<T>& p) const
{
  return x != p.x || y != p.y;
}

template<class T>
inline Point2<T>& Point2<T>::operator +=(const Point2<T>& r)
{
  x += r.x;
  y += r.y;
  return *this;
}

template<class T>
inline Point2<T>& Point2<T>::operator -=(const Point2<T>& r)
{
  x -= r.x;
  y -= r.y;
  return *this;
}

template<class T>
inline Point2<T>& Point2<T>::operator *=(T m)
{
  x *= m;
  y *= m;
  return *this;
}

template<class T>
inline Point2<T>& Point2<T>::operator /=(T val)
{
  x /= val;
  y /= val;
  return *this;
}

//////////////////////////////////////////////////////////////////////////

template<class T>
inline Point2<T> operator + (const Point2<T>& l, const Point2<T>& r)
{
  return Point2<T> (l.x+r.x, l.y+r.y);
}

template<class T>
inline Point2<T> operator - (const Point2<T>& l, const Point2<T>& r)
{
  return Point2<T> (l.x-r.x, l.y-r.y);
}

template<class T>
inline Point2<T> operator * (const Point2<T>& l, T m)
{
  return Point2<T> (l.x*m, l.y*m);
}

template<class T>
inline Point2<T> operator / (const Point2<T>& l, T val)
{
  return Point2<T> (l.x/val, l.y/val);
}

template<class T>
std::ostream& operator << (std::ostream& os, const Point2<T>& p)
{
  //os << "(" << p.x << "; " << p.y << ")";
  os << p.x << " " << p.y;
  return os;
}

template <typename T>
struct Point2Less
{
  bool operator()(const Point2<T>& l, const Point2<T>& r) const
  {
    return l.x < r.x || (l.x == r.x && l.y < r.y);
  }
};

typedef Point2<int>       Point2I;

//////////////////////////////////////////////////////////////////////////

template<class T, class FUNC_ADD, class FUNC_SUB>
class FenwickTree
{
public:
  void init(int n);
  void init(const vector<T>&);

  void set_value(int i, const T& v_new);
  void set_delta(int i, const T& delta); //!!! для некот-х ф-ций, типа sum, можно delta

  T func(int r) const; //вычислить функцию на [0,r]
  T func(int l, int r) const; //вычислить функцию на [l,r]

protected:
  vector<T> t; //значения ф-ций для спец-х отрезков
  vector<T> v; //значения элем-в массива
};

template<class T, class FUNC_ADD, class FUNC_SUB>
void FenwickTree<T, FUNC_ADD, FUNC_SUB>::init(int n)
{
  v.assign(n, 0);
  t.assign(n, 0); //!!!только для некот-х ф-ций верно: сумма, мин/макс
}

template<class T, class FUNC_ADD, class FUNC_SUB>
void FenwickTree<T, FUNC_ADD, FUNC_SUB>::init(const vector<T>& a)
{
  init(a.size());
  for (unsigned i = 0; i < a.size(); i++)
    set_value(i, a[i]);
}

template<class T, class FUNC_ADD, class FUNC_SUB>
void FenwickTree<T, FUNC_ADD, FUNC_SUB>::set_value(int i, const T& v_new)
{
  T& v_old = v[i]; //func(i,i); //нужно доп-но хранить значения элем-в или вычислять: v_old = func(i,i);
  for (int n = t.size(); i < n; i |= i+1)
    t[i] = FUNC_ADD()(FUNC_SUB()(t[i], v_old), v_new);
  v_old = v_new; //если хранить значения элем-в
}

template<class T, class FUNC_ADD, class FUNC_SUB>
void FenwickTree<T, FUNC_ADD, FUNC_SUB>::set_delta(int i, const T& delta) //!!! для некот-х ф-ций, типа sum, можно delta
{
  v[i] += delta;
  for (int n = t.size(); i < n; i |= i+1)
    t[i] = FUNC_ADD()(t[i], delta);
}

template<class T, class FUNC_ADD, class FUNC_SUB>
T FenwickTree<T, FUNC_ADD, FUNC_SUB>::func(int r) const //вычислить функцию на [0,r]
{
  T res = 0;
  for (; r >= 0; r &= r+1, --r)
    res = FUNC_ADD()(res, t[r]);
  return res;
}

template<class T, class FUNC_ADD, class FUNC_SUB>
T FenwickTree<T, FUNC_ADD, FUNC_SUB>::func(int l, int r) const //вычислить функцию на [l,r]
{
  return FUNC_SUB()(func(r), func(l-1));
}

template<class T> struct FuncAdd { T operator()(const T& a, const T& b) const { return a+b; } };
template<class T> struct FuncSub { T operator()(const T& a, const T& b) const { return a-b; } };

template<class T>
class FenwickTreeSum : public FenwickTree<T, FuncAdd<T>, FuncSub<T>>
{
public:
  FenwickTreeSum(int n) { this->init(n); }

  T sum(int r) const { return this->func(r); }
  T sum(int l, int r) const { return this->func(l, r); }
};

//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
////a
//void main()
//{
//  istream& is = input();
//  ostream& os = output();
//
//  IN_INT(n);
//  int c[] = {1, 5, 10, 20, 100};
//  int res=0;
//  FOR_REV (i,0,5)
//  {
//    res+=n/c[i];
//    n%=c[i];
//  }
//
//  os << res;
//}

//////////////////////////////////////////////////////////////////////////
////b
//void main()
//{
//  istream& is = input();
//  ostream& os = output();
//
//  IN_INT(n);
//
//  vector<int> a(n);
//  int m = INT_MAX;
//  FOR (i,0,n)
//  {
//    is >> a[i];
//  }
//  int i = min_element(ALL(a))-a.begin();
//  int pos = a[i]%n, t = a[i];
//  for (;;)
//  {
//    if (a[pos]<=t)
//    {
//      os<<pos+1;
//      return;
//    }
//    ++t;
//    pos=(pos+1)%n;
//  }
//  //os << res;
//}

//////////////////////////////////////////////////////////////////////////
////c - TODO
//
//int n,k;
//vector<vector<int>> a;
//map<int,Point2I> cars;
//vector<Point2I>  cdst;
//
//vector<pair<int,Point2I>> go_to_place(int car)
//{
//  Point2I pos = cars[car];
//  Point2I dst = cdst[car];
//  //static vector<int> prev[4];
//  //FOR (i,0,4)
//  //{
//  //  prev[i].clear();
//  //  prev[i].resize(n,-1);
//  //}
//  //static vector<Point2I> f;
//  //f.clear();
//  //f.push_back(cars[car]);
//
//  vector<pair<int,Point2I>> moves;
//  set<Point2I,Point2Less<int>> used;
//  while (dst.y != pos.y)
//  {
//    int dy = dst.y - pos.y;
//    Point2I p1 = pos;
//    p1.y+=sign(dy);
//    if (!a[p1.x][p1.y])
//    {
//      pos=p1;
//      moves.push_back(make_pair(car,p1));
//    }
//    else
//    {
//      p1 = pos;
//      int dx = p1.x ==1?1:-1;
//      p1.x+=dx;
//
//      if (!a[p1.x][p1.y]&&used.find(p1)==used.end())
//      {
//        pos=p1;
//        moves.push_back(make_pair(car,p1));
//        used.insert(p1);
//      }
//      else
//      {
//        return vector<pair<int,Point2I>>();
//      }
//    }
//  }
//
//  while (dst.x!=pos.x)
//  {
//    Point2I p1 = pos;
//    p1.x+=sign(dst.x-pos.x);
//    if (!a[p1.x][p1.y]||a[p1.x][p1.y]==car)
//    {
//      pos=p1;
//      moves.push_back(make_pair(car,p1));
//    }
//    else
//    {
//      return vector<pair<int,Point2I>>();
//    }
//  }
//
//  return moves;
//}
//
//void main()
//{
//  istream& is = input();
//  ostream& os = output();
//
//  is>>n>>k;
//  init_v2(a,4,n);
//  cdst.resize(k);
//
//  FOR (i,0,n)
//    FOR (j,0,n)
//  {
//      is >> a[i][j];
//      if (a[i][j])
//      {
//        if (i==1||i==2)
//          cars[a[i][j]] = Point2I(i,j);
//        else
//          cdst[a[i][j]] = Point2I(i,j);
//      }
//  }
//
//  vector<pair<int,Point2I>> res;
//
//  FOR_EACH (it,cars)
//  {
//    int car = it->first;
//    Point2I pos = it->second;
//    vector<pair<int,Point2I>> moves = go_to_place(car);
//    if (!moves.empty())
//    {
//      //cars.erase(it++);
//      a[pos.x][pos.y]=0;
//      res.insert(res.end(),ALL(moves));
//    }
//  }
//
//  if (res.empty()&&k==2*n)
//  {
//    os<<-1;
//    return;
//  }
//
//  FOR (i,1,3)
//    FOR (j,0,n)
//  {
//
//  }
//  //os << res;
//}

//////////////////////////////////////////////////////////////////////////
//d
void main()
{
  istream& is = input();
  ostream& os = output();

  IN_INT(n);

  vector<int> a(n<<1);
  map<int,vector<int>> m;
  FOR (i,0,n<<1)
  {
    is >> a[i];
    m[a[i]].push_back(i);
  }

  FenwickTreeSum<int> s(n<<1);
  FOR (i,0,n<<1)
    s.set_value(i,1);

  int res = 0;
  FOR (i,0,n<<1)
  {
    if (a[i])
    {
      res += s.sum(m[a[i]][0],m[a[i]][1]) - 2;
      s.set_value(m[a[i]][1],0);
      a[m[a[i]][1]] = 0;
    }
  }

  os << res;
}

//////////////////////////////////////////////////////////////////////////

//void main()
//{
//  istream& is = input();
//  ostream& os = output();
//
//  IN_INT(n);
//
//  //vector<int> a(n);
//  //FOR (i,0,n)
//  //  is >> a[i];
//
//  //os << res;
//}


#include <iostream>
#include <memory.h>
using namespace std;
const int nmax=200+5;
int ar[nmax];
int ar_b[nmax];
int main(){

	int i,j,k,n,ans,temp;
	scanf("%d",&n);
	for(i=0;i<2*n;i++){
		scanf("%d",&ar[i]);
		ar_b[i]=ar[i];
	}
	ans=0;
	for(i=0;i<n;i++){

		temp=ar[2*i];
		for(j=2*i+1;j<2*n;j++){
			if(temp==ar[j]){

				ans+=(j-2*i-1);

				for(k=2*i+1;k<=j;k++){
					ar_b[k]=ar[k];
				}
				ar[2*i+1]=ar[j];
				for(k=2*i+1;k<j;k++){
					ar[k+1]=ar_b[k];
				}
				for(k=2*i+1;k<=j;k++){
					ar_b[k]=ar[k];
				}
			}
		}
	}
	cout<<ans<<endl;
	return 0;
}


#include <iostream>
using namespace std;

int main() {
	int c[123456], k = 0;
	int n;
	cin >> n;
	for (int i = 0; i < 2*n; i+=2) {
		cin >> c[i]>>c[i+1];
	}
	for (int i = 0; i < 2*n-1; i+=2) {
		if (c[i]!=c[i+1]) {
			int l = i+1;
			while (c[l] != c[i]) { l++; }
			while (l != i + 1) { swap(c[l], c[l - 1]); l--; k++; }
		}
	}
	cout << k;

return 0;
}


#include <iostream>
using namespace std;
int a[210];
int main()
{
    int n,j,ans=0;
    cin>>n;
    for(int i=1;i<=2*n;++i) cin>>a[i];
    for(int i=2;i<=2*n;i+=2){
        for(j=i;j<=2*n;j++) if(a[j]==a[i-1]) break;
        for(;j>i;j--) swap(a[j],a[j-1]),ans++;
    }
    cout<<ans<<endl;
    return 0;
}


n=int(input())
a=list(map(int,input().strip().split()))
x={}
ans=0
for i in range(2*n):
    if a[i] in x:
        ans+=i-x[a[i]]-1
        for j in x:
            if x[j] > x[a[i]]:
                x[j]+=1
    else:
        x[a[i]]=i
print(ans)


n = int(input())
a = [int(i) for i in input().split()]
ans = 0
for i in range(0, n):
    s = a[0]
    del a[0]
    s = a.index(s)
    ans+=s
    del a[s]
print(ans)


n = int(input())
a = list(map(int, input().split()))
c = 0
for _i in range(n):
  i = 2 * _i
  for j in range(i + 1, 2 * n):
    if a[i] == a[j]:
      a[i + 2:j + 1] = a[i + 1:j]
      a[i + 1] = a[j]
      c += j - i - 1
      break
print(c)


n=input()
ar=list(map(int, input().strip().split()))
i=0
while len(ar)>0:
	k=ar[0]
	del ar[0]
	t=ar.index(k)
	i+=t
	del ar[t]
print (i)


# itne me hi thakk gaye?
n = int(input())
arr = list(map(int, input().split()))
count = 0
for ii in range(2*n):
	i = arr[ii]
	x = arr.index(i)
	y = arr.index(i, x+1)
	arr1 = arr[:x+1]
	arr2 = []
	for z in arr[x+1:]:
		if z != i:
			arr2.append(z)
	newarr = arr1 + [i] + arr2
	# print(newarr)
	arr = newarr[::]
	count += abs(x-y) - 1
print(count)


import heapq

n = int(input())
n *= 2
line = list(map(int, input().split()))

cnt = 0

while True:
    flag = False
    L, R = -1, -1

    # print(line)
    # input()

    i = 0
    while i < n - 1:
        if line[i] == line[i + 1]:
            i += 2
        else:
            L = i
            for j in range(i + 1, n):
                if line[j] == line[i]:
                    R = j
                    break
            flag = True
            break
    # print(L, ' ', R)
    # input()

    if not flag:
        break

    cnt += R - L - 1

    t = line[L]
    for i in range(R, L + 1, -1):
        line[i] = line[i - 1]
    line[L + 1] = t

print(cnt)


n=int(input())
a=[int(x) for x in input().split()]
ans=0
n=2*n
for i in range(0,n-1,2):
    if(a[i]==a[i+1]):
        continue
    for j in range(i+1,n):
        if a[i]==a[j]:
            break
    for k in range(j,i+1,-1):
        a[k-1],a[k]=a[k],a[k-1]
        ans+=1

print(ans)


def f(pairs_count: int, people: list):
    swap_count = 0
    if pairs_count < 1:
        return swap_count
    for left in range(0, pairs_count + pairs_count, 2):
        # find
        a = left + 1
        for a in range(left + 1, len(people)):
            if people[left] == people[a]:
                break
        # move
        for i in range(a, left + 1, -1):
            people[i - 1], people[i] = people[i], people[i - 1]
            swap_count += 1
    return swap_count

if __name__ == "__main__":
    n = int(input())
    l = [int(i) for i in input().split()]
    print(f(n, l))
#
# assert f(4, [int(k) for k in "1 1 2 3 3 2 4 4".split()]) == 2
# assert f(3, [int(k) for k in "1 1 2 2 3 3".split()]) == 0
# assert f(3, [int(k) for k in "3 1 2 3 1 2".split()]) == 3


n = int(input())
v = list(map(int,input().split()))
ans = 0

pos = [[j for j in range(2*n) if v[j] == i+1] for i in range(n)]

#print(v,pos)

for p in range(len(v)):
    i = v[p]-1
    if pos[i][0]+1 == pos[i][1]: continue
    for j in range(len(pos)):
        if j == i: continue
        if pos[j][0] > pos[i][0] and pos[j][0] <= pos[i][1]: pos[j][0] += 1
        if pos[j][1] > pos[i][0] and pos[j][1] <= pos[i][1]: pos[j][1] += 1
    ans += pos[i][1] - pos[i][0] - 1
    pos[i][1] = pos[i][0]+1
    #print(pos,ans)

print(ans)
#print(pos)


nops = int(input())
pers = [int(x) for x in input().split()]
ans = 0
while pers:
    i = pers.index(pers.pop(0))
    ans += i
    pers.pop(i)
print(ans)


N = int(input())
a = list(map(int,input().split()))
ans = 0
for i in range(N):
  b = a[i]
  a[i] = a[i] + 1000
  c = a.index(b)
  ans += c - i -1
  a.remove(b)
print(ans)


import math
from collections import Counter
L=lambda:list(map(int,input().split()))
M=lambda:map(int,input().split())
I=lambda:int(input())
IN=lambda:input()
def s(a):
    print("".join(list(map(str,a))))
#______________________-------------------------------_____________________#
n=I()
a=L()
n+=n
c=0
while n>0:
    x=a[0]
    a.pop(0)
    i=a.index(x)
    c+=i
    a.pop(i)
    n-=2
print(c)


#!/usr/bin/env python3
from sys import stdin

def solve(tc):
    n = int(stdin.readline().strip())
    li = list(map(int,stdin.readline().split()))

    ans = 0
    for i in range(0,2*n,2):
        for j in range(i+1,2*n):
            if li[i]==li[j]:
                for k in range(j,i+1,-1):
                    ans += 1
                    tmp = li[k]
                    li[k] = li[k-1]
                    li[k-1] = tmp
                break
    print(ans)

LOCAL_TEST = not __debug__
if LOCAL_TEST:
    infile = __file__.split('.')[0] + "-test.in"
    stdin = open(infile, 'r')

tcs = (int(stdin.readline().strip()) if LOCAL_TEST else 1)
tc = 1
while tc <= tcs:
    solve(tc)
    tc += 1


n = int(input())
a = [int(x) for x in input().split()]
used = [0 for _ in range(n * 2)]

res = 0
for i in range(n * 2):
    if used[i]:
        continue
    cnt = 0
    for j in range(i + 1, n * 2):
        if a[i] == a[j]:
            used[j] = 1
            break
        if used[j] == 0:
            cnt += 1

    res += cnt

print(res)


input()
p=list(map(int,input().split()))
#mat
d={}
spot={}
tot=0
for k in range(len(p)):
    if(p[k] not in d.keys()):
        d[p[k]]=k
    else:
        spot[p[k]]=k
        d[p[k]]=k-d[p[k]]
for k in range(len(p)):
    tot+=d[p[k]]-1
    sp=spot[p[k]]
    for i in range(k,sp):
        if(spot[p[i]]>sp):
            d[p[i]]-=1
    d[p[k]]=1
print(tot)


n = int(input())
positions = list(map(int, input().split(" ")))

swaps = 0
for i in range(n):
    number = positions[0]
    swaps += positions[1:].index(number)
    positions.remove(number)
    positions.remove(number)

print(swaps)


# Suit and Tie
# http://codeforces.com/contest/996/problem/D

n = int(input())

nums = input()
nums = [int(i) for i in nums.split()]

ans = 0

for i in range(0,len(nums),2):

    target = nums[i]

    other = i+1

    for j in range(i+1,len(nums)):
        if nums[j] == target:
            other = j

    swaps = other - i - 1
    ans += swaps

    # perform swaps
    for j in range(other,i+1,-1):
        nums[j], nums[j-1] = nums[j-1], nums[j]

    #print(nums)

print(ans)


n=int(input())
a=list(map(int,input().split()))
c=0
while len(a)!=0:
    z=a[0]
    b=a.index(z)
    d=a[1:].index(z)+1
#    print(b,d)
    c+=(d-b-1)
    a.remove(z)
    a.remove(z)
#    print(a)
print(c)


n=int(input())
l=list(map(int,input().split()))
d={}
sumi=0
i=0
while(i<2*n):
 # print(l,i)
  for j in range(i+1,2*n):
    if(l[i]==l[j]):
      sumi=j-i-1+sumi
      k=l.pop(j)
      l.insert(i+1,k)
      #print(l)
      break
  if(i==0):
    i=2
  else:
    i=i*2

print(sumi)


n=int(input())
l=list(map(int,input().split()))
sumi=0
while(len(l)>2):
  #print(l)
  for j in range(1,len(l)):
    if(l[0]==l[j]):
      sumi=j-1+sumi
      k=l.pop(j)
      l.pop(0)
      break

print(sumi)


n = int(input())
a = [int(v) for v in input().split()]

ans = 0

for i in range(0, 2 * n, 2):
    if a[i] == a[i + 1]:
        continue
    else:
        pair_idx = a[i+2:].index(a[i]) + (i + 2)
        ans += pair_idx - (i + 1)
        a = a[:i+1] + [a[i]] + a[i+1:pair_idx] + a[pair_idx+1:]

print(ans)


a = input()
k = list(map(int, input().split()))

total = 0

while k:
    i = k.index(k.pop(0))
    total = total + i
    k.pop(i)

print(total)


n=int(input())
p=list(map(int,input().split()))
ch=[0 for i in range(n+1)]
for i in range(0,2*n,2):
    if p[i]==p[i+1]:
        ch[p[i]]=1
count=0
for i in range(0,2*n,2):
    if p[i+1]!=p[i]:
        for j in range(i+1,2*n):
            if p[j]==p[i]:
                count=count+j-i
                count-=1
                for l in range(j,i+1,-1):
                    p[l]=p[l-1]
                p[i+1]=p[i]
                ch[p[i]]=1
                break
print(count)


n=int(input())
a=list(map(int,input().split()))
ans=0
while a:
    x=a[0]
    del a[0]
    ind=a.index(x)
    del a[ind]
    ans+=ind
print(ans)


input()
a=list(map(int,input().split()))
cnt=0
while a:
 i=a.index(a.pop(0))
 cnt+=i
 a.pop(i)
print(cnt)


n=int(input())
a=[int(i) for i in input().split()]
dict={}
temp=[]
for i in range(len(a)):
    dict[a[i]]=i
for i in range(len(a)):
    temp.append(dict[a[i]])
count=0
for i in range(len(a)-1):
    for j in range(len(a)-i-1):
        #print('I:',i,'J:',j)
        #print(temp)
        if temp[j]>temp[j+1]:
            temp[j],temp[j+1]=temp[j+1],temp[j]
            count+=1
print(count)


n=int(input())
l=list(map(int,input().strip().split()))
lo=[ -1 for i in range(n+1)]
lc=[ -1 for j in range(n+1)]
lp=[ [] for u in range(n+1)]
open1=[]
count=0
for i in range(2*n):
	if lo[l[i]]==-1:
		for j in open1:
			lp[l[i]].append(j)
		open1.append(l[i])
		lo[l[i]]=i+1
	else:
		r=0
		lc[l[i]]=i+1
		for j in lp[l[i]]:
			if lc[j]!=-1:
				r=r+1
		open1.remove(l[i])
		count=count+lc[l[i]]-lo[l[i]]-1-r
print (count)


#Have copied from eugalt
f = lambda: list(map(int, input().split()))
n = int(input())
a = f()
k = 0
while a:
    i = a.index(a.pop(0))
    k += i
    del a[i]
print(k)


#!/usr/bin/env python3

N = int(input())
flag = 1
a = [int(i) for i in input().split()]
Sum = 0
for i in range(0,len(a) - 1,2):
    #print(a)
    j = i + 1
    while a[j] != a[i]:
        j += 1
    Sum += (j - i - 1)
    a = a[:i + 1] + [a[j]] + a[i + 1:j] + a[j + 1:]
print(Sum)


def sol(s):
    if len(s)==0:
        return 0
    if s[0]==s[1]:
        return sol(s[2::])
    ind=s[1::].index(s[0])
    return ind+sol(s[1:ind+1]+s[ind+2::])

n=int(input())
s=list(map(int,input().split()))
print(sol(s))


def sol(s):
    if len(s)==0:
        return 0
    if s[0]==s[1]:
        return sol(s[2::])
    ind=s[1::].index(s[0])
    return ind+sol(s[1:ind+1]+s[ind+2::])

n=int(input())
s=list(map(int,input().split()))
s1=""
for i in s:
    s1+=str(i)
print(sol(s1))


k = input()
a = [int(x) for x in input().split()]
c = 0
while(a):
    f = a.pop(0)
    i = a.index(f)
    c += i
    del a[i]
print(c)


def sort(a):
	ans = 0
	for i in range(0, 2 * n - 2, 2):
		j = i + 1
	#	print('a[i] = ', a[i])
		while a[j] != a[i]:
	#		print(j, ':', a[j])
			j += 1
	#	print(j)
		for k in range(j, i + 1, -1):
			a[k], a[k - 1] = a[k - 1], a[k]
		ans += j - i - 1
	#	print(*a)
	#	a[i + 1], a[j] = a[j], a[i + 1]
	return ans
n = int(input())
a = [int(i) for i in input().split()]
print(sort(a))


n=int(input())
a=[map(int,input().split())]
ans =0
for i in range(0, n, 2):
 for j in range(i+1,n):
  if a[i] == a[j]:
   for k in range(j-1,i+1):
    t=a[k]
    a[k]=a[k+1]
    a[K+1]=t
    ans+=1
   break
print(ans)


n=int(input())
a=[int(x) for x in input().split()]
ans =0
for i in range(0, 2*n, 2):
 for j in range(i+1,2*n):
  if a[i] == a[j]:
   for k in range(j-1,i+1):
    t=a[k]
    a[k]=a[k+1]
    a[k+1]=t
    ans+=1
   break
print(ans)


n=int(input())
a=[int(x) for x in input().split()]
ans =0
for i in range(0, 2*n, 2):
    for j in range(i+2,2*n):
        if a[i] == a[j]:
            for k in range(j-1, i, -1):
                t=a[k]
                a[k]=a[k+1]
                a[k+1]=t
                ans+=1
            print(a)
            break
print(ans)


n=int(input())
a=[int(x) for x in input().split()]
ans =0
for i in range(0, 2*n, 2):
    for j in range(i+2,2*n):
        if a[i] == a[j]:
            for k in range(j-1, i, -1):
                t=a[k]
                a[k]=a[k+1]
                a[k+1]=t
                ans+=1
            break
print(ans)


n=int(input())
a=[int(x) for x in input().split()]
ans =0
for i in range(0, 2*n, 2):
    for j in range(i+2,2*n):
        if a[i] == a[j]:
            for k in range(i+1, j):
                t=a[k]
                a[k]=a[k+1]
                a[k+1]=t
                ans+=1
            break
print(ans)


n=int(input())
a=[map(int,input().split())]
ans =0
for i in range(0, n, 2):
 for j in range(i+1,n):
  if a[i] == a[j]:
   for k in range(j-1,i+1):
    t=a[k]
    a[k]=a[k+1]
    a[k+1]=t
    ans+=1
   break
print(ans)


n  = int(input())
ckn = list(map(int, input().split()))
res = 0

# print(ckn)
for p in range(n):
    f = ckn.pop(0)
    # print(f, ckn)
    g_ind = ckn.index(f)
    # print(g_ind)
    res += g_ind
    ckn.pop(g_ind)
    # print(g_ind, ckn)
print(res)


n = int(input())
x = list(map(int, input().split()))
ind = 0
count = 0
while ind != (2 * n):
	if (x[ind] != x[ind + 1]):
		q = ind + 1
		while (x[q] != x[ind]):
			q += 1
		while (q != ind + 1):
			x[q], x[q - 1] = x[q - 1], x[q]
			q -= 1
			count += 1
	ind += 2
print(count)


n=int(input())
n*=2
a=[*map(int,input().split())]
c=0
for i in range(1,n,2):
 j=next(j for j in range(i,n)if a[j]==a[i-1])
 c+=j-i
 a[i],a[i+1:j+1]=a[j],a[i:j]
print(c)


n=int(input())
a=[*map(int,input().split())]
c=0
for i in range(1,n):
 j=a.index(a[i-1],i);c+=j-i;del a[j]
print(c)


input()
a=[*map(int,input().split())]
c=0
while a:
 i=a.index(a.pop(0));c+=i;del a[i]
print(c)


import sys
def fastio():
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

def debug(*var, sep = ' ', end = '\n'):
	print(*var, file=sys.stderr, sep = sep, end = end)

INF = 10**20
MOD = 10**9 + 7
I = lambda:list(map(int,input().split()))
from math import gcd
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br

n, = I()
a = I()

ans = 0
v = [0] * 2 * n
for i in range(0, 2*n, 2):
	v[i] = 1
	if a[i] == a[i+1]: continue
	cur = a[i+1]
	swaps = 0
	for j in range(i + 1, 2*n):
		if a[j] == a[i]:
			break
		swaps += 1
	for k in range(j, i + 1, -1):
		a[k] = a[k-1]
	a[i + 1] = a[i]
	debug(swaps)
	ans += swaps
print(ans)


n=int(input())
used=[0]*(n+1)
a=list(map(int,input().split()))
r=[0]*(n+1)
l=[0]*(n+1)
c=[0]*(n+1)
for i in range(2*n):
    r[a[i]]=i
for i in range(2*n-1,-1,-1):
    l[a[i]]=i
for i in range(n,0,-1):
    c[i]=r[i]-l[i]-1
res=0
for i in range(2*n):
    if(used[a[i]]):
        continue
    used[a[i]]=1
    res+=c[a[i]]
    for j in range(1,n+1):
        if(l[j]<=r[a[i]] and r[a[i]]<=r[j]):
            c[j]-=1
print(res)


n = int(input())
a = [0]+list(map(int,input().split()))
l = [0]*(n+1)
ans = 0
for i in range(1,2*n+1):
    if(not l[a[i]]):
        l[a[i]] = 1
        c = 0
        for j in range(i+1,2*n+1):
            if(not l[a[j]]):
                c+=1
            else:
                if(a[i]==a[j]):
                    ans+=c
print(ans)


n=int(input())
a=[int(i) for i in input().split()]
s=0
for i in range(0,len(a),2):
    if a[i]!=a[i+1]:
        rf=(2*n-1-(a[i:][::-1].index(a[i])))
        s+=abs(rf-(i+1))
        a=a[:i+1]+[a[rf]]+a[i+1:rf]+a[rf+1:]
    # print(a)
print(s)


n=int(input())

a=list(map(int,input().split()))
cost=0
for i in range(n):
    pos2=a.index(a[2*i],2*i+1)
    for j in range(pos2,2*i,-1):
        a[j]=a[j-1]
    #print(a)
    #print(cost,pos2,i)
    cost+=(pos2-(2*i+1))
print(cost)


pairs = int(input())
line = [int(x) for x in input().split()]

def solve(lst, count):
  if len(lst) == 2:
    return count
  if lst[0] == lst[1]:
    return solve(lst[2:], count)
  targ = lst[0]
  other = lst[1:].index(targ)
  lst.remove(targ)
  lst.remove(targ)
  return solve(lst, count + other)

print(solve(line, 0))


def solve(a):
    swaps = 0
    for i in range(0, len(a), 2):
        if a[i] != a[i+1]:
            for j in range(len(a)-1, i+1, -1):
                if a[j] == a[i]:
                    t = a[j]
                    a[j] = a[j-1]
                    a[j-1] = t
                    swaps += 1
    return swaps

input()
inp = [int(i) for i in input().strip().split(" ")]
print(solve(inp))


def solve(a):
    swaps = 0
    for i in range(0, len(a), 2):
        if a[i] != a[i+1]:
            for j in range(len(a)-1, i+1, -1):
                if a[j] == a[i]:
                    t = a[j]
                    a[j] = a[j-1]
                    a[j-1] = t
                    swaps += 1
    return swaps

inp = [int(i) for i in input().strip().split(" ")]
print(solve(inp))


def swap(l,a,b):
    l[a], l[b] = l[b], l[a]

N = int(input())
a = []
for i in range(2*N):
    v = int(input())
    a.append(v)

i = 0
s = 0
while i<2*N-2:
    if a[i] != a[i+1]:
        ii = a.index(a[i], i+1)
#        print(ii)
        d = ii-i-1
        s += d
#        print(s)
        for j in range(d):
            swap(a,i+1+(d-j-1),i+1+(d-j))
#        print(a)
    i += 2
print(s)


def swap(l,a,b):
    l[a], l[b] = l[b], l[a]

N = int(input())
a = list(map(int, input().split()))

i = 0
s = 0
while i<2*N-2:
    if a[i] != a[i+1]:
        ii = a.index(a[i], i+1)
#        print(ii)
        d = ii-i-1
        s += d
#        print(s)
        for j in range(d):
            swap(a,i+1+(d-j-1),i+1+(d-j))
#        print(a)
    i += 2
print(s)


n=int(input())
s=list(map(int,input().split()))
swap=[0 for i in range(n+1)]
for i in range(0,2*n,2):
    if s[i]==s[i+1]:
        swap[s[i]]=1
cnt=0
for i in range(0,2*n,2):
    if swap[s[i]]==0 and s[i+1]!=s[i]:
        for j in range(i+1,2*n):
            if s[j]==s[i]:
                cnt+=j-i
                k=s[i+1]
                for l in range(i+2,j+1):
                    s[l]=s[l-1]
                s[i+1]=s[i]
                swap[s[i]]=1
                break
print(cnt)


n=int(input())
s=list(map(int,input().split()))
swap=[0 for i in range(n+1)]
for i in range(0,2*n,2):
    if s[i]==s[i+1]:
        swap[s[i]]=1
cnt=0
for i in range(0,2*n,2):
    if swap[s[i]]==0 and s[i+1]!=s[i]:
        for j in range(i+1,2*n):
            if s[j]==s[i]:
                cnt+=j-i-1
                k=s[i+1]
                for l in range(j,i+1,-1):
                    s[l]=s[l-1]
                s[i+1]=s[i]
                swap[s[i]]=1
                break
print(cnt)


from __future__ import print_function
import sys
import math
import os.path
import random
from copy import deepcopy
from functools import reduce

from collections import Counter, ChainMap, defaultdict
from itertools import cycle, chain
from queue import Queue, PriorityQueue, deque
from heapq import heappush, heappop, heappushpop, heapify, heapreplace, nlargest, nsmallest
import bisect

from statistics import mean, mode, median, median_low, median_high

# CONFIG
sys.setrecursionlimit(10**9)

# LOG
def log(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

# INPUT
def ni():
    return map(int, input().split())

def nio(offset):
    return map(lambda x: int(x) + offset, input().split())

def nia():
    return list(map(int, input().split()))

# CONVERT
def toString(aList, sep=" "):
    return sep.join(str(x) for x in aList)

def toMapInvertIndex(aList):
    return {k: v for v, k in enumerate(aList)}

# SORT
def sortId(arr):
    return sorted(range(arr), key=lambda k: arr[k])

# MAIN

n, = ni()
a = deque(nia())

s = 0

for _ in range(n):
    x = a.popleft()
    ix = a.index(x)
    s += ix
    a.remove(x)

print(s)


n = int(input())
a = [int(x) for x in input().split()]
ind , value = 0,0
num = n
while num>0:
	x = a[ind]
	nextInd = -1
	for i in range(ind+1,2*n):
		if x is a[i]:
			nextInd = i
			break

	for i in range(nextInd,ind+1,-1):
		a[i], a[i-1] = a[i-1], a[i]
		value+=1

	ind+=2
	num -=1

print(value)


R = lambda: map(int, input().split())

n = int(input())
a = list(R())

s = 0
while a:
    if a[0] == a[1]:
        a = a[2:]
    else:
        # dbvar(a)
        i = a[2:].index(a[0]) + 2
        a = a[1:i] + a[i+1:]
        s += i - 1
print(s)


from collections import defaultdict

def get_ind(j):
    global indexes

    indexes = defaultdict(list)

    for i in range(j, 2 * n):
        indexes[a[i]].append(i)

n = int(input())
a = list(map(int, input().split()))

ans = 0
for i in range(0, 2 * n, 2):
    get_ind(i)

    el = a[i]
    p = indexes[el].pop()

    for j in range(i + 1, p)[::-1]:
        a[j], a[j + 1] = a[j + 1], a[j]
        ans += 1

print(ans)


n=int(input())
s=[int(z) for z in input().split()]
counter=0
for i in range(0,2*n,2):
    sn=s[i]
    for j in range(i+1,2*n):
        if s[j]==sn:
            for p in range(j,i+1,-1):
                s[p],s[p-1]=s[p-1],s[p]
                counter+=1
            break
print(counter)


def solve(store, list, index, val):
    loc_count = 0

    while a[index - 1] != val:

        if store[a[index - 1]] != index - 1:
            store[a[index - 1]] = index

        a[index - 1], a[index] = a[index], a[index - 1]
        loc_count += 1
        index -= 1

    return loc_count

n, count = int(input()), 0
store = {}
a = list(map(int, input().strip().split()))

for i, item in enumerate(a):

    if item not in store:
        store[item] = i
    else:
        if store[item] != i:
            count += solve(store, a, i, item)

print(count)


n = int(input())
a = list(map(int, input().split()))
count = 0
for i in range(0, (2 * n) - 1):
	for j in range(i, 2 * n):
		if a[i] == a[j] and j == i + 1:
			break
		if a[i] == a[j] and i != j:
			for k in range(j, i + 1, -1):
				a[k] = a[k - 1]
				count += 1
			a[i + 1] = a[i]
			break
print(count)


def main():
    n = int(input())
    a = list(map(int, input().split()))
    ret = 0
    while len(a) > 2:
        p = a[0]
        a = a[1:]
        c = a.index(p)
        ret += c
        a.pop(c)
    print(ret)
    return 0
main()


def shift(ar, pos, req):
    cur = ar[pos]
    while pos > req:
        ar[pos] = ar[pos-1]
        pos -= 1
    ar[req] = cur

n = int(input())
ar = list(map(int, input().split()))
i = 0
ans = 0
while i < 2 * n:
    pos = i + 1 + ar[i+1:].index(ar[i])
    #print(ar[i], ar)
    #print(pos)
    if pos - i > 1:
        ans += pos - (i + 1)
        shift(ar, pos, i+1)
    i += 2

print(ans)


def shift(ar, pos, req):
    cur = ar[pos]
    while pos > req:
        ar[pos] = ar[pos-1]
        pos -= 1
    ar[req] = cur

n = int(input())
ar = list(map(int, input().split()))
i = 0
ans = 0
while i < n:
    pos = i + 1 + ar[i+1:].index(ar[i])
    #print(pos)
    if pos - i > 1:
        ans += pos - (i + 1)
        shift(ar, pos, i+1)
    i += 2

print(ans)


n = int(input())
a = list(map(int,input().split()))
t = 0
for i in range(n):
    x = a[0]
    a.pop(0)
    y = a.index(x)
    t+=y
    a.pop(y)

print(t)


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
short int a[100000];
short int b[100000];
short int c[100000];
long nu[100000];
int main(){
    ll n,a,mi = 10000000001,ind = -1;
    cin >> n;
    for(int i=0;i<n;i++){
        cin >> a;
        a -= i;
        a+=(n-1);
        if(a/n < mi){
            mi = a/n;
            ind = i;
        }
    }
    //cout << ind;
    cout << ind+1 << endl;
    return 0;
}


n = int(input())
a = list(map(int, input().split()))
ans = 0
d = {}
c = {}
for i in range(1,n+1):
    d[i] = 0
    c[i] = 0
for i in range(n-1):
    for j in range(2*n - i*2):
        if c[a[j]] == 0:
            c[a[j]] +=1
            d[a[j]] += j
        else:
            d[a[j]] += j-1
    mn = 100000000000
    nx=-1
    for j in d:
        if d[j] < mn:
            mn = d[j]
            nx = j
        d[j] = 0
        c[j] = 0
    del d[nx]
    del c[nx]
    ans += mn
    a = [i for i in a if i != nx]
print(ans)


from heapq import heapify,heappush,heappop
def prim(graph,start):
    mst={vertex:[] for vertex in graph.keys()}
    visited={vertex:False for vertex in graph.keys()}
    visited[start]=True
    pqueue=[(graph[start][nbr],start,nbr) for nbr in graph[start].keys()]
    heapify(pqueue)
    while pqueue:
        cost,frm,to=heappop(pqueue)
        if visited[to]==False:
            mst[frm]+=[to]
            visited[to]=True
            for nbr in graph[to].keys():
                if visited[nbr]==False:
                    heappush(pqueue,(graph[to][nbr],to,nbr))
    return mst


n=int(input())
arr=list(map(int,input().split()))
dic={i:[] for i in range(1,n+1)}
for i in range(len(arr)):
    dic[arr[i]]+=[i]
ans=0
for i in range(1,n+1):
    for j in range(i+1,n+1):
        ai,bi=dic[i]
        aj,bj=dic[j]
        if ai<aj:
            if bj<bi:
                ans+=2
            elif bi<aj:
                ans+=0
            else:
                ans+=1
        else:
            if bi<bj:
                ans+=2
            elif bj<ai:
                ans+=0
            else:
                ans+=1
print(ans)


n = int(input())
L = list(map(int, input().split()))
ans = 0
while len(L) > 0:
    now = L.pop(0)
    ans += L.index(now)
    L.remove(now)
print(ans)


n = int(input())
couples = input().split(" ")

def reorder(couples, i):
	global n
	first = couples[i]
	j = 2*n-1
	while(couples[j] != first):
		j -= 1
	count = 0
	while(j-1 != i):
		count += 1
		couples[j] = couples[j-1]
		j -= 1
	couples[i+1] = first
	return couples,count

i = 0
total = 0
while(i < 2*n-1):
	if couples[i] == couples[i+1]:
		i += 2
	else:
		couples,count = reorder(couples,i)
		total += count
		i += 2

print(total)


n = int(input())

raw = list(map(int,input().split(" ")))

seen = {} #not to use again
position = [] #holds the L and Rs
spacing = 0 #counts spacing to be dealth with
for i in range(2*n):
	if raw[i] in seen:
		position += ["R"]
		spacing += i - seen[raw[i]] - 1
	else:
		seen[raw[i]] = i
		position += ["L"]
swaps = 0

singleswap = 0
def goodswap(index):
	global swaps
	global spacing
	global position
	global raw
	global singleswap
	while(index < (2*n-1)):
		if spacing == 0:
			print(swaps)
			exit()
		if(raw[index] != raw[index+1] and position[index] == "L" and position[index+1] == "R"):
			swaps += 1
			singleswap = 0
			temp = raw[index]
			raw[index] = raw[index+1]
			raw[index+1] = temp
			position[index] = "R"
			position[index+1] = "L"
			index -= index
			spacing -= 2
		else:
			index += 1
	badswap()

def badswap():
	global swaps
	global position
	global raw
	global singleswap
	index = singleswap
	first = 1
	while(index < (2*n-1)):
		if raw[index] == raw[index+1] and first == 1:
			index += 2
		if raw[index] != raw[index+1]:
			first = 0
		if raw[index] != raw[index+1] and first == 0:
			swaps += 1
			temp = raw[index]
			raw[index] = raw[index+1]
			raw[index+1] = temp
			temppos = position[index]
			position[index] = position[index+1]
			position[index+1] = temppos
			singleswap = index + 1
			break
	goodswap(index)

if n == 1:
	print(0)
	exit()
goodswap(1)


n = int(input())

raw = list(map(int,input().split(" ")))

seen = {} #not to use again
position = [] #holds the L and Rs
spacing = 0 #counts spacing to be dealth with
for i in range(2*n):
	if raw[i] in seen:
		position += ["R"]
		spacing += i - seen[raw[i]] - 1
	else:
		seen[raw[i]] = i
		position += ["L"]
swaps = 0

singleswap = 0

def goodswap(index):
	global swaps
	global spacing
	global position
	global raw
	global singleswap
	while(index!=(2*n-1)):
		if spacing == 0:
			print(swaps)
			exit()
		if(raw[index] != raw[index+1] and position[index] == "L" and position[index+1] == "R"):
			swaps += 1
			singleswap = 0
			temp = raw[index]
			raw[index] = raw[index+1]
			raw[index+1] = temp
			position[index] = "R"
			position[index+1] = "L"
			index -= index
			spacing -= 2
		else:
			index += 1
	badswap()

def badswap():
	global swaps
	global position
	global raw
	global singleswap
	index = singleswap
	first = 1
	while(index!=(2*n-1)):
		if raw[index] == raw[index+1] and first == 1:
			index += 2
		if raw[index] != raw[index+1]:
			first = 0
		if raw[index] != raw[index+1] and first == 0:
			swaps += 1
			temp = raw[index]
			raw[index] = raw[index+1]
			raw[index+1] = temp
			temppos = position[index]
			position[index] = position[index+1]
			position[index+1] = temppos
			singleswap = index + 1
			break
	goodswap(index)

goodswap(1)


n = int(input())
a = list(map(int, input().split()))
ans=0
while(a):
    x = a.index(a.pop(0))
    ans = ans + x
    del a[x]
print(ans)


def  inp():
    return list(map(int,input().split()))
n,=inp()
l=inp()
ans=0
for i in range(n-1):
    x=l.pop(0)
    ans+=l.index(x)
    l.remove(x)
print(ans)


def minSwaps(n,pairs,a):
	i = 0
	c = 0
	vis = [0]*(2*n+1)
	while i < 2*n+1:
		j=i+1
		while j<2*n+1 and vis[j]:
			j+=1
		if j>=2*n:
			break
		if a[i]==a[j]:
			vis[i]=1
			vis[j]=1
			#print("l")
		else:
			#print("u")
			k = sum(vis[i+1:pairs[i]])
			f = pairs[i]-i-1-k
			k = sum(vis[j+1:pairs[j]])
			s = pairs[j]-j+1-k
			#print(f,s,k)
			if f<s:
				vis[i]=1
				vis[pairs[i]]=1
				c+=f
			else:
				vis[j]=1
				vis[pairs[j]]=1
				c+=s
		while i<2*n+1 and vis[i]:
		    i+=1
		#print(i,j,vis)
	return c

n = int(input().strip())
a = [int(x) for x in input().strip().split(' ')]
d = {}
pairs = [0]*(2*n)
for i in range(2*n):
	if a[i] in d:
		pairs[d[a[i]]] = i
		pairs[i] = d[a[i]]
	else:
		d[a[i]]=i
#print(a,pairs)
print(minSwaps(n, pairs,a))


n = int(input())
arr = list(map(int, input().split()))
ans = 0

for i in range(0, n * 2, 2):
    fi = arr.index(arr[i], i + 1, len(arr))
    if i + 1 != fi:
        ans += fi - i - 1
        del arr[fi]
        arr.insert(i + 1, arr[i])

print(ans)


from queue import deque
n = int(input())
arr = deque(map(int, input().split()))
ans = 0

for i in range(0, n * 2, 2):
    fi = arr.index(arr[i], i + 1, len(arr))
    if i + 1 != fi:
        ans += fi - i - 1
        del arr[fi]
        arr.insert(i + 1, arr[i])

print(ans)


def count_inversions(lst):
    return merge_count_inversion(lst)[1]

def merge_count_inversion(lst):
    if len(lst) <= 1:
        return lst, 0
    middle = int( len(lst) / 2 )
    left, a = merge_count_inversion(lst[:middle])
    right, b = merge_count_inversion(lst[middle:])
    result, c = merge_count_split_inversion(left, right)
    return result, (a + b + c)

def merge_count_split_inversion(left, right):
    result = []
    count = 0
    i, j = 0, 0
    left_len = len(left)
    while i < left_len and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            count += left_len - i
            j += 1
    result += left[i:]
    result += right[j:]
    return result, count

def f(n, nums):
    sset = dict()
    nums2 = []

    k = 1
    for i in nums:
        if i in sset:
            nums2.append(sset[i])
        else:
            nums2.append(k)
            sset[i] = k
            k += 1

    return count_inversions(nums2)

n = int(input())
queues = [int(i) for i in input().split()]
print(f(n, queues))


n=int(input())
arr=list(map(int,input().strip().split(' ')))
swap=0
m={}
for i in range(2*n):
    if(arr[i] in m):
        m[arr[i]].append(i)
    else:
        m[arr[i]]=[i]
for i in range(0,2*n-1,2):
    if(arr[i]!=arr[i+1]):
        temp=m[arr[i]]
        swap+=temp[1]-i-1
        x=arr[i+1]
        arr[i+1]=arr[i]
        arr[temp[1]]=x
    #print(arr)
    #print(swap)
print(swap)


n=int(input())
arr=list(map(int,input().strip().split(' ')))
swap=0
i=0
while(i<2*n):
    if(arr[i]!=arr[i+1]):
        cnt=0
        for j in range(2*n):
            if(arr[i]==arr[j]):
                cnt+=1
            if(cnt==2):
                break
        swap+=j-i-1
        key=arr[i+1]
        while(j>i+2):
            arr[j]=arr[j-1]
            j-=1
            #print(arr)
        arr[i+2]=key
        arr[i+1]=arr[i]
        #print('hi',arr)
    i+=2
print(swap)


n = int(input())
s = list(map(int, input().split()))

t = 0
while len(s) > 0:
    ls = len(s)
    s1 = s.index(s[0], 1)
    sn = s.index(s[-1])

    if s1 < ls - sn-1:
        s = s[1:s1]+s[s1+1:]
        t += s1-1
    else:
        t += ls-sn-2
        s = s[:sn] + s[sn+1:ls-1]

print(t)


n = int(input())
s = list(map(int, input().split()))

t = 0
while len(s) > 0:
    ls = len(s)
    s1 = s.index(s[0], 1)
    sn = s.index(s[-1])

    if s1 < ls - sn:
        s = s[1:s1]+s[s1+1:]
        t += s1-1
    else:
        t += ls-sn-1
        s = s[:sn] + ([] if sn < ls - 1 else s[sn+1:-1])

print(t)


import itertools as it
import sys
"""
R=[1,1,2,3,3,2,4,4]
def F(x,d):
    if all(x[i]==x[i+1] for i in range(0,len(x),2)):
        return 0
    if d==0: return None
    r=None
    for i in range(len(x)-1):
        y=x[:]
        y[i],y[i+1]=x[i+1],x[i]
        u=F(y,d-1)
        if u is not None:
            u+=1
            if r is None: r=u
            else: r=min(r,u)
    return r

def G(x):
    for i in it.count(0):
        if F(x,i) is not None: return i
"""

def bad(x):
    r=0
    changed=True
    while changed:
        changed=False
        for i in range(len(x)):
            if changed: break
            first=i
            for j in range(i+1,len(x)):
                if x[i]==x[j]:
                    if i+1==j: break
                    r+=(j+1)-(i+2)
                    for k in range(i+1,j)[::-1]: x[k],x[k+1]=x[k+1],x[k]
                    changed=True
                    break
    return r

"""
N=3
freq={}
for x in it.permutations(list(range(0,N))*2):
    u=G(list(x))
    v=bad(list(x))
    assert(u==v)
    #print(x,u)
    freq[u]=freq.get(u,0)+1

for i in sorted(freq): print(i,freq[i])
"""

R=sys.stdin.read().split(" ")
Z=[]
for u in R:
    u=u.strip()
    Z+=u.split("\n")
Z=[int(i.strip()) for i in Z if len(i)]
N=Z[0]

print(bad(Z[1:2*N+1]))


n=int(input())
arr=list(map(int,input().split()))
dict1={}
for i in range(2*n):
	try:
		dict1[arr[i]].append(i+1)
	except:
		KeyError
		dict1[arr[i]]=[i+1]
ans=0
#print(dict1)
for i in range(0,2*n,2):
	if(dict1[arr[i]][1]==i+1):
		j=dict1[arr[i]][0]-1
		while(j>dict1[arr[i]][1]):
			if(dict1[arr[j-1]][0]==j):
				dict1[arr[j-1]][0]=j+1
			else:
				dict1[arr[j-1]][1]=j+1
			dict1[arr[i]][0]-=1
			temp=arr[j]
			arr[j]=arr[j-1]
			arr[j-1]=temp
			j-=1
			ans+=1
	else:
		j=dict1[arr[i]][1]-1
		while(j>dict1[arr[i]][0]):
			if(dict1[arr[j-1]][0]==j):
				dict1[arr[j-1]][0]=j+1
			else:
				dict1[arr[j-1]][1]=j+1
			dict1[arr[i]][1]-=1
			temp=arr[j]
			arr[j]=arr[j-1]
			arr[j-1]=temp
			j-=1
			ans+=1
print(ans)
#print(dict1)


#from operator import itemgetter
n=int(input())
arr=list(map(int,input().split()))
ct=0
#freq=[0]*(n+1)
ans=0
for i in range(2*n):
	for j in range(i+2,2*n):
		if arr[j]==arr[i]:
			p,q=i,j
			while(q-p!=1):
				arr[q],arr[q-1]=arr[q-1],arr[q]
				q-=1
				ct+=1
print(ct)


#include <iostream>
#include <vector>
#include <queue>
#include <ctime>
#include <set>
#include <map>
#include <algorithm>

using namespace std;

template<typename S, typename T>
struct Min_cost_max_flow {

private:
    struct edge {
        int b, e;
        S c, f, p;
        int n;
        edge *back_edge;

        edge(int b, int e, S c, S p, int n) : b(b), e(e), c(c), f(0), p(p), n(n), back_edge(nullptr) {}
    };

    vector<vector<edge *>> edges;
    vector<int> d;
    vector<edge *> from;

    S INF;
    int n;

    bool bfs(int s, int t) {
        d.assign(n, INF);
        d[s] = 0;
        for (int i = 0; i < n - 1; ++i) {
            bool f = false;
            for (int j = 0; j < n; ++j) {
                for (auto e : edges[j]) {
                    if (e->c - e->f == 0) {
                        continue;
                    }

                    if (d[j] < INF) {
                        if (d[e->e] > d[e->b] + e->p) {
                            d[e->e] = d[j] + e->p;
                            from[e->e] = e;
                            f = true;
                        }
                    }
                }
            }

            if (!f) {
                break;
            }
        }

        return d[t] != INF;
    }

    pair<T, T> push(int s, int v, S c_min) {
        if (v == s) {
            return {c_min, 0};
        }

        auto e = from[v];
        auto add = push(s, e->b, std::min(c_min, e->c - e->f));
        if (add.first > 0) {
            e->f += add.first;
            e->back_edge->f -= add.first;
            add.second += add.first * e->p;
        }
        return add;
    }

public:

    explicit Min_cost_max_flow(int n, S INF) : INF(INF), n(n) {
        d.resize(n);
        from.resize(n);
        edges.resize(n);
    }

    void add_edge(int b, int e, S c, S p, int n) {
        edge *e1 = new edge(b, e, c, p, n);
        edge *e2 = new edge(e, b, 0, -p, n);
        e1->back_edge = e2;
        e2->back_edge = e1;
        edges[b].push_back(e1);
        edges[e].push_back(e2);
    }

    T run(int s, int t) {
        T price = 0;
        while (bfs(s, t)) {
            auto add = push(s, t, INF);
            price += add.second;
        }

        return price;
    }

    void ans(vector<int> &ans, int n) {
        for (int i = 2; i < n; ++i) {
            for (auto e : edges[i]) {
                if (e->n != -1 && e->f == 1) {
                    ans[e->n] = 1;
                }
            }
        }
    }
};

vector<int> line, column, p, from;

struct tmp {
    int b, e, p, n;

    bool operator<(const tmp &other) {
        return b < other.b || (b == other.b && e < other.e);
    }
};

int main() {

    ios_base::sync_with_stdio(false);
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    int n, k;
    cin >> n >> k;

    set<int> ver;
    int b, e, p;
    vector<tmp> tasks;
    Min_cost_max_flow<int, long long> min_cost(2 * n + 3, 1000000001);

    for (int i = 0; i < n; ++i) {
        cin >> b >> e >> p;
        tasks.push_back({b, b + e, p, i});
    }

    sort(tasks.begin(), tasks.end());

    for (int i = 2; i <= n + 1; ++i) {
        b = tasks[i - 2].b;
        e = tasks[i - 2].e;
        p = tasks[i - 2].p;
        min_cost.add_edge(i, n + i, 1, -p, tasks[i - 2].n);
        min_cost.add_edge(1, i, k, 0, -1);
        min_cost.add_edge(n + i, 2 * n + 2, 1, 0, -1);
    }

    min_cost.add_edge(0, 1, k, 0, -1);

    for (int i = 2; i < n + 1; ++i) {
        min_cost.add_edge(i, i + 1, k, 0, -1);
        for (int j = i + 1; j <= n + 1; ++j) {
            if (tasks[i - 2].e <= tasks[j - 2].b) {
                min_cost.add_edge(n + i, j, 1, 0, -1);
                break;
            }
        }
    }

    cerr << min_cost.run(0, 2 * n + 2) << "\n";
    vector<int> ans(n);
    min_cost.ans(ans, n + 2);
    for (auto e : ans) {
        cout << e << " ";
    }
    return 0;
}


#define _CRT_SECURE_NO_WARNINGS

#include <vector>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <numeric>
#include <cstdint>
#include <time.h>
#include <unordered_map>

#define int long long
#define double long double
#define accuracy(a) fixed << setprecision(a)

const int INF = (int)1e9;
const double EPS = 0.000000000000001;
const double PI = acos(-1.0);
const int MOD = (int)1e9 + 7;

using namespace std;

void fast_io()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}

void file_in(string filename)
{
	freopen(filename.c_str(), "r", stdin);
}

void file_out(string filename)
{
	freopen(filename.c_str(), "w", stdout);
}

double diffclock(clock_t clock1, clock_t clock2)
{
	double diffticks = clock2 - clock1;
	return diffticks / ((double)CLOCKS_PER_SEC / 1000);
}

void sleep(int milliseconds)
{
	clock_t start = clock();
	for (clock_t end = clock(); diffclock(start, end) < milliseconds; end = clock()) {}
}

struct Edge
{
	int to;
	int capacity;
	int flow;
	int cost;
	int reversed_edge = -1;
	int index;

	Edge(int to = -1, int capacity = -1, int flow = -1, int cost = -1, int index = -1) :
		to(to), capacity(capacity), flow(flow), cost(cost), index(index) {}
};

struct EdgeFord
{
	int from;
	int to;
	int cost;
	int id;

	EdgeFord(int from = -1, int to = -1, int cost = -1, int id = -1) :
		from(from), to(to), cost(cost), id(id) {}
};

struct Parent
{
	int vertex;
	int edge;

	Parent(int vertex = -1, int edge = -1) :
		vertex(vertex), edge(edge) {}
};

int n, m, s, t;
vector< vector<Edge> > graph;
//vector<Edge>* graph;
vector<EdgeFord> edge_list;
vector<int> prior;
vector<Parent> parent;

void make_edge(int from, int to, int capacity, int cost, int index = -1)
{
	//Main graph
	graph[from].push_back(Edge(to, capacity, 0, cost, index));
	graph[to].push_back(Edge(from, 0, 0, -cost, index));
	graph[from].back().reversed_edge = graph[to].size() - 1;
	graph[to].back().reversed_edge = graph[from].size() - 1;

	//FordBellman graph
	edge_list.push_back(EdgeFord(from, to, cost, graph[from].size() - 1));
}

void FordBellman(vector<int>& dist, vector<Parent>& parent)
{
	dist.assign(n, INF);
	parent.assign(n, Parent());
	dist[s] = 0;
	parent[s] = Parent(s);
	for (int i = 0; i < n - 1; ++i)
	{
		bool any_relax = false;
		for (int j = 0; j < edge_list.size(); ++j)
		{
			if (dist[edge_list[j].from] < INF)
			{
				if (dist[edge_list[j].to] > dist[edge_list[j].from] + edge_list[j].cost)
				{
					dist[edge_list[j].to] = dist[edge_list[j].from] + edge_list[j].cost;
					parent[edge_list[j].to] = Parent(edge_list[j].from, edge_list[j].id);
					any_relax = true;
				}
			}
		}
		if (!any_relax)
		{
			break;
		}
	}
}

int count_cost(int from, int id)
{
	return graph[from][id].cost + prior[from] - prior[graph[from][id].to];
}

void Dijkstra(vector<int>& dist, vector<Parent>& parent)
{
	dist.assign(n, INF);
	parent.assign(n, Parent());
	vector<char> used(n);
	dist[s] = 0;
	parent[s] = Parent(s);
	int min_ind, min_dist;
	for (int i = 0; i < n; ++i)
	{
		min_ind = min_dist = INF;
		for (int j = 0; j < n; ++j)
		{
			if (!used[j] && (dist[j] < min_dist))
			{
				min_dist = dist[j];
				min_ind = j;
			}
		}
		if (min_ind == INF)
		{
			break;
		}
		used[min_ind] = 1;
		for (int j = 0; j < graph[min_ind].size(); ++j)
		{
			if (graph[min_ind][j].capacity - graph[min_ind][j].flow <= 0)
			{
				continue;
			}
			int edge_cost = count_cost(min_ind, j);
			if (dist[min_ind] + edge_cost < dist[graph[min_ind][j].to])
			{
				dist[graph[min_ind][j].to] = dist[min_ind] + edge_cost;
				parent[graph[min_ind][j].to] = Parent(min_ind, j);
			}
		}
	}
}

void Dijkstra2(vector<int>& dist, vector<Parent>& parent)
{
	dist.assign(n, INF);
	parent.assign(n, Parent());
	dist[s] = 0;
	parent[s] = Parent(s);
	set< pair<int, int> > q;
	q.insert({0, s});
	while (!q.empty())
	{
		int min_ind = q.begin()->second;
		q.erase(q.begin());
		for (int j = 0; j < graph[min_ind].size(); ++j)
		{
			if (graph[min_ind][j].capacity - graph[min_ind][j].flow <= 0)
			{
				continue;
			}
			int edge_cost = count_cost(min_ind, j);
			if (dist[min_ind] + edge_cost < dist[graph[min_ind][j].to])
			{
				q.erase({ dist[graph[min_ind][j].to], graph[min_ind][j].to});
				dist[graph[min_ind][j].to] = dist[min_ind] + edge_cost;
				parent[graph[min_ind][j].to] = Parent(min_ind, j);
				q.insert({ dist[graph[min_ind][j].to], graph[min_ind][j].to });
			}
		}
	}
}

void simpleDecomposition(int start, vector<int>& edges)
{
	deque< pair<int, int> > used_edges;
	vector<char> used(n);
	int cur, flow;
	cur = start;
	flow = INF;
	for (; !used[cur]; )
	{
		if (cur == t)
		{
			break;
		}
		bool is_found = false;
		for (int i = 0; i < graph[cur].size(); ++i)
		{
			if (graph[cur][i].flow > 0)
			{
				used_edges.push_back({cur, i});
				flow = min(flow, graph[cur][i].flow);
				used[cur] = 1;
				cur = graph[cur][i].to;
				is_found = true;
				break;
			}
		}
		if (!is_found)
		{
			return;
		}
	}
	if (used[cur])
	{
		while (used_edges.front().first != cur)
		{
			used_edges.pop_front();
		}
		for (auto p : used_edges)
		{
			graph[p.first][p.second].flow -= flow;
		}
		return;
	}
	int cost = 0;
	for (auto p : used_edges)
	{
		edges.push_back(graph[p.first][p.second].index);
		graph[p.first][p.second].flow -= flow;
	}
	return;
}

void Decomposition()
{
	vector< vector<int>> simpleParts;
	vector<int> edges;
	simpleDecomposition(s, edges);
	while (!edges.empty())
	{
		simpleParts.push_back(edges);
		edges.clear();
		simpleDecomposition(s, edges);
	}
	for (int i = 0; i < n; ++i)
	{
		if (i == s)
		{
			continue;
		}
		simpleDecomposition(i, edges);
		while (!edges.empty())
		{
			simpleParts.push_back(edges);
			edges.clear();
			simpleDecomposition(i, edges);
		}
	}

	for (int i = 0; i < simpleParts.size(); ++i)
	{
		cout << simpleParts[i].size() << ' ';
		for (int j : simpleParts[i])
		{
			cout << j << ' ';
		}
		cout << '\n';
	}
}

signed main()
{
	fast_io();

	//Graph input
	int tn, k;
	cin >> tn >> k;
	n = 2 * tn + 3;
	s = 2 * tn;
	t = 2 * tn + 2;
	graph.resize(n);
	vector< pair<int, int> > times(tn);
	for (int i = 0; i < tn; ++i)
	{
		int start, time, cost;
		cin >> start >> time >> cost;
		make_edge(i, tn + i, 1, -cost);
		times[i] = { start, time };
	}
	for (int i = 0; i < tn; ++i)
	{
		for (int j = 0; j < tn; ++j)
		{
			if (i == j)
			{
				continue;
			}
			if (times[i].first + times[i].second <= times[j].first)
			{
				make_edge(tn + i, j, 1, 0);
			}
		}
	}
	make_edge(s, s + 1, k, 0);
	for (int i = 0; i < tn; ++i)
	{
		make_edge(s + 1, i, 1, 0);
		make_edge(tn + i, t, 1, 0);
	}

	FordBellman(prior, parent);

	int flow, cost;
	flow = cost = 0;
	while (parent[t].vertex != -1)
	{
		//Merge new flow
		int max_flow = INF;
		for (int cur = t; cur != s; )
		{
			Edge parent_edge = graph[parent[cur].vertex][parent[cur].edge];
			max_flow = min(max_flow, parent_edge.capacity - parent_edge.flow);
			cur = parent[cur].vertex;
		}
		for (int cur = t; cur != s; )
		{
			graph[parent[cur].vertex][parent[cur].edge].flow += max_flow;
			int reversed_edge = graph[parent[cur].vertex][parent[cur].edge].reversed_edge;
			graph[cur][reversed_edge].flow -= max_flow;
			cost += graph[parent[cur].vertex][parent[cur].edge].cost * max_flow;
			cur = parent[cur].vertex;
		}
		flow += max_flow;

		//Count new flow
		vector<int> new_dist;
		Dijkstra2(new_dist, parent);
		for (int i = 0; i < n; ++i)
		{
			prior[i] += new_dist[i];
		}
	}

	for (int i = 0; i < tn; ++i)
	{
		cout << (graph[i][0].flow > 0 ? '1' : '0') << ' ';
	}
	cout << '\n';

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS

#include <vector>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <numeric>
#include <cstdint>
#include <time.h>
#include <unordered_map>

#define int long long
#define double long double
#define accuracy(a) fixed << setprecision(a)

const int INF = (int)1e9;
const double EPS = 0.000000000000001;
const double PI = acos(-1.0);
const int MOD = (int)1e9 + 7;

using namespace std;

void fast_io()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
}

void file_in(string filename)
{
	freopen(filename.c_str(), "r", stdin);
}

void file_out(string filename)
{
	freopen(filename.c_str(), "w", stdout);
}

double diffclock(clock_t clock1, clock_t clock2)
{
	double diffticks = clock2 - clock1;
	return diffticks / ((double)CLOCKS_PER_SEC / 1000);
}

void sleep(int milliseconds)
{
	clock_t start = clock();
	for (clock_t end = clock(); diffclock(start, end) < milliseconds; end = clock()) {}
}

struct Edge
{
	int to;
	int capacity;
	int flow;
	int cost;
	int reversed_edge = -1;
	int index;

	Edge(int to = -1, int capacity = -1, int flow = -1, int cost = -1, int index = -1) :
		to(to), capacity(capacity), flow(flow), cost(cost), index(index) {}
};

struct EdgeFord
{
	int from;
	int to;
	int cost;
	int id;

	EdgeFord(int from = -1, int to = -1, int cost = -1, int id = -1) :
		from(from), to(to), cost(cost), id(id) {}
};

struct Parent
{
	int vertex;
	int edge;

	Parent(int vertex = -1, int edge = -1) :
		vertex(vertex), edge(edge) {}
};

int n, m, s, t;
vector< vector<Edge> > graph;
//vector<Edge>* graph;
vector<EdgeFord> edge_list;
vector<int> prior;
vector<Parent> parent;

void make_edge(int from, int to, int capacity, int cost, int index = -1)
{
	//Main graph
	graph[from].push_back(Edge(to, capacity, 0, cost, index));
	graph[to].push_back(Edge(from, 0, 0, -cost, index));
	graph[from].back().reversed_edge = graph[to].size() - 1;
	graph[to].back().reversed_edge = graph[from].size() - 1;

	//FordBellman graph
	edge_list.push_back(EdgeFord(from, to, cost, graph[from].size() - 1));
}

void FordBellman(vector<int>& dist, vector<Parent>& parent)
{
	dist.assign(n, INF);
	parent.assign(n, Parent());
	dist[s] = 0;
	parent[s] = Parent(s);
	for (int i = 0; i < n - 1; ++i)
	{
		bool any_relax = false;
		for (int j = 0; j < edge_list.size(); ++j)
		{
			if (dist[edge_list[j].from] < INF)
			{
				if (dist[edge_list[j].to] > dist[edge_list[j].from] + edge_list[j].cost)
				{
					dist[edge_list[j].to] = dist[edge_list[j].from] + edge_list[j].cost;
					parent[edge_list[j].to] = Parent(edge_list[j].from, edge_list[j].id);
					any_relax = true;
				}
			}
		}
		if (!any_relax)
		{
			break;
		}
	}
}

int count_cost(int from, int id)
{
	return graph[from][id].cost + prior[from] - prior[graph[from][id].to];
}

void Dijkstra(vector<int>& dist, vector<Parent>& parent)
{
	dist.assign(n, INF);
	parent.assign(n, Parent());
	vector<char> used(n);
	dist[s] = 0;
	parent[s] = Parent(s);
	int min_ind, min_dist;
	for (int i = 0; i < n; ++i)
	{
		min_ind = min_dist = INF;
		for (int j = 0; j < n; ++j)
		{
			if (!used[j] && (dist[j] < min_dist))
			{
				min_dist = dist[j];
				min_ind = j;
			}
		}
		if (min_ind == INF)
		{
			break;
		}
		used[min_ind] = 1;
		for (int j = 0; j < graph[min_ind].size(); ++j)
		{
			if (graph[min_ind][j].capacity - graph[min_ind][j].flow <= 0)
			{
				continue;
			}
			int edge_cost = count_cost(min_ind, j);
			if (dist[min_ind] + edge_cost < dist[graph[min_ind][j].to])
			{
				dist[graph[min_ind][j].to] = dist[min_ind] + edge_cost;
				parent[graph[min_ind][j].to] = Parent(min_ind, j);
			}
		}
	}
}

void Dijkstra2(vector<int>& dist, vector<Parent>& parent)
{
	dist.assign(n, INF);
	parent.assign(n, Parent());
	dist[s] = 0;
	parent[s] = Parent(s);
	set< pair<int, int> > q;
	q.insert({0, s});
	while (!q.empty())
	{
		int min_ind = q.begin()->second;
		q.erase(q.begin());
		for (int j = 0; j < graph[min_ind].size(); ++j)
		{
			if (graph[min_ind][j].capacity - graph[min_ind][j].flow <= 0)
			{
				continue;
			}
			int edge_cost = count_cost(min_ind, j);
			if (dist[min_ind] + edge_cost < dist[graph[min_ind][j].to])
			{
				q.erase({ dist[graph[min_ind][j].to], graph[min_ind][j].to});
				dist[graph[min_ind][j].to] = dist[min_ind] + edge_cost;
				parent[graph[min_ind][j].to] = Parent(min_ind, j);
				q.insert({ dist[graph[min_ind][j].to], graph[min_ind][j].to });
			}
		}
	}
}

void simpleDecomposition(int start, vector<int>& edges)
{
	deque< pair<int, int> > used_edges;
	vector<char> used(n);
	int cur, flow;
	cur = start;
	flow = INF;
	for (; !used[cur]; )
	{
		if (cur == t)
		{
			break;
		}
		bool is_found = false;
		for (int i = 0; i < graph[cur].size(); ++i)
		{
			if (graph[cur][i].flow > 0)
			{
				used_edges.push_back({cur, i});
				flow = min(flow, graph[cur][i].flow);
				used[cur] = 1;
				cur = graph[cur][i].to;
				is_found = true;
				break;
			}
		}
		if (!is_found)
		{
			return;
		}
	}
	if (used[cur])
	{
		while (used_edges.front().first != cur)
		{
			used_edges.pop_front();
		}
		for (auto p : used_edges)
		{
			graph[p.first][p.second].flow -= flow;
		}
		return;
	}
	int cost = 0;
	for (auto p : used_edges)
	{
		edges.push_back(graph[p.first][p.second].index);
		graph[p.first][p.second].flow -= flow;
	}
	return;
}

void Decomposition()
{
	vector< vector<int>> simpleParts;
	vector<int> edges;
	simpleDecomposition(s, edges);
	while (!edges.empty())
	{
		simpleParts.push_back(edges);
		edges.clear();
		simpleDecomposition(s, edges);
	}
	for (int i = 0; i < n; ++i)
	{
		if (i == s)
		{
			continue;
		}
		simpleDecomposition(i, edges);
		while (!edges.empty())
		{
			simpleParts.push_back(edges);
			edges.clear();
			simpleDecomposition(i, edges);
		}
	}

	for (int i = 0; i < simpleParts.size(); ++i)
	{
		cout << simpleParts[i].size() << ' ';
		for (int j : simpleParts[i])
		{
			cout << j << ' ';
		}
		cout << '\n';
	}
}

signed main()
{
	fast_io();

	//Graph input
	int tn, k;
	cin >> tn >> k;
	n = 2 * tn + 2;
	s = 2 * tn;
	t = 2 * tn + 1;
	graph.resize(n);
	vector< pair< pair<int, int>, pair<int, int> > > times(tn);
	for (int i = 0; i < tn; ++i)
	{
		int start, time, cost;
		cin >> start >> time >> cost;
		times[i] = { {start, time}, {cost, i} };
	}
	sort(times.begin(), times.end());
	for (int i = 0; i < tn; ++i)
	{
		make_edge(i, tn + i, 1, -times[i].second.first);
		if (i == tn - 1)
		{
			make_edge(i, t, k, 0);
		}
		else
		{
			make_edge(i, i + 1, k, 0);
		}
		bool is_found = false;
		for (int j = 0; j < tn; ++j)
		{
			if (times[i].first.first + times[i].first.second <= times[j].first.first)
			{
				make_edge(tn + i, j, k, 0);
				is_found = true;
				break;
			}
		}
		if (!is_found)
		{
			make_edge(tn + i, t, k, 0);
		}
	}
	make_edge(s, 0, k, 0);

	FordBellman(prior, parent);

	int flow, cost;
	flow = cost = 0;
	while (parent[t].vertex != -1)
	{
		//Merge new flow
		int max_flow = INF;
		for (int cur = t; cur != s; )
		{
			Edge parent_edge = graph[parent[cur].vertex][parent[cur].edge];
			max_flow = min(max_flow, parent_edge.capacity - parent_edge.flow);
			cur = parent[cur].vertex;
		}
		for (int cur = t; cur != s; )
		{
			graph[parent[cur].vertex][parent[cur].edge].flow += max_flow;
			int reversed_edge = graph[parent[cur].vertex][parent[cur].edge].reversed_edge;
			graph[cur][reversed_edge].flow -= max_flow;
			cost += graph[parent[cur].vertex][parent[cur].edge].cost * max_flow;
			cur = parent[cur].vertex;
		}
		flow += max_flow;

		//Count new flow
		vector<int> new_dist;
		Dijkstra2(new_dist, parent);
		for (int i = 0; i < n; ++i)
		{
			prior[i] += new_dist[i];
		}
	}

	vector<int> res(tn);
	for (int i = 0; i < tn; ++i)
	{
		for (Edge e : graph[i])
		{
			if (e.cost < 0)
			{
				if (e.flow > 0)
				{
					res[times[i].second.second] = 1;
				}
				break;
			}
		}
	}
	for (int i : res)
	{
		cout << i << ' ';
	}
	cout << '\n';

	return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;
using namespace std;

#pragma GCC optimize("Ofast")
#pragma GCC optimize ("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#define endl "\n"
#define ima INT_MAX
#define imi INT_MIN
#define lma LLONG_MAX
#define lmi LLONG_MIN
#define mem(X,A) memset(X,A,sizeof(X))
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define mp make_pair
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define lli long long int
#define pii pair<int,int>
#define vii vector<pii>
#define pb push_back
#define eb emplace_back
#define em emplace
#define all(v)  v.begin(),v.end()
#define mod 1000000007
#define vi vector<int>
#define vl vector<lli>
#define vll vector<pair<lli,lli>>
#define pll pair<lli,lli>
#define vvi vector<vector<int>>
#define vvl vector<vector<lli>>
#define error(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
#define tk(args...) take(args);
#define posLSB(X) __builtin_ctz(X)
#define num1bit(X) __builtin_popcount(X)
#define numlead0(X) __builtin_clz(X)
#define umreserve(X) X.reserve(32768); X.max_load_factor(0.25);

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int RANDOM = chrono::high_resolution_clock::now().time_since_epoch().count();
struct chash { // To use most bits rather than just the lowest ones:
	const uint64_t C = (lli)(4e18 * acos(0)) | 71; // large odd number
	lli operator()(lli x) const { return __builtin_bswap64((x^RANDOM)*C); }
};

void err(istream_iterator<string> it) {} template<typename T, typename... Args> void err(istream_iterator<string> it, T a, Args... args) { cout << *it << " = " << a << "\n"; err(++it, args...);}
void take() {} template<typename T, typename... Args> void take( T & a, Args & ... args ) { cin>>a; take(args...); }
template<class T>
void printvec(vector<T> &a){
	for(T &x:a){
		cout<<x<<" ";
	}
	cout<<endl;
}
template<class T>
void printarr(T a[],lli n){
	for(lli i=0;i<n;i++){
		cout<<a[i]<<" ";
	}
	cout<<endl;
}
struct HASH{
  size_t operator()(const pair<int,int>&x)const{
    return (size_t) x.first * 37U + (size_t) x.second;
  }
};

lli add(lli a, lli b) {
	a += b;
	if (a >= mod) a -= mod;
	return a;
}

lli mul(lli a, lli b) {
	return a * 1ll * b % mod;
}

inline bool setmin(lli &x, lli y) { return (y < x) ? x = y, 1 : 0; }
inline bool setmax(lli &x, lli y) { return (y > x) ? x = y, 1 : 0; }

lli power_mod(lli a,lli x){if(x==0) return 1;lli y=power_mod(a,x/2);lli ans=(y*y)%mod; if(x%2) ans=(ans*a)%mod;return ans;}
lli inv(lli a){return power_mod(a,mod-2);}
lli power(lli a, lli x){ if(x==0) return 1; lli y= power(a,x/2); lli ans=(y*y); if(x%2) ans*=a; return ans;}

  template<class Flow, class Cost>
struct MinCostFlow {
	const Flow INF_FLOW = 1000111000;
	const Cost INF_COST = 1000111000111000LL;

	int n, t, S, T;
	Flow totalFlow;
	Cost totalCost;
	vector<int> last, visited;
	vector<Cost> dis;
	struct Edge {
		int to;
		int id;
		Flow cap;
		Cost cost;
		int next;
		Edge(int to, Flow cap, Cost cost, int next,int id) :
				to(to), cap(cap), cost(cost), next(next), id(id) {}
	};
	vector<Edge> edges;

	MinCostFlow(int n) : n(n), t(0), totalFlow(0), totalCost(0), last(n, -1), visited(n, 0), dis(n, 0) {
		edges.clear();
	}

	int addEdge(int from, int to, Flow cap, Cost cost, int id) {
		edges.push_back(Edge(to, cap, cost, last[from],id));
		last[from] = t++;
		edges.push_back(Edge(from, 0, -cost, last[to],id));
		last[to] = t++;
		return t - 2;
	}

	pair<Flow, Cost> minCostFlow(int _S, int _T) {
		S = _S; T = _T;
		SPFA();
		while (1) {
			while (1) {
				rep(i,0,n) visited[i] = 0;
				if (!findFlow(S, INF_FLOW)) break;
			}
			if (!modifyLabel()) break;
		}
		return make_pair(totalFlow, totalCost);
	}

private:
	void SPFA() {
		rep(i,0,n) dis[i] = INF_COST;
		priority_queue< pair<Cost,int> > Q;
		Q.push(make_pair(dis[S]=0, S));
		while (!Q.empty()) {
			int x = Q.top().second;
			Cost d = -Q.top().first;
			Q.pop();
			// For double: dis[x] > d + EPS
			if (dis[x] != d) continue;
			for(int it = last[x]; it >= 0; it = edges[it].next)
				if (edges[it].cap > 0 && dis[edges[it].to] > d + edges[it].cost)
					Q.push(make_pair(-(dis[edges[it].to] = d + edges[it].cost), edges[it].to));
		}
		Cost disT = dis[T]; rep(i,0,n) dis[i] = disT - dis[i];
	}

	Flow findFlow(int x, Flow flow) {
		if (x == T) {
			totalCost += dis[S] * flow;
			totalFlow += flow;
			return flow;
		}
		visited[x] = 1;
		Flow now = flow;
		for(int it = last[x]; it >= 0; it = edges[it].next)
			// For double: fabs(dis[edges[it].to] + edges[it].cost - dis[x]) < EPS
			if (edges[it].cap && !visited[edges[it].to] && dis[edges[it].to] + edges[it].cost == dis[x]) {
				Flow tmp = findFlow(edges[it].to, min(now, edges[it].cap));
				edges[it].cap -= tmp;
				edges[it ^ 1].cap += tmp;
				now -= tmp;
				if (!now) break;
			}
		return flow - now;
	}

	bool modifyLabel() {
		Cost d = INF_COST;
		rep(i,0,n) if (visited[i])
			for(int it = last[i]; it >= 0; it = edges[it].next)
				if (edges[it].cap && !visited[edges[it].to])
					d = min(d, dis[edges[it].to] + edges[it].cost - dis[i]);

		// For double: if (d > INF_COST / 10)     INF_COST = 1e20
		if (d == INF_COST) return false;
		rep(i,0,n) if (visited[i])
			dis[i] += d;
		return true;
	}
};

int n,k;
struct task{
	lli s,t,c,id;
	task(lli s=0,lli t=0,lli c=0, lli id=0):s(s),t(t),c(c),id(id){}
};
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin>>n>>k;
	vector<task> a(n);
	for(int i=0;i<n;i++){
		cin>>a[i].s>>a[i].t>>a[i].c;
		a[i].id=i;
	}
	sort(all(a),[&](const task &x, const task&y){
		return x.s<y.s;
	});
	vector<int> s(n);
	for(int i=0;i<n;i++){
		s[i]=a[i].s;
	}
	int N=n+2;
	MinCostFlow<int,lli> st(N);
	for(int i=0;i<n;i++){
		st.addEdge(i,i+1,k,0,-1);
	}
	st.addEdge(n,n+1,k,0,-1);
	for(int i=0;i<n;i++){
		auto it=lower_bound(all(s),a[i].s+a[i].t);
		int idx=it-s.begin();
		st.addEdge(i+1,idx+1,1,-a[i].c,a[i].id);
	}
	auto ff=st.minCostFlow(0,N-1);
	vector<int> ans(n);
	for(int i=0;i<st.edges.size();i+=2){
		if(st.edges[i].id>=0 and st.edges[i+1].cap){
			ans[st.edges[i].id]=1;
		}
	}
	printvec(ans);
}


#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")

#include <bits/stdc++.h>

using namespace std;

typedef double db;
typedef long long ll;
typedef long double ld;
typedef string str;

typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;
typedef complex<ld> cd;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<ld> vd;
typedef vector<str> vs;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<cd> vcd;

#define FOR(i,a,b) for (int i = (a); i < (b); i++)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); i--)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a : x)

#define mp make_pair
#define pb push_back
#define eb emplace_back
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound

#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define rsz resize
#define ins insert

const int MOD = 1e9+7; // 998244353 = (119<<23)+1
const ll INF = 1e18;
const int MX = 2e5+5;
const ld PI = 4*atan((ld)1);

template<class T> bool ckmin(T& a, const T& b) { return a > b ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/rope>

using namespace __gnu_pbds;
using namespace __gnu_cxx;

template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define ook order_of_key
#define fbo find_by_order

namespace input {
    template<class T> void re(complex<T>& x);
    template<class T1, class T2> void re(pair<T1,T2>& p);
    template<class T> void re(vector<T>& a);
    template<class T, size_t SZ> void re(array<T,SZ>& a);

    template<class T> void re(T& x) { cin >> x; }
    void re(double& x) { string t; re(t); x = stod(t); }
    void re(ld& x) { string t; re(t); x = stold(t); }
    template<class T, class... Ts> void re(T& t, Ts&... ts) {
        re(t); re(ts...);
    }

    template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = cd(a,b); }
    template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
    template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
    template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}

using namespace input;

namespace output {
    void pr(int x) { cout << x; }
    void pr(long x) { cout << x; }
    void pr(ll x) { cout << x; }
    void pr(unsigned x) { cout << x; }
    void pr(unsigned long x) { cout << x; }
    void pr(unsigned long long x) { cout << x; }
    void pr(float x) { cout << x; }
    void pr(double x) { cout << x; }
    void pr(ld x) { cout << x; }
    void pr(char x) { cout << x; }
    void pr(const char* x) { cout << x; }
    void pr(const string& x) { cout << x; }
    void pr(bool x) { pr(x ? "true" : "false"); }
    template<class T> void pr(const complex<T>& x) { cout << x; }

    template<class T1, class T2> void pr(const pair<T1,T2>& x);
    template<class T> void pr(const T& x);

    template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
        pr(t); pr(ts...);
    }
    template<class T1, class T2> void pr(const pair<T1,T2>& x) {
        pr("{",x.f,", ",x.s,"}");
    }
    template<class T> void pr(const T& x) {
        pr("{"); // const iterator needed for vector<bool>
        bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
        pr("}");
    }

    void ps() { pr("\n"); } // print w/ spaces
    template<class T, class... Ts> void ps(const T& t, const Ts&... ts) {
        pr(t); if (sizeof...(ts)) pr(" "); ps(ts...);
    }

    void pc() { pr("]\n"); } // debug w/ commas
    template<class T, class... Ts> void pc(const T& t, const Ts&... ts) {
        pr(t); if (sizeof...(ts)) pr(", "); pc(ts...);
    }
    #define dbg(x...) pr("[",#x,"] = ["), pc(x);
}

using namespace output;

namespace io {
    void setIn(string s) { freopen(s.c_str(),"r",stdin); }
    void setOut(string s) { freopen(s.c_str(),"w",stdout); }
    void setIO(string s = "") {
        cin.sync_with_stdio(0); cin.tie(0); // fast I/O
        cin.exceptions(cin.failbit); // ex. throws exception when you try to read letter into int
        if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
    }
}

using namespace io;

template<class T> T invGeneral(T a, T b) {
	a %= b; if (a == 0) return b == 1 ? 0 : -1;
	T x = invGeneral(b,a);
	return x == -1 ? -1 : ((1-(ll)b*x)/a+b)%b;
}

template<class T> struct modular {
	T val;
	explicit operator T() const { return val; }
	modular() { val = 0; }
	modular(const ll& v) {
		val = (-MOD <= v && v <= MOD) ? v : v % MOD;
		if (val < 0) val += MOD;
	}

	// friend ostream& operator<<(ostream& os, const modular& a) { return os << a.val; }
	friend void pr(const modular& a) { pr(a.val); }
	friend void re(modular& a) { ll x; re(x); a = modular(x); }

	friend bool operator==(const modular& a, const modular& b) { return a.val == b.val; }
	friend bool operator!=(const modular& a, const modular& b) { return !(a == b); }
	friend bool operator<(const modular& a, const modular& b) { return a.val < b.val; }

	modular operator-() const { return modular(-val); }
	modular& operator+=(const modular& m) { if ((val += m.val) >= MOD) val -= MOD; return *this; }
	modular& operator-=(const modular& m) { if ((val -= m.val) < 0) val += MOD; return *this; }
	modular& operator*=(const modular& m) { val = (ll)val*m.val%MOD; return *this; }
	friend modular pow(modular a, ll p) {
		modular ans = 1; for (; p; p /= 2, a *= a) if (p&1) ans *= a;
		return ans;
	}
	friend modular inv(const modular& a) {
		auto i = invGeneral(a.val,MOD); assert(i != -1);
		return i;
	} // equivalent to return exp(b,MOD-2) if MOD is prime
	modular& operator/=(const modular& m) { return (*this) *= inv(m); }

	friend modular operator+(modular a, const modular& b) { return a += b; }
	friend modular operator-(modular a, const modular& b) { return a -= b; }
	friend modular operator*(modular a, const modular& b) { return a *= b; }

	friend modular operator/(modular a, const modular& b) { return a /= b; }
};

typedef modular<int> mi;
typedef pair<mi,mi> pmi;
typedef vector<mi> vmi;
typedef vector<pmi> vpmi;

template<class T> using pqg = priority_queue<T,vector<T>,greater<T>>;
template<class T> T poll(pqg<T>& x) {
	T y = x.top(); x.pop();
	return y;
}

template<int SZ> struct mcmf {
	typedef ll F; typedef ll C;
	struct Edge { int to, rev; F flow, cap; C cost; int id; };
	vector<Edge> adj[SZ];
	void addEdge(int u, int v, F cap, C cost, int id) {
		assert(cap >= 0);
		Edge a{v, sz(adj[v]), 0, cap, cost,id}, b{u, sz(adj[u]), 0, 0, -cost,-MOD};
		adj[u].pb(a), adj[v].pb(b);
	}

	int N, s, t;
	pi pre[SZ]; // previous vertex, edge label on path
	pair<C,F> cost[SZ]; // tot cost of path, amount of flow
	C totCost, curCost; F totFlow;
	void reweight() {
		// ensures all non-negative edge weights, destroys original
		F0R(i,N) trav(p,adj[i]) p.cost += cost[i].f-cost[p.to].f;
	}
	bool spfa() { // reweighting will ensure that there will be negative weights only during the first time you run this
		F0R(i,N) cost[i] = {INF,0}; cost[s] = {0,INF};
		pqg<pair<ll,int>> todo; todo.push({0,s});
		while (sz(todo)) {
			auto x = poll(todo); if (x.f > cost[x.s].f) continue;
			trav(a,adj[x.s]) if (x.f+a.cost < cost[a.to].f && a.flow < a.cap) {
				// if costs are doubles, add EPS to ensure that
				// algo does not traverse 0-weight cycle repeatedly
				pre[a.to] = {x.s,a.rev};
				cost[a.to] = {x.f+a.cost,min(a.cap-a.flow,cost[x.s].s)};
				todo.push({cost[a.to].f,a.to});
			}
		}
		curCost += cost[t].f; return cost[t].s;
	}
	void backtrack() {
		auto f = cost[t].s; totFlow += f, totCost += curCost*f;
		for (int x = t; x != s; x = pre[x].f) {
			adj[x][pre[x].s].flow -= f;
			adj[pre[x].f][adj[x][pre[x].s].rev].flow += f;
		}
	}

	pair<F,C> calc(int _N, int _s, int _t) {
		N = _N; s = _s, t = _t; totFlow = totCost = curCost = 0;
		spfa();
		while (1) {
			reweight();
			if (!spfa()) return {totFlow, totCost};
			backtrack();
		}
	}
};

int n,k;
mcmf<2002> m;

vector<array<int,3>> compress(vector<array<int,3>> v) {
    map<int,int> m;
    trav(t,v) m[t[0]] = m[t[1]] = 0;
    int co = 0;
    trav(t,m) t.s = ++co;
    trav(t,v) t[0] = m[t[0]], t[1] = m[t[1]];
    return v;
}

bool ans[1001];

int main() {
    setIO(); re(n,k);
    vector<array<int,3>> v(n);
    re(v); trav(t,v) t[1] += t[0];
    auto V = compress(v);
    m.addEdge(0,1,k,0,-1);
    FOR(i,2,2002) m.addEdge(i-1,i,INF,0,-1);
    int co = 0;
    trav(t,V) m.addEdge(t[0],t[1],1,-t[2],++co);
    m.calc(2002,0,2001);
    F0R(i,2002) trav(t,m.adj[i]) if (t.flow > 0) if (t.id > 0) ans[t.id] = 1;
    FOR(i,1,n+1) {
    	if (ans[i]) pr(1);
    	else pr(0);
    	pr(' ');
    }
}

/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?), set tle
	* do smth instead of nothing and stay organized
*/


#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")

#include <bits/stdc++.h>

using namespace std;

typedef double db;
typedef long long ll;
typedef long double ld;
typedef string str;

typedef pair<int, int> pi;
typedef pair<ll,ll> pl;
typedef pair<ld,ld> pd;
typedef complex<ld> cd;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<ld> vd;
typedef vector<str> vs;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<cd> vcd;

#define FOR(i,a,b) for (int i = (a); i < (b); i++)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); i--)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a : x)

#define mp make_pair
#define pb push_back
#define eb emplace_back
#define f first
#define s second
#define lb lower_bound
#define ub upper_bound

#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define rsz resize
#define ins insert

const int MOD = 1e9+7; // 998244353 = (119<<23)+1
const ll INF = 1e18;
const int MX = 2e5+5;
const ld PI = 4*atan((ld)1);

template<class T> bool ckmin(T& a, const T& b) { return a > b ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; }

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/rope>

using namespace __gnu_pbds;
using namespace __gnu_cxx;

template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define ook order_of_key
#define fbo find_by_order

namespace input {
    template<class T> void re(complex<T>& x);
    template<class T1, class T2> void re(pair<T1,T2>& p);
    template<class T> void re(vector<T>& a);
    template<class T, size_t SZ> void re(array<T,SZ>& a);

    template<class T> void re(T& x) { cin >> x; }
    void re(double& x) { string t; re(t); x = stod(t); }
    void re(ld& x) { string t; re(t); x = stold(t); }
    template<class T, class... Ts> void re(T& t, Ts&... ts) {
        re(t); re(ts...);
    }

    template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = cd(a,b); }
    template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
    template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
    template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}

using namespace input;

namespace output {
    void pr(int x) { cout << x; }
    void pr(long x) { cout << x; }
    void pr(ll x) { cout << x; }
    void pr(unsigned x) { cout << x; }
    void pr(unsigned long x) { cout << x; }
    void pr(unsigned long long x) { cout << x; }
    void pr(float x) { cout << x; }
    void pr(double x) { cout << x; }
    void pr(ld x) { cout << x; }
    void pr(char x) { cout << x; }
    void pr(const char* x) { cout << x; }
    void pr(const string& x) { cout << x; }
    void pr(bool x) { pr(x ? "true" : "false"); }
    template<class T> void pr(const complex<T>& x) { cout << x; }

    template<class T1, class T2> void pr(const pair<T1,T2>& x);
    template<class T> void pr(const T& x);

    template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
        pr(t); pr(ts...);
    }
    template<class T1, class T2> void pr(const pair<T1,T2>& x) {
        pr("{",x.f,", ",x.s,"}");
    }
    template<class T> void pr(const T& x) {
        pr("{"); // const iterator needed for vector<bool>
        bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
        pr("}");
    }

    void ps() { pr("\n"); } // print w/ spaces
    template<class T, class... Ts> void ps(const T& t, const Ts&... ts) {
        pr(t); if (sizeof...(ts)) pr(" "); ps(ts...);
    }

    void pc() { pr("]\n"); } // debug w/ commas
    template<class T, class... Ts> void pc(const T& t, const Ts&... ts) {
        pr(t); if (sizeof...(ts)) pr(", "); pc(ts...);
    }
    #define dbg(x...) pr("[",#x,"] = ["), pc(x);
}

using namespace output;

namespace io {
    void setIn(string s) { freopen(s.c_str(),"r",stdin); }
    void setOut(string s) { freopen(s.c_str(),"w",stdout); }
    void setIO(string s = "") {
        cin.sync_with_stdio(0); cin.tie(0); // fast I/O
        cin.exceptions(cin.failbit); // ex. throws exception when you try to read letter into int
        if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
    }
}

using namespace io;

template<class T> T invGeneral(T a, T b) {
	a %= b; if (a == 0) return b == 1 ? 0 : -1;
	T x = invGeneral(b,a);
	return x == -1 ? -1 : ((1-(ll)b*x)/a+b)%b;
}

template<class T> struct modular {
	T val;
	explicit operator T() const { return val; }
	modular() { val = 0; }
	modular(const ll& v) {
		val = (-MOD <= v && v <= MOD) ? v : v % MOD;
		if (val < 0) val += MOD;
	}

	// friend ostream& operator<<(ostream& os, const modular& a) { return os << a.val; }
	friend void pr(const modular& a) { pr(a.val); }
	friend void re(modular& a) { ll x; re(x); a = modular(x); }

	friend bool operator==(const modular& a, const modular& b) { return a.val == b.val; }
	friend bool operator!=(const modular& a, const modular& b) { return !(a == b); }
	friend bool operator<(const modular& a, const modular& b) { return a.val < b.val; }

	modular operator-() const { return modular(-val); }
	modular& operator+=(const modular& m) { if ((val += m.val) >= MOD) val -= MOD; return *this; }
	modular& operator-=(const modular& m) { if ((val -= m.val) < 0) val += MOD; return *this; }
	modular& operator*=(const modular& m) { val = (ll)val*m.val%MOD; return *this; }
	friend modular pow(modular a, ll p) {
		modular ans = 1; for (; p; p /= 2, a *= a) if (p&1) ans *= a;
		return ans;
	}
	friend modular inv(const modular& a) {
		auto i = invGeneral(a.val,MOD); assert(i != -1);
		return i;
	} // equivalent to return exp(b,MOD-2) if MOD is prime
	modular& operator/=(const modular& m) { return (*this) *= inv(m); }

	friend modular operator+(modular a, const modular& b) { return a += b; }
	friend modular operator-(modular a, const modular& b) { return a -= b; }
	friend modular operator*(modular a, const modular& b) { return a *= b; }

	friend modular operator/(modular a, const modular& b) { return a /= b; }
};

typedef modular<int> mi;
typedef pair<mi,mi> pmi;
typedef vector<mi> vmi;
typedef vector<pmi> vpmi;

template<class T> using pqg = priority_queue<T,vector<T>,greater<T>>;
template<class T> T poll(pqg<T>& x) {
	T y = x.top(); x.pop();
	return y;
}

template<int SZ> struct mcmf {
	typedef ll F; typedef ll C;
	struct Edge { int to, rev; F flow, cap; C cost; int id; };
	vector<Edge> adj[SZ];
	void addEdge(int u, int v, F cap, C cost, int id) {
		assert(cap >= 0);
		Edge a{v, sz(adj[v]), 0, cap, cost,id}, b{u, sz(adj[u]), 0, 0, -cost,-MOD};
		adj[u].pb(a), adj[v].pb(b);
	}

	int N, s, t;
	pi pre[SZ]; // previous vertex, edge label on path
	pair<C,F> cost[SZ]; // tot cost of path, amount of flow
	C totCost, curCost; F totFlow;
	void reweight() {
		// ensures all non-negative edge weights, destroys original
		F0R(i,N) trav(p,adj[i]) p.cost += cost[i].f-cost[p.to].f;
	}
	bool spfa() { // reweighting will ensure that there will be negative weights only during the first time you run this
		F0R(i,N) cost[i] = {INF,0}; cost[s] = {0,INF};
		pqg<pair<ll,int>> todo; todo.push({0,s});
		while (sz(todo)) {
			auto x = poll(todo); if (x.f > cost[x.s].f) continue;
			trav(a,adj[x.s]) if (x.f+a.cost < cost[a.to].f && a.flow < a.cap) {
				// if costs are doubles, add EPS to ensure that
				// algo does not traverse 0-weight cycle repeatedly
				pre[a.to] = {x.s,a.rev};
				cost[a.to] = {x.f+a.cost,min(a.cap-a.flow,cost[x.s].s)};
				todo.push({cost[a.to].f,a.to});
			}
		}
		curCost += cost[t].f; return cost[t].s;
	}
	void backtrack() {
		auto f = cost[t].s; totFlow += f, totCost += curCost*f;
		for (int x = t; x != s; x = pre[x].f) {
			adj[x][pre[x].s].flow -= f;
			adj[pre[x].f][adj[x][pre[x].s].rev].flow += f;
		}
	}

	pair<F,C> calc(int _N, int _s, int _t) {
		N = _N; s = _s, t = _t; totFlow = totCost = curCost = 0;
		while (spfa()) reweight(), backtrack();
		return {totFlow, totCost};
	}
};

int n,k;
mcmf<2002> m;

vector<array<int,3>> compress(vector<array<int,3>> v) {
    map<int,int> m;
    trav(t,v) m[t[0]] = m[t[1]] = 0;
    int co = 0;
    trav(t,m) t.s = ++co;
    trav(t,v) t[0] = m[t[0]], t[1] = m[t[1]];
    return v;
}

bool ans[1001];

int main() {
    setIO(); re(n,k);
    vector<array<int,3>> v(n);
    re(v); trav(t,v) t[1] += t[0];
    auto V = compress(v);
    m.addEdge(0,1,k,0,-1);
    FOR(i,2,2002) m.addEdge(i-1,i,INF,0,-1);
    int co = 0;
    trav(t,V) m.addEdge(t[0],t[1],1,-t[2],++co);
    m.calc(2002,0,2001);
    F0R(i,2002) trav(t,m.adj[i]) if (t.flow > 0) if (t.id > 0) ans[t.id] = 1;
    FOR(i,1,n+1) {
    	if (ans[i]) pr(1);
    	else pr(0);
    	pr(' ');
    }
}

/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?), set tle
	* do smth instead of nothing and stay organized
*/