#pragma GCC optimize("Ofast")  // remove in mingw32 bit ;
#pragma GCC target("avx,avx2,fma")
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#define ALL(x) x.begin(),x.end()
#define PB push_back
#define EB emplace_back
#define F first
#define S second
#define ll long long
#define double long double
#define MP make_pair
// #define int long long
// #define MAX LONG_LONG_MAX
// #define MIN LONG_LONG_MIN

using namespace std;

#ifdef CUST_DEBUG
template<class K, class V>ostream& operator<<(ostream&s,const pair<K,V>&p){s<<'<'<<p.F<<','<<p.S<<'>';return s;}
template<class T, class=typename T::value_type, class=typename enable_if<!is_same<T,string>::value>::type>
ostream& operator<<(ostream&s,const T&v){s<<'[';for(auto&x:v){s<<x<<", ";}if(!v.empty()){s<<"\b\b";}s<<']';return s;}
void __prnt(){cerr<<endl;} template<class T, class...Ts>void __prnt(T&&a,Ts&&...etc){cerr<<a<<' ';__prnt(etc...);}
#define print(...) __prnt(__VA_ARGS__)
#else
#define print(...)
template<typename A> ostream& operator<<(ostream &cout, vector<A> const &v);
template<typename A, typename B> ostream& operator<<(ostream &cout, pair<A, B> const &p){return cout<<"("<<p.F<<", "<<p.S<<")";}
template<typename A> ostream& operator<<(ostream &cout,vector<A> const &v){cout<<"[";for(int i=0;i<v.size();i++){if(i)cout<<", ";cout<<v[i];}return cout<<"]";}
template<typename A, typename B> istream& operator>>(istream& cin, pair<A, B> &p){cin>>p.F;return cin>>p.S;}
#endif

const long long MAXN = 2e6 +7;

ll suf[MAXN] = {0} ,a[MAXN] ,idx[MAXN] ,op[MAXN];

void check(){
	ll order = -1 ,n ,m;
	cin >> n >> m;
	for(ll i = 1 ;i <= n ;i++){
		cin >> a[i];
	}

	for(ll i =  1; i <= m ;i++){
		cin >> op[i] >> idx[i];
	}

	for(ll i = m ;i > 0 ;i--){
		suf[i] = max(suf[i + 1] , idx[i]);
	}
	ll last = 1e10;
	for(ll i = 1 ;i <= m ;i++){
		ll o = op[i] ,id = idx[i];
		if(id < suf[i]) continue;
		if(order == o && last >= id) continue;
		order = o;
		last = min(last ,id);
// 		cout << MP(last ,order);
		if(o == 1) sort(a+1 ,a+id+1);
		else sort(a+1 ,a+id+1 ,greater<ll>());
	}
	for(ll i = 1 ;i <= n ;i++) cout << a[i] <<" \n"[i == n];
}

int32_t main(){
	#ifndef CUST_DEBUG
	ios_base::sync_with_stdio(false); cin.tie(NULL);
	#endif
	// cin.exceptions(cin.Failbit);
	int t = 1;
	// cin >> t;
	for(int i = 1 ; i <= t ;i++){
		// cout << "Case "<< i << ":\n";
		check();
	}
	return 0;
}


#pragma GCC optimize("Ofast")  // remove in mingw32 bit ;
#pragma GCC target("avx,avx2,fma")
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
#define ALL(x) x.begin(),x.end()
#define PB push_back
#define EB emplace_back
#define F first
#define S second
#define ll long long
#define double long double
#define MP make_pair
// #define int long long
// #define MAX LONG_LONG_MAX
// #define MIN LONG_LONG_MIN

using namespace std;

#ifdef CUST_DEBUG
template<class K, class V>ostream& operator<<(ostream&s,const pair<K,V>&p){s<<'<'<<p.F<<','<<p.S<<'>';return s;}
template<class T, class=typename T::value_type, class=typename enable_if<!is_same<T,string>::value>::type>
ostream& operator<<(ostream&s,const T&v){s<<'[';for(auto&x:v){s<<x<<", ";}if(!v.empty()){s<<"\b\b";}s<<']';return s;}
void __prnt(){cerr<<endl;} template<class T, class...Ts>void __prnt(T&&a,Ts&&...etc){cerr<<a<<' ';__prnt(etc...);}
#define print(...) __prnt(__VA_ARGS__)
#else
#define print(...)
template<typename A> ostream& operator<<(ostream &cout, vector<A> const &v);
template<typename A, typename B> ostream& operator<<(ostream &cout, pair<A, B> const &p){return cout<<"("<<p.F<<", "<<p.S<<")";}
template<typename A> ostream& operator<<(ostream &cout,vector<A> const &v){cout<<"[";for(int i=0;i<v.size();i++){if(i)cout<<", ";cout<<v[i];}return cout<<"]";}
template<typename A, typename B> istream& operator>>(istream& cin, pair<A, B> &p){cin>>p.F;return cin>>p.S;}
#endif

const long long MAXN = 2e6 +7;

ll suf[MAXN] = {0} ,a[MAXN] ,idx[MAXN] ,op[MAXN] ,cnt[MAXN] = {0};

void check(){
	ll order = -1 ,n ,m;
	cin >> n >> m;
	for(ll i = 1 ;i <= n ;i++){
		cin >> a[i];
	}

	for(ll i =  1; i <= m ;i++){
		cin >> op[i] >> idx[i];
		cnt[idx[i]]++;
	}

	for(ll i = m ;i > 0 ;i--){
		suf[i] = max(suf[i + 1] , idx[i]);
	}
	ll last = 1e10;
	for(ll i = 1 ;i <= m ;i++){
		ll o = op[i] ,id = idx[i];
		if(cnt[id] > 1){cnt[id]--;continue;}
		cnt[i]--;
		if(id < suf[i]) continue;
		if(order == o && last >= id) continue;
		order = o;
		last = min(last ,id);
// 		cout << MP(last ,order);
		if(o == 1) sort(a+1 ,a+id+1);
		else sort(a+1 ,a+id+1 ,greater<ll>());
	}
	for(ll i = 1 ;i <= n ;i++) cout << a[i] <<" \n"[i == n];
}

int32_t main(){
	#ifndef CUST_DEBUG
	ios_base::sync_with_stdio(false); cin.tie(NULL);
	#endif
	// cin.exceptions(cin.Failbit);
	int t = 1;
	// cin >> t;
	for(int i = 1 ; i <= t ;i++){
		// cout << "Case "<< i << ":\n";
		check();
	}
	return 0;
}


#include<bits/stdc++.h>

using namespace std;
const int MAXN = 100100;

int v[MAXN];

int main(){

	deque<pair<int,int>> s;

	int n,m;
	cin >> n >> m;

	for(int i = 1;i <= n;i++){
		cin >> v[i];
	}

	vector<pair<int,int>> vec;
	//
	for(int i = 1;i <= m;i++){
		pair<int,int> q;
		cin >> q.first >> q.second;

		vec.push_back(q);
	}

	for(int i = 0;i < vec.size();i++){
		pair<int,int> q = vec[i];
		while(!s.empty() && s.back().second <= q.second) s.pop_back();
		s.push_back(q);
	}

	if(!s.empty()) sort(v + 1,v + (int) s.front().second + 1);

	int p1 = s.front().second;
	int p2 = 1;

	vector<int> resp;

	int tam;
	if(s.empty()) tam = 0;
	else tam = s.front().second;

	for(int i = n;i > tam;i--){
		resp.push_back(v[i]);
	}

	//for(int i = 1;i <= s.front().second;i++) cout << "a " << v[i] << endl;

	while(!s.empty()){
		int lado = s.front().first;
		int h = s.front().second;
		int r;

		//cout << "// " << lado << " " << h << endl;

		s.pop_front();

		if(s.empty()) r = h;
		else r = h - s.front().second;

		if(lado == 2){
			for(int i = 1;i <= r;i++) resp.push_back(v[p2]) , p2++;
		}
		else{
			for(int i = 1;i <= r;i++) resp.push_back(v[p1]) , p1--;
		}
	}

	for(int i = resp.size()-1; i >= 0;i--) cout << resp[i] << " ";

}


#include<bits/stdc++.h>

using namespace std;
const int MAXN = 100100;

int v[MAXN];

int main(){

	deque<pair<int,int>> s;

	int n,m;
	cin >> n >> m;

	for(int i = 1;i <= n;i++){
		cin >> v[i];
	}

	vector<pair<int,int>> vec;

	for(int i = 1;i <= m;i++){
		pair<int,int> q;
		cin >> q.first >> q.second;

		vec.push_back(q);
	}

	for(int i = 0;i < vec.size();i++){
		pair<int,int> q = vec[i];
		while(!s.empty() && s.back().second <= q.second) s.pop_back();
		s.push_back(q);
	}

	if(!s.empty()) sort(v + 1,v + (int) s.front().second + 1);

	int p1 = s.front().second;
	int p2 = 1;

	vector<int> resp;

	int tam;
	if(s.empty()) tam = 0;
	else tam = s.front().second;

	for(int i = n;i > tam;i--){
		resp.push_back(v[i]);
	}

	//for(int i = 1;i <= s.front().second;i++) cout << "a " << v[i] << endl;

	while(!s.empty()){
		int lado = s.front().first;
		int h = s.front().second;
		int r;

		//cout << "// " << lado << " " << h << endl;

		s.pop_front();

		if(s.empty()) r = h;
		else r = h - s.front().second;

		if(lado == 2){
			for(int i = 1;i <= r;i++) resp.push_back(v[p2]) , p2++;
		}
		else{
			for(int i = 1;i <= r;i++) resp.push_back(v[p1]) , p1--;
		}
	}

	for(int i = resp.size()-1; i >= 0;i--) cout << resp[i] << " ";

}


#include<bits/stdc++.h>

using namespace std;
const int MAXN = 100100;

int v[MAXN];

int main(){

	deque<pair<int,int>> s;

	int n,m;
	cin >> n >> m;

	for(int i = 1;i <= n;i++){
		cin >> v[i];
	}

	vector<pair<int,int>> vec;

	for(int i = 1;i <= m;i++){
		pair<int,int> q;
		cin >> q.first >> q.second;

		vec.push_back(q);
	}

	for(int i = 0;i < vec.size();i++){
		pair<int,int> q = vec[i];
		while(!s.empty() && s.back().second <= q.second) s.pop_back();
		s.push_back(q);
	}

	if(!s.empty()) sort(v + 1,v + (int) s.front().second + 1);

	int p1 = s.front().second;
	int p2 = 1;

	vector<int> resp;

	int tam;
	if(s.empty()) tam = 0;
	else tam = s.front().second;

	for(int i = n;i > tam;i--){
		resp.push_back(v[i]);
	}

	for(int i = 1;i <= s.front().second;i++) cout << "a " << v[i] << endl;

	while(!s.empty()){
		int lado = s.front().first;
		int h = s.front().second;
		int r;

		//cout << "// " << lado << " " << h << endl;

		s.pop_front();

		if(s.empty()) r = h;
		else r = h - s.front().second;

		if(lado == 2){
			for(int i = 1;i <= r;i++) resp.push_back(v[p2]) , p2++;
		}
		else{
			for(int i = 1;i <= r;i++) resp.push_back(v[p1]) , p1--;
		}
	}

	for(int i = resp.size()-1; i >= 0;i--) cout << resp[i] << " ";

}


#include<bits/stdc++.h>

using namespace std;
const int MAXN = 100100;

int v[MAXN];

int main(){

	deque<pair<int,int>> s;

	int n,m;
	cin >> n >> m;

	for(int i = 1;i <= n;i++){
		cin >> v[i];
	}

	vector<pair<int,int>> vec;

	for(int i = 1;i <= m;i++){
		pair<int,int> q;
		cin >> q.first >> q.second;

		vec.push_back(q);
	}

	for(int i = 0;i < vec.size();i++){
		pair<int,int> q = vec[i];
		while(!s.empty() && s.back().second <= q.second) s.pop_back();
		s.push_back(q);
	}

	if(!s.empty()) sort(v + 1,v + s.front().second);

	int p1 = s.front().second;
	int p2 = 1;

	vector<int> resp;

	int tam;
	if(s.empty()) tam = 0;
	else tam = s.front().second;

	for(int i = n;i > tam;i--){
		resp.push_back(v[i]);
	}

	while(!s.empty()){
		int lado = s.front().first;
		int h = s.front().second;
		int r;

		//cout << "// " << lado << " " << h << endl;

		s.pop_front();

		if(s.empty()) r = h;
		else r = h - s.front().second;

		if(lado == 2){
			for(int i = 1;i <= r;i++) resp.push_back(v[p2]) , p2++;
		}
		else{
			for(int i = 1;i <= r;i++) resp.push_back(v[p1]) , p1--;
		}
	}

	for(int i = resp.size()-1; i >= 0;i--) cout << resp[i] << " ";

}


#include<bits/stdc++.h>

using namespace std;
const int MAXN = 200100;

int v[MAXN];

int main(){

	deque<pair<int,int>> s;

	int n,m;
	cin >> n >> m;

	for(int i = 1;i <= n;i++){
		cin >> v[i];
	}

	vector<pair<int,int>> vec;

	for(int i = 1;i <= m;i++){
		pair<int,int> q;
		cin >> q.first >> q.second;

		vec.push_back(q);
	}

	for(int i = 0;i < vec.size();i++){
		pair<int,int> q = vec[i];
		while(!s.empty() && s.back().second <= q.second) s.pop_back();
		s.push_back(q);
	}

	if(!s.empty()) sort(v + 1,v + (int) s.front().second + 1);

	int p1 = s.front().second;
	int p2 = 1;

	vector<int> resp;

	int tam;
	if(s.empty()) tam = 0;
	else tam = s.front().second;

	for(int i = n;i > tam;i--){
		resp.push_back(v[i]);
	}

	//for(int i = 1;i <= s.front().second;i++) cout << "a " << v[i] << endl;

	while(!s.empty()){
		int lado = s.front().first;
		int h = s.front().second;
		int r;

		//cout << "// " << lado << " " << h << endl;

		s.pop_front();

		if(s.empty()) r = h;
		else r = h - s.front().second;

		if(lado == 2){
			for(int i = 1;i <= r;i++) resp.push_back(v[p2]) , p2++;
		}
		else{
			for(int i = 1;i <= r;i++) resp.push_back(v[p1]) , p1--;
		}
	}

	for(int i = resp.size()-1; i >= 0;i--) cout << resp[i] << " ";

}


#include<bits/stdc++.h>

using namespace std;
const int MAXN = 100100;

int v[MAXN];

int main(){

	deque<pair<int,int>> s;

	int n,m;
	cin >> n >> m;

	for(int i = 1;i <= n;i++){
		cin >> v[i];
	}

	vector<pair<int,int>> vec;

	for(int i = 1;i <= m;i++){
		pair<int,int> q;
		cin >> q.first >> q.second;

		vec.push_back(q);
	}

	for(int i = 0;i < vec.size();i++){
		pair<int,int> q = vec[i];
		while(!s.empty() && s.back().second <= q.second) s.pop_back();
		s.push_back(q);
	}

	if(!s.empty()) sort(v + 1,v + (int) s.front().second + 1);

	int p1 = s.front().second;
	int p2 = 1;

	vector<int> resp;

	int tam;
	if(s.empty()) tam = 0;
	else tam = s.front().second;

	for(int i = n;i > tam;i--){
		resp.push_back(v[i]);
	}

	//for(int i = 1;i <= s.front().second;i++) cout << "a " << v[i] << endl;

	while(!s.empty()){
		int lado = s.front().first;
		int h = s.front().second;
		int r;

		//cout << "// " << lado << " " << h << endl;

		s.pop_front();

		if(s.empty()) r = h;
		else r = h - s.front().second;

		if(lado == 2){
			for(int i = 1;i <= r;i++) resp.push_back(v[p2]) , p2++;
		}
		else{
			for(int i = 1;i <= r;i++) resp.push_back(v[p1]) , p1--;
		}
	}
	//
	for(int i = resp.size()-1; i >= 0;i--) cout << resp[i] << " ";

}


#include<bits/stdc++.h>

#define EB emplace_back
#define int long long
#define F first
#define S second
#define N 100005
#define ALL(x) x.begin(),x.end()
#define endl '\n'

using namespace std;

int32_t main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

int tt=1;
//cin>>tt;
while(tt--)
{
int n,m; cin>>n>>m;
int arr[n];
for(auto &x : arr) cin>>x;
vector<pair<int,int>> v(m);
for(auto &[x,y] : v) {
	cin>>x>>y;
	x-=1;
	y-=1;
}
reverse(ALL(v));

int curr = -1;
vector<pair<int,int>> A;

for(auto &[x,y] : v)
{
	if ( y > curr)
	{
		A.EB(x,y);
		curr = y;
	}
}
reverse(ALL(A));

int size = A.size();
for (int i = 1; i < size - 1; i++)
{
	if (A[i].F == A[i-1].F)
	{
		A.erase(A.begin() + i,A.begin() + i + 1);
	}
}
// for(auto x : A) cout<<x.F<<" "<<x.S<<endl;
// exit(0);
vector<int> Ans;

size = A.size();

int l = 0;
int r = n - 1;
while (r > A[0].S)
{
	Ans.EB(arr[r--]);
}
sort(arr,arr+r+1);

for (int i = 0; i < size - 1; i++)
{
	int cnt = A[i].S - A[i+1].S;
	while (cnt--)
	{
		if(A[i].F == 0) Ans.EB(arr[r--]);
		else Ans.EB(arr[l++]);
	}
}
	while(r >= l)
	{
		if(A[size - 1].F == 0) Ans.EB(arr[r--]);
		else Ans.EB(arr[l++]);
	}

reverse(ALL(Ans));
for(auto x : Ans) cout<<x<< " ";
}
return 0;

}


#include<bits/stdc++.h>

#define EB emplace_back
#define int long long
#define F first
#define S second
#define N 100005
#define ALL(x) x.begin(),x.end()
#define endl '\n'

using namespace std;

int32_t main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

int tt=1;
//cin>>tt;
while(tt--)
{
int n,m; cin>>n>>m;
int arr[n];
for(auto &x : arr) cin>>x;
vector<pair<int,int>> v(m);
for(auto &[x,y] : v) {
	cin>>x>>y;
	x-=1;
	y-=1;
}
reverse(ALL(v));

int curr = -1;
vector<pair<int,int>> A;

for(auto &[x,y] : v)
{
	if ( y > curr)
	{
		A.EB(x,y);
		curr = y;
	}
}
reverse(ALL(A));

int size = A.size();
//?for (int i = 1; i < size - 1; i++)
//?{
	//?if (A[i].F == A[i-1].F)
	//?{
		//?A.erase(A.begin() + i,A.begin() + i + 1);
	//?}
//?}
// for(auto x : A) cout<<x.F<<" "<<x.S<<endl;
// exit(0);
vector<int> Ans;

size = A.size();

int l = 0;
int r = n - 1;
while (r > A[0].S)
{
	Ans.EB(arr[r--]);
}
sort(arr,arr+r+1);

for (int i = 0; i < size - 1; i++)
{
	int cnt = A[i].S - A[i+1].S;
	while (cnt--)
	{
		if(A[i].F == 0) Ans.EB(arr[r--]);
		else Ans.EB(arr[l++]);
	}
}
	while(r >= l)
	{
		if(A[size - 1].F == 0) Ans.EB(arr[r--]);
		else Ans.EB(arr[l++]);
	}

reverse(ALL(Ans));
for(auto x : Ans) cout<<x<< " ";
}
return 0;

}


#include<bits/stdc++.h>

#define EB emplace_back
#define int long long
#define F first
#define S second
#define N 100005
#define ALL(x) x.begin(),x.end()
#define endl '\n'

using namespace std;

int32_t main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

int tt=1;
//cin>>tt;
while(tt--)
{
int n,m; cin>>n>>m;
int arr[n];
for(auto &x : arr) cin>>x;
vector<pair<int,int>> v(m);
for(auto &[x,y] : v) {
	cin>>x>>y;
	x-=1;
	y-=1;
}
reverse(ALL(v));

int curr = 0;
vector<pair<int,int>> A;

for(auto &[x,y] : v)
{
	if ( y > curr)
	{
		A.EB(x,y);
		curr = y;
	}
}
reverse(ALL(A));
multiset<int> mul;
for (auto x : arr) mul.insert(x);
int size = A.size();
for (int i = 1; i < size; i++)
{
	if (A[i].F == A[i-1].F)
	{
		A.erase(A.begin() + i,A.begin() + i + 1);
	}
}
// for(auto x : A) cout<<x.F<<" "<<x.S<<endl;
// exit(0);
vector<int> Ans;

size = A.size();

int l = 0;
int r = n - 1;
while (r > A[0].S)
{
	Ans.EB(arr[r--]);
}
sort(arr,arr+r+1);

for (int i = 0; i < size - 1; i++)
{
	int cnt = A[i].S - A[i+1].S;
	while (cnt--)
	{
		if(A[i].F == 0) Ans.EB(arr[r--]);
		else Ans.EB(arr[l++]);
	}
}
	while(r >= l)
	{
		if(A[size - 1].F == 0) Ans.EB(arr[r--]);
		else Ans.EB(arr[l++]);
	}

reverse(ALL(Ans));
for(auto x : Ans) cout<<x<< " ";
}
return 0;

}


#include<bits/stdc++.h>

#define EB emplace_back
#define int long long
#define F first
#define S second
#define N 100005
#define ALL(x) x.begin(),x.end()
#define endl '\n'

using namespace std;

int32_t main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

int tt=1;
//cin>>tt;
while(tt--)
{
int n,m; cin>>n>>m;
int arr[n];
for(auto &x : arr) cin>>x;
vector<pair<int,int>> v(m);
for(auto &[x,y] : v) {
	cin>>x>>y;
	x-=1;
	y-=1;
}
reverse(ALL(v));

int curr = 0;
vector<pair<int,int>> A;

for(auto &[x,y] : v)
{
	if ( y > curr)
	{
		A.EB(x,y);
		curr = y;
	}
}
reverse(ALL(A));
multiset<int> mul;
for (auto x : arr) mul.insert(x);
int size = A.size();
for (int i = 1; i < size - 1; i++)
{
	if (A[i].F == A[i-1].F)
	{
		A.erase(A.begin() + i,A.begin() + i + 1);
	}
}
// for(auto x : A) cout<<x.F<<" "<<x.S<<endl;
// exit(0);
vector<int> Ans;

size = A.size();

int l = 0;
int r = n - 1;
while (r > A[0].S)
{
	Ans.EB(arr[r--]);
}
sort(arr,arr+r+1);

for (int i = 0; i < size - 1; i++)
{
	int cnt = A[i].S - A[i+1].S;
	while (cnt--)
	{
		if(A[i].F == 0) Ans.EB(arr[r--]);
		else Ans.EB(arr[l++]);
	}
}
	while(r >= l)
	{
		if(A[size - 1].F == 0) Ans.EB(arr[r--]);
		else Ans.EB(arr[l++]);
	}

reverse(ALL(Ans));
for(auto x : Ans) cout<<x<< " ";
}
return 0;

}


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

#define lli long long int
#define db double
#define ll long long
#define ld long double
#define li long int
#define pb push_back
#define mp make_pair
#define FOR(i,a,b) for(i=a;i<b;i++)
#define RFOR(i,a,b) for(i=a;i>b;i--)
#define ff first
#define ss second
#define fast ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);srand(time(NULL));
#define MOD 1000000007

bool isprime(ll n)
{

            if (n <= 1)  return false;
            if (n <= 3)  return true;

            if (n%2 == 0 || n%3 == 0)
                return false;

            for (ll i=5; i*i<=n; i=i+6)
            {
                if (n%i == 0 || n%(i+2) == 0)
                   return false;
            }

            return true;
}
int main()
{
    ll n,m,i,ma=-1,t,r,k=0,x,mi=-1,y;
    cin>>n>>m;
    ll a[n];
    vector< pair<ll,ll> > v;
    FOR(i,0,n)
        cin>>a[i];
    FOR(i,0,m)
    {
        cin>>t>>r;
        v.pb(mp(t,r));
        if(r>=ma)
        {
            ma=r;
            x=i;
            k=t;
        }
    }
    FOR(i,x+1,m)
    {
        if(v[i].ff!=k)
        {
            if(v[i].ss>=mi)
            {
                mi=v[i].ss;
                y=i;
            }
        }
    }
    if(k==1)
    {
        sort(a,a+ma);
        if(mi!=-1)
            sort(a,a+mi,greater<ll>());
    }
    else
    {
        sort(a,a+ma,greater<ll>());
        if(mi!=-1)
            sort(a,a+mi);
    }
    FOR(i,0,n)
        cout<<a[i]<<" ";
}


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

#define lli long long int
#define db double
#define ll long long
#define ld long double
#define li long int
#define pb push_back
#define mp make_pair
#define FOR(i,a,b) for(i=a;i<b;i++)
#define RFOR(i,a,b) for(i=a;i>b;i--)
#define ff first
#define ss second
#define fast ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);srand(time(NULL))
#define MOD 1000000007
#define nl cout<<endl
#define inf LONG_LONG_MAX
#define minf LONG_LONG_MIN
bool isprime(ll n)
{

            if (n <= 1)  return false;
            if (n <= 3)  return true;

            if (n%2 == 0 || n%3 == 0)
                return false;

            for (ll i=5; i*i<=n; i=i+6)
            {
                if (n%i == 0 || n%(i+2) == 0)
                   return false;
            }

            return true;
}
bool sec(const pair< pair<ll,ll> , ll > &a,const pair< pair<ll,ll> , ll > &b)
{
    if(a.ff.ff==b.ff.ff)
        return a.ss>b.ss;
    else
        return (a.ff.ff>b.ff.ff);
}
ll sum(ll n,ll m)
{
    m--;
    return (n*(n+1))/2 - (m*(m+1))/2;
}
int main()
{
    ll n,m,i,t,r;
    cin>>n>>m;
    ll a[n];
    FOR(i,0,n)
        cin>>a[i];
    vector< pair< pair<ll,ll>,ll> > v(m),q;
    FOR(i,0,m)
    {
        cin>>v[i].ff.ss>>v[i].ff.ff;
        v[i].ss=i;
    }
    sort(v.begin(),v.end(),sec);
    ll k=-1;
    FOR(i,0,m)
    {
        if(v[i].ss>k)
        {
            k=v[i].ss;
            q.pb(mp(mp(v[i].ff.ff,v[i].ff.ss),v[i].ss));
        }
    }
    vector<ll> b;
    FOR(i,0,v[0].ff.ff)
        b.pb(a[i]);
    sort(b.begin(),b.end());

    ll le=0,re=q[0].ff.ff,j;
    q.pb(mp(mp(0,0),0));
    FOR(i,1,q.size())
    {
        RFOR(j,q[i-1].ff.ff,q[i].ff.ff)
            a[j-1] = (q[i-1].ff.ss == 1) ? b[--re] : b[le++];
    }
    FOR(i,0,n)
        cout<<a[i]<<" ";
}


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

#define lli long long int
#define db double
#define ll long long
#define ld long double
#define li long int
#define pb push_back
#define mp make_pair
#define FOR(i,a,b) for(i=a;i<b;i++)
#define RFOR(i,a,b) for(i=a;i>b;i--)
#define ff first
#define ss second
#define fast ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);srand(time(NULL));
#define MOD 1000000007

bool isprime(ll n)
{

            if (n <= 1)  return false;
            if (n <= 3)  return true;

            if (n%2 == 0 || n%3 == 0)
                return false;

            for (ll i=5; i*i<=n; i=i+6)
            {
                if (n%i == 0 || n%(i+2) == 0)
                   return false;
            }

            return true;
}
int main()
{
    ll n,m,i,ma=-1,t,r,k=0,x,mi=-1,y;
    cin>>n>>m;
    ll a[n];
    vector< pair<ll,ll> > v;
    FOR(i,0,n)
        cin>>a[i];
    FOR(i,0,m)
    {
        cin>>t>>r;
        v.pb(mp(t,r));
        if(r>=ma)
        {
            ma=r;
            x=i;
            k=t;
        }
    }
    FOR(i,x+1,m)
    {
        if(v[i].ff!=x)
        {
            if(v[i].ss>=mi)
            {
                mi=v[i].ss;
                y=i;
            }
        }
    }
    if(k==1)
    {
        sort(a,a+ma);
        if(mi!=-1)
            sort(a,a+mi,greater<ll>());
    }
    else
    {
        sort(a,a+ma,greater<ll>());
        if(mi!=-1)
            sort(a,a+mi);
    }
    FOR(i,0,n)
        cout<<a[i]<<" ";
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define ALL(x) (x).begin(), (x).end()
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define gg(x) getInt(&x)
#define chu(x) cout<<"["<<#x<<" "<<(x)<<"]"<<endl
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
ll powmod(ll a, ll b, ll MOD) {ll ans = 1; while (b) {if (b % 2)ans = ans * a % MOD; a = a * a % MOD; b /= 2;} return ans;}
inline void getInt(int* p);
const int maxn = 1000010;
const int inf = 0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
int n,m;
int a[maxn];
stack<pii> b;
multiset<int> s;
std::vector<pii> v;
int main()
{
    //freopen("D:\\code\\text\\input.txt","r",stdin);
    //freopen("D:\\code\\text\\output.txt","w",stdout);
    gbtb;
    cin>>n>>m;
    repd(i,1,n)
    {
        cin>>a[i];
    }
    int op,r;
    int q=0;
    repd(i,1,m)
    {
        cin>>op>>r;
        while(!b.empty()&&b.top().se<=r)
        {
            b.pop();
        }
        b.push(mp(op,r));
        q=max(q,r);
    }
    repd(i,1,q)
    {
        s.insert(a[i]);
    }
    v.push_back(mp(0,0));
    while(!b.empty())
    {
        v.push_back(b.top());
        b.pop();
    }
    int last=q;
    for(int j=sz(v)-2;j>=0;--j)
    {
        op=v[j+1].fi;
//        cout<<v[j].se+1<<endl;
        for(int i=last;i>=v[j].se+1;i--)
        {
            if(op==1)
            {
                auto it=s.end();
                it--;
                a[i]=*it;
                s.erase(it);
            }else
            {
                a[i]=(*(s.begin()));
                s.erase(s.begin());
            }
        }
        last=v[j].se;
    }
    repd(i,1,n)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
    return 0;
}

inline void getInt(int* p) {
    char ch;
    do {
        ch = getchar();
    } while (ch == ' ' || ch == '\n');
    if (ch == '-') {
        *p = -(getchar() - '0');
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 - ch + '0';
        }
    }
    else {
        *p = ch - '0';
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 + ch - '0';
        }
    }
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define ALL(x) (x).begin(), (x).end()
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define gg(x) getInt(&x)
#define chu(x) cout<<"["<<#x<<" "<<(x)<<"]"<<endl
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
ll powmod(ll a, ll b, ll MOD) {ll ans = 1; while (b) {if (b % 2)ans = ans * a % MOD; a = a * a % MOD; b /= 2;} return ans;}
inline void getInt(int* p);
const int maxn = 1000010;
const int inf = 0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
int n,m;
int a[maxn];
stack<pii> b;
multiset<int> s;
std::vector<pii> v;
int main()
{
    //freopen("D:\\code\\text\\input.txt","r",stdin);
    //freopen("D:\\code\\text\\output.txt","w",stdout);
    gbtb;
    cin>>n>>m;
    repd(i,1,n)
    {
        cin>>a[i];
    }
    int op,r;
    int q=0;
    repd(i,1,m)
    {
        cin>>op>>r;
        while(!b.empty()&&b.top().se<=r)
        {
            b.pop();
        }
        b.push(mp(op,r));
        q=max(q,r);
    }
    repd(i,1,q)
    {
        s.insert(a[i]);
    }
    v.push_back(mp(0,0));
    while(!b.empty())
    {
        v.push_back(b.top());
        b.pop();
    }
    int last=q;
    for(int j=sz(v)-2;j>=0;--j)
    {
        op=v[j+1].fi;
        cout<<v[j].se+1<<endl;
        for(int i=last;i>=v[j].se+1;i--)
        {
            if(op==1)
            {
                auto it=s.end();
                it--;
                a[i]=*it;
                s.erase(it);
            }else
            {
                a[i]=(*(s.begin()));
                s.erase(s.begin());
            }
        }
        last=v[j].se;
    }
    repd(i,1,n)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
    return 0;
}

inline void getInt(int* p) {
    char ch;
    do {
        ch = getchar();
    } while (ch == ' ' || ch == '\n');
    if (ch == '-') {
        *p = -(getchar() - '0');
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 - ch + '0';
        }
    }
    else {
        *p = ch - '0';
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 + ch - '0';
        }
    }
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define ALL(x) (x).begin(), (x).end()
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '\0', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define gg(x) getInt(&x)
#define chu(x) cout<<"["<<#x<<" "<<(x)<<"]"<<endl
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b) {return b ? gcd(b, a % b) : a;}
ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
ll powmod(ll a, ll b, ll MOD) {ll ans = 1; while (b) {if (b % 2)ans = ans * a % MOD; a = a * a % MOD; b /= 2;} return ans;}
inline void getInt(int* p);
const int maxn = 1000010;
const int inf = 0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
int n,m;
int a[maxn];
stack<pii> b;
multiset<int> s;
int main()
{
    //freopen("D:\\code\\text\\input.txt","r",stdin);
    //freopen("D:\\code\\text\\output.txt","w",stdout);
    gbtb;
    cin>>n>>m;
    repd(i,1,n)
    {
        cin>>a[i];
    }
    int op,r;
    int q=0;
    repd(i,1,m)
    {
        cin>>op>>r;
        while(!b.empty()&&b.top().se<=r)
        {
            b.pop();
        }
        b.push(mp(op,r));
        q=max(q,r);
    }
    repd(i,1,q)
    {
        s.insert(a[i]);
    }
    int last=0;
    while(!b.empty())
    {
        for(int i=b.top().se;i>last;i--)
        {
            if(op==1)
            {
                auto it=s.end();
                it--;
                a[i]=*it;
                s.erase(it);
            }else
            {
                a[i]=(*(s.begin()));
                s.erase(s.begin());
            }
        }
        last=b.top().se;
        b.pop();
    }
    repd(i,1,n)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
    return 0;
}

inline void getInt(int* p) {
    char ch;
    do {
        ch = getchar();
    } while (ch == ' ' || ch == '\n');
    if (ch == '-') {
        *p = -(getchar() - '0');
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 - ch + '0';
        }
    }
    else {
        *p = ch - '0';
        while ((ch = getchar()) >= '0' && ch <= '9') {
            *p = *p * 10 + ch - '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;

#define endl '\n'
#define fast_io                       \
    ios_base::sync_with_stdio(false); \
    cin.tie(0);                       \
    cout.tie(0);

typedef long long int ll;
typedef long double ld;
#define mp make_pair
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define X first
#define Y second
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))

//use to find kth smallest element in int set, insert with ob.insert(int), find rank with *ob.find_by_order(k-1)
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

template<typename T>
void print(T ar[], int n)
{
    for (int i = 0; i < n; i++)
    {
        cout << ar[i] << " ";
    }
    cout << endl;
}

template<typename T>
void print(vector<T> &vec)
{
    for (int i = 0; i < vec.size(); i++)
    {
        cout << vec[i] << " ";
    }
    cout << endl;
}

void do_stuff()
{
    int n, m;
    cin >> n >> m;

    ll ar[n];
    pair<int, int> re[m];
    pair<int, int> q[m];
    forn(i, n)
    {
        cin >> ar[i];
    }
    forn(i,m)
    {
        cin >> re[i].first >> re[i].second;
        re[i].second--;
        q[i].first = re[i].second;
        q[i].second = i;
    }

    sort(q, q + m, greater<pair<int, int>>());

    ll ans[n];
    int ind = n - 1;
    int ind2 = q[0].second;
    while (ind != q[0].first)
    {
        ans[ind] = ar[ind];
        ind--;
    }
    multiset<ll> ordered;
    for (int i = 0; i <= ind; i++)
    {
        ordered.insert(ar[i]);
    }

    int currind = 0;

    while(!ordered.empty())
    {
        int ni = currind + 1;
        int nextind = ind - 1;
        while(ni< m&& q[ni].second < ind2)
        {
            ni++;
        }
        if(ni==m)
        {
            nextind = -1;
        }
        else
        {
            nextind = q[ni].first;
        }
        currind = ni;

        int order = re[ind2].first;
        if (order == 1)
        {
            while (ind != nextind)
            {
                ans[ind] = *(--ordered.end());
                ind--;
                ordered.erase(--ordered.end());
            }
            ind2 = (ni==m? -1 : q[ni].second);
        }
        else
        {
            while (ind != nextind)
            {
                ans[ind] = *(ordered.begin());
                ind--;
                ordered.erase(ordered.begin());
            }
            ind2 = (ni == m ? -1 : q[ni].second);
        }

    }

    forn(i, n)
    {
        cout << ans[i] << " ";
    }
    cout << endl;
}

int main()
{
    fast_io

    int t;
    //cin >> t;

    t=1;
    while (t--)
    {
        do_stuff();
    }
}


#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;

#define endl '\n'
#define fast_io                       \
    ios_base::sync_with_stdio(false); \
    cin.tie(0);                       \
    cout.tie(0);

typedef long long int ll;
typedef long double ld;
#define mp make_pair
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define X first
#define Y second
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))

//use to find kth smallest element in int set, insert with ob.insert(int), find rank with *ob.find_by_order(k-1)
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

template<typename T>
void print(T ar[], int n)
{
    for (int i = 0; i < n; i++)
    {
        cout << ar[i] << " ";
    }
    cout << endl;
}

template<typename T>
void print(vector<T> &vec)
{
    for (int i = 0; i < vec.size(); i++)
    {
        cout << vec[i] << " ";
    }
    cout << endl;
}

void do_stuff()
{
    int n, m;
    cin >> n >> m;

    ll ar[n];
    pair<int, int> re[m];
    pair<int, int> q[m];
    forn(i, n)
    {
        cin >> ar[i];
    }
    forn(i,m)
    {
        cin >> re[i].first >> re[i].second;
        re[i].second--;
        q[i].first = re[i].second;
        q[i].second = i;
    }

    sort(q, q + m, greater<pair<int, int>>());

    ll ans[n];
    int ind = n - 1;
    int ind2 = q[0].second;
    while (ind != q[0].first)
    {
        ans[ind] = ar[ind];
        ind--;
    }
    multiset<ll> ordered;
    for (int i = 0; i <= ind; i++)
    {
        ordered.insert(ar[i]);
    }

    while(!ordered.empty())
    {
        int nextind = ind-1;
        while(nextind>=0 && q[nextind].second < ind2)
        {
            nextind--;
        }
        int order = re[ind2].first;
        if (order == 1)
        {
            while (ind != nextind)
            {
                ans[ind] = *(--ordered.end());
                ind--;
                ordered.erase(--ordered.end());
            }
            ind2 = q[nextind].second;
        }
        else
        {
            while (ind != nextind)
            {
                ans[ind] = *(ordered.begin());
                ind--;
                ordered.erase(ordered.begin());
            }
            ind2 = q[nextind].second;
        }

    }

    forn(i, n)
    {
        cout << ans[i] << " ";
    }
    cout << endl;
}

int main()
{
    fast_io

    int t;
    //cin >> t;

    t=1;
    while (t--)
    {
        do_stuff();
    }
}


#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;

#define endl '\n'
#define fast_io                       \
    ios_base::sync_with_stdio(false); \
    cin.tie(0);                       \
    cout.tie(0);

typedef long long int ll;
typedef long double ld;
#define mp make_pair
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define X first
#define Y second
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))

//use to find kth smallest element in int set, insert with ob.insert(int), find rank with *ob.find_by_order(k-1)
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

template<typename T>
void print(T ar[], int n)
{
    for (int i = 0; i < n; i++)
    {
        cout << ar[i] << " ";
    }
    cout << endl;
}

template<typename T>
void print(vector<T> &vec)
{
    for (int i = 0; i < vec.size(); i++)
    {
        cout << vec[i] << " ";
    }
    cout << endl;
}

void do_stuff()
{
    int n, m;
    cin >> n >> m;

    ll ar[n];
    pair<int, int> re[m];
    pair<int, int> q[m];
    forn(i, n)
    {
        cin >> ar[i];
    }
    forn(i,m)
    {
        cin >> re[i].first >> re[i].second;
        re[i].second--;
        q[i].first = re[i].second;
        q[i].second = i;
    }

    sort(q, q + m, greater<pair<int, int>>());

    ll ans[n];
    int ind = n - 1;
    int ind2 = q[0].second;
    while (ind != q[0].first)
    {
        ans[ind] = ar[ind];
        ind--;
    }
    multiset<ll> ordered;
    for (int i = 0; i <= ind; i++)
    {
        ordered.insert(ar[i]);
    }

    int currind = 0;

    while(!ordered.empty())
    {
        int ni = currind + 1;
        int nextind = ind - 1;
        while(ni< m&& q[ni].second < ind2)
        {
            ni++;
        }
        if(ni==m)
        {
            nextind = -1;
        }
        else
        {
            nextind = q[ni].first;
        }
        currind = ni;

        int order = re[ind2].first;
        if (order == 1)
        {
            while (ind != nextind)
            {
                ans[ind] = *(--ordered.end());
                ind--;
                ordered.erase(--ordered.end());
            }
            ind2 = q[nextind].second;
        }
        else
        {
            while (ind != nextind)
            {
                ans[ind] = *(ordered.begin());
                ind--;
                ordered.erase(ordered.begin());
            }
            ind2 = q[nextind].second;
        }

    }

    forn(i, n)
    {
        cout << ans[i] << " ";
    }
    cout << endl;
}

int main()
{
    fast_io

    int t;
    //cin >> t;

    t=1;
    while (t--)
    {
        do_stuff();
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
    Scanner in;
    PrintWriter out;

    void setIn(String fI) {

        try {
            in = new Scanner(new FileInputStream(new File(fI)));
        } catch (FileNotFoundException e) {
            throw new Error(e);
        }
    }

    void setIn() {
        in = new Scanner(System.in);
    }

    void setOut(String fO) {
        try {
            out = new PrintWriter(new FileWriter(fO));
        } catch (IOException e) {
            throw new Error(e);
        }
    }

    void setOut() {
        out = new PrintWriter(System.out);
    }

    class Scanner {
        StringTokenizer st;
        BufferedReader in;
        String del;

        Scanner(InputStream is) {
            in = new BufferedReader(new InputStreamReader(is));
            st = null;
            del = " \t\n\r\f";
        }

        void setDelimiters(String del) {
            this.del = del;
        }

        String next() {
            if (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine(), del);
            }
            if (!st.hasMoreElements()) {
                return next();
            }
            return st.nextToken();
        }

        String nextLine() {
            try {
                st = null;
                return in.readLine();
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        char nextChar() {
            try {
                char ch = (char) in.read();
                while (del.indexOf(ch) >= 0)
                    ch = (char) in.read();
                return ch;
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        boolean hasNext() {
            try {
                return in.ready() || (st != null && st.hasMoreTokens());
            } catch (IOException e) {
                throw new Error(e);
            }
        }

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

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

        BigInteger nextBigInteger() {
            return new BigInteger(next());
        }

        BigDecimal nextBigDecimal() {
            return new BigDecimal(next());
        }

        int[] nextIntArray(int len) {
            int[] a = new int[len];
            for (int i = 0; i < len; i++) {
                a[i] = nextInt();
            }
            return a;
        }

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

    public static void main(String[] args) {
        new Main().run();
    }

    void run() {
        setIn();
        setOut();
        try {
            solve();
        } finally {
            out.close();
        }
    }

    void out(HashMap<Integer, ArrayList<Integer>> map) {
        ArrayList<Integer> a = new ArrayList<Integer>();
        for (int mod : map.keySet()) {
            for (int dig : map.get(mod)) {
                a.add(dig);
            }
        }
        Collections.sort(a);
        for (int pos = a.size() - 1; pos >= 0; pos--) {
            out.print(a.get(pos));
        }
    }

    void solve() {
        int n = in.nextInt();
        HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
        for (int i = 0; i <= 2; i++) {
            map.put(i, new ArrayList<Integer>());
        }
        for (int i = 0; i < n; i++) {
            int buf = in.nextInt();
            map.get(buf % 3).add(buf);
        }
        for (int i = 0; i <= 2; i++) {
            Collections.sort(map.get(i));
        }
        int sum = 0;
        for (int i = 0; i <= 2; i++) {
            for (int dig : map.get(i)) {
                sum += dig;
            }
        }
        if (sum == 0) {
            out.println(0);
            return;
        }
        if (map.get(0).get(0) != 0) {
            out.println(-1);
            return;
        }
        if (sum % 3 == 0) {
            out(map);
            return;
        }
        if (sum % 3 == 1) {
            if (map.get(1).size() >= 1) {
                map.get(1).remove(0);
                out(map);
            } else if (map.get(2).size() >= 2) {
                map.get(2).remove(0);
                map.get(2).remove(0);
                out(map);
            } else {
                out.println(-1);
            }
            return;
        }
        if (map.get(2).size() >= 1) {
            map.get(2).remove(0);
            out(map);
        } else if (map.get(1).size() >= 2) {
            map.get(1).remove(0);
            map.get(1).remove(0);
            out(map);
        } else {
            out.println(-1);
        }
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
    Scanner in;
    PrintWriter out;

    void setIn(String fI) {

        try {
            in = new Scanner(new FileInputStream(new File(fI)));
        } catch (FileNotFoundException e) {
            throw new Error(e);
        }
    }

    void setIn() {
        in = new Scanner(System.in);
    }

    void setOut(String fO) {
        try {
            out = new PrintWriter(new FileWriter(fO));
        } catch (IOException e) {
            throw new Error(e);
        }
    }

    void setOut() {
        out = new PrintWriter(System.out);
    }

    class Scanner {
        StringTokenizer st;
        BufferedReader in;
        String del;

        Scanner(InputStream is) {
            in = new BufferedReader(new InputStreamReader(is));
            st = null;
            del = " \t\n\r\f";
        }

        void setDelimiters(String del) {
            this.del = del;
        }

        String next() {
            if (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine(), del);
            }
            if (!st.hasMoreElements()) {
                return next();
            }
            return st.nextToken();
        }

        String nextLine() {
            try {
                st = null;
                return in.readLine();
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        char nextChar() {
            try {
                char ch = (char) in.read();
                while (del.indexOf(ch) >= 0)
                    ch = (char) in.read();
                return ch;
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        boolean hasNext() {
            try {
                return in.ready() || (st != null && st.hasMoreTokens());
            } catch (IOException e) {
                throw new Error(e);
            }
        }

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

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

        BigInteger nextBigInteger() {
            return new BigInteger(next());
        }

        BigDecimal nextBigDecimal() {
            return new BigDecimal(next());
        }

        int[] nextIntArray(int len) {
            int[] a = new int[len];
            for (int i = 0; i < len; i++) {
                a[i] = nextInt();
            }
            return a;
        }

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

    public static void main(String[] args) {
        new Main().run();
    }

    void run() {
        setIn();
        setOut();
        try {
            solve();
        } finally {
            out.close();
        }
    }

    void out(HashMap<Integer, ArrayList<Integer>> map) {
        ArrayList<Integer> a = new ArrayList<Integer>();
        for (int mod : map.keySet()) {
            for (int dig : map.get(mod)) {
                a.add(dig);
            }
        }
        Collections.sort(a);
        for (int pos = a.size() - 1; pos >= 0; pos--) {
            out.print(a.get(pos));
        }
    }

    void solve() {
        int n = in.nextInt();
        HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
        for (int i = 0; i <= 2; i++) {
            map.put(i, new ArrayList<Integer>());
        }
        for (int i = 0; i < n; i++) {
            int buf = in.nextInt();
            map.get(buf % 3).add(buf);
        }
        for (int i = 0; i <= 2; i++) {
            Collections.sort(map.get(i));
        }
        int sum = 0;
        for (int i = 0; i <= 2; i++) {
            for (int dig : map.get(i)) {
                sum += dig;
            }
        }
        if (sum == 0) {
            out.println(0);
            return;
        }
        if (map.get(0).size() == 0 || map.get(0).get(0) != 0) {
            out.println(-1);
            return;
        }
        if (sum % 3 == 0) {
            out(map);
            return;
        }
        if (sum % 3 == 1) {
            if (map.get(1).size() >= 1) {
                map.get(1).remove(0);
                out(map);
            } else if (map.get(2).size() >= 2) {
                map.get(2).remove(0);
                map.get(2).remove(0);
                out(map);
            } else {
                out.println(-1);
            }
            return;
        }
        if (map.get(2).size() >= 1) {
            map.get(2).remove(0);
            out(map);
        } else if (map.get(1).size() >= 2) {
            map.get(1).remove(0);
            map.get(1).remove(0);
            out(map);
        } else {
            out.println(-1);
        }
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
    Scanner in;
    PrintWriter out;

    void setIn(String fI) {

        try {
            in = new Scanner(new FileInputStream(new File(fI)));
        } catch (FileNotFoundException e) {
            throw new Error(e);
        }
    }

    void setIn() {
        in = new Scanner(System.in);
    }

    void setOut(String fO) {
        try {
            out = new PrintWriter(new FileWriter(fO));
        } catch (IOException e) {
            throw new Error(e);
        }
    }

    void setOut() {
        out = new PrintWriter(System.out);
    }

    class Scanner {
        StringTokenizer st;
        BufferedReader in;
        String del;

        Scanner(InputStream is) {
            in = new BufferedReader(new InputStreamReader(is));
            st = null;
            del = " \t\n\r\f";
        }

        void setDelimiters(String del) {
            this.del = del;
        }

        String next() {
            if (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine(), del);
            }
            if (!st.hasMoreElements()) {
                return next();
            }
            return st.nextToken();
        }

        String nextLine() {
            try {
                st = null;
                return in.readLine();
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        char nextChar() {
            try {
                char ch = (char) in.read();
                while (del.indexOf(ch) >= 0)
                    ch = (char) in.read();
                return ch;
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        boolean hasNext() {
            try {
                return in.ready() || (st != null && st.hasMoreTokens());
            } catch (IOException e) {
                throw new Error(e);
            }
        }

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

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

        BigInteger nextBigInteger() {
            return new BigInteger(next());
        }

        BigDecimal nextBigDecimal() {
            return new BigDecimal(next());
        }

        int[] nextIntArray(int len) {
            int[] a = new int[len];
            for (int i = 0; i < len; i++) {
                a[i] = nextInt();
            }
            return a;
        }

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

    public static void main(String[] args) {
        new Main().run();
    }

    void run() {
        setIn();
        setOut();
        try {
            solve();
        } finally {
            out.close();
        }
    }

    void out(HashMap<Integer, ArrayList<Integer>> map) {
        ArrayList<Integer> a = new ArrayList<Integer>();
        for (int mod : map.keySet()) {
            for (int dig : map.get(mod)) {
                a.add(dig);
            }
        }
        Collections.sort(a);
        if (a.get(0) == a.get(a.size() - 1) && a.get(0) == 0) {
            out.println(0);
            return;
        }
        for (int pos = a.size() - 1; pos >= 0; pos--) {
            out.print(a.get(pos));
        }
    }

    void solve() {
        int n = in.nextInt();
        HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
        for (int i = 0; i <= 2; i++) {
            map.put(i, new ArrayList<Integer>());
        }
        for (int i = 0; i < n; i++) {
            int buf = in.nextInt();
            map.get(buf % 3).add(buf);
        }
        for (int i = 0; i <= 2; i++) {
            Collections.sort(map.get(i));
        }
        int sum = 0;
        for (int i = 0; i <= 2; i++) {
            for (int dig : map.get(i)) {
                sum += dig;
            }
        }
        if (sum == 0) {
            out.println(0);
            return;
        }
        if (map.get(0).size() == 0 || map.get(0).get(0) != 0) {
            out.println(-1);
            return;
        }
        if (sum % 3 == 0) {
            out(map);
            return;
        }
        if (sum % 3 == 1) {
            if (map.get(1).size() >= 1) {
                map.get(1).remove(0);
                out(map);
            } else if (map.get(2).size() >= 2) {
                map.get(2).remove(0);
                map.get(2).remove(0);
                out(map);
            } else {
                out.println(-1);
            }
            return;
        }
        if (map.get(2).size() >= 1) {
            map.get(2).remove(0);
            out(map);
        } else if (map.get(1).size() >= 2) {
            map.get(1).remove(0);
            map.get(1).remove(0);
            out(map);
        } else {
            out.println(-1);
        }
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;

public class Main {
    Scanner in;
    PrintWriter out;

    void setIn(String fI) {

        try {
            in = new Scanner(new FileInputStream(new File(fI)));
        } catch (FileNotFoundException e) {
            throw new Error(e);
        }
    }

    void setIn() {
        in = new Scanner(System.in);
    }

    void setOut(String fO) {
        try {
            out = new PrintWriter(new FileWriter(fO));
        } catch (IOException e) {
            throw new Error(e);
        }
    }

    void setOut() {
        out = new PrintWriter(System.out);
    }

    class Scanner {
        StringTokenizer st;
        BufferedReader in;
        String del;

        Scanner(InputStream is) {
            in = new BufferedReader(new InputStreamReader(is));
            st = null;
            del = " \t\n\r\f";
        }

        void setDelimiters(String del) {
            this.del = del;
        }

        String next() {
            if (st == null || !st.hasMoreTokens()) {
                st = new StringTokenizer(nextLine(), del);
            }
            if (!st.hasMoreElements()) {
                return next();
            }
            return st.nextToken();
        }

        String nextLine() {
            try {
                st = null;
                return in.readLine();
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        char nextChar() {
            try {
                char ch = (char) in.read();
                while (del.indexOf(ch) >= 0)
                    ch = (char) in.read();
                return ch;
            } catch (IOException e) {
                throw new Error(e);
            }
        }

        boolean hasNext() {
            try {
                return in.ready() || (st != null && st.hasMoreTokens());
            } catch (IOException e) {
                throw new Error(e);
            }
        }

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

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

        BigInteger nextBigInteger() {
            return new BigInteger(next());
        }

        BigDecimal nextBigDecimal() {
            return new BigDecimal(next());
        }

        int[] nextIntArray(int len) {
            int[] a = new int[len];
            for (int i = 0; i < len; i++) {
                a[i] = nextInt();
            }
            return a;
        }

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

    public static void main(String[] args) {
        new Main().run();
    }

    void run() {
        setIn();
        setOut();
        try {
            solve();
        } finally {
            out.close();
        }
    }

    void out(HashMap<Integer, ArrayList<Integer>> map) {
        ArrayList<Integer> a = new ArrayList<Integer>();
        for (int mod : map.keySet()) {
            for (int dig : map.get(mod)) {
                a.add(dig);
            }
        }
        Collections.sort(a);
        for (int pos = a.size() - 1; pos >= 0; pos--) {
            out.print(a.get(pos));
        }
    }

    void solve() {
        int n = in.nextInt();
        HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
        for (int i = 0; i <= 2; i++) {
            map.put(i, new ArrayList<Integer>());
        }
        for (int i = 0; i < n; i++) {
            int buf = in.nextInt();
            map.get(buf % 3).add(buf);
        }
        for (int i = 0; i <= 2; i++) {
            Collections.sort(map.get(i));
        }
        int sum = 0;
        for (int i = 0; i <= 2; i++) {
            for (int dig : map.get(i)) {
                sum += dig;
            }
        }
        if (sum == 0) {
            out.println(0);
            return;
        }
        if (map.size() == 0 || map.get(0).get(0) != 0) {
            out.println(-1);
            return;
        }
        if (sum % 3 == 0) {
            out(map);
            return;
        }
        if (sum % 3 == 1) {
            if (map.get(1).size() >= 1) {
                map.get(1).remove(0);
                out(map);
            } else if (map.get(2).size() >= 2) {
                map.get(2).remove(0);
                map.get(2).remove(0);
                out(map);
            } else {
                out.println(-1);
            }
            return;
        }
        if (map.get(2).size() >= 1) {
            map.get(2).remove(0);
            out(map);
        } else if (map.get(1).size() >= 2) {
            map.get(1).remove(0);
            map.get(1).remove(0);
            out(map);
        } else {
            out.println(-1);
        }
    }
}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Round131B {
	private static final int LOCAL_ENV = 0;

	static int n;
	static int[] digits;
	static int total;
	static int[] walk;
	static int[] best;
	static int bestRemoved;

	public static boolean better(int[] w1, int[] w2) {
		for (int i = 9; i >= 1; i--) {
			if (w1[i] < w2[i]) {
				return true;
			}
			if (w1[i] > w2[i]) {
				return false;
			}
		}
		return false;
	}

	public static void check(int v, int subTotal, int removed) {
		if (v == 10) {
			if ((total - subTotal) % 3 == 0) {
				if (best == null || (bestRemoved > removed)) {
					best = walk.clone();
					bestRemoved = removed;
				} else if (bestRemoved == removed && better(walk, best)) {
					best = walk.clone();
				}
			}
			return;
		}

		for (int i = 0; i < 3 && i <= digits[v]; i++) {
			walk[v] = i;
			check(v + 1, subTotal + v * i, removed + ((i > 0) ? 1 : 0));
		}
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		try {
			if (LOCAL_ENV == 1) {
				in = new Scanner(new File("input.txt"));
			}
		} catch (FileNotFoundException e) {
			in = new Scanner(System.in);
		}

		digits = new int[10];
		n = in.nextInt();
		total = 0;
		boolean noneZero = false;

		for (int i = 0; i < n; i++) {
			int x = in.nextInt();
			digits[x]++;
			total += x;
			if (x > 0) {
				noneZero = true;
			}
		}

		if (digits[0] == 0) {
			System.out.println("-1");
			return;
		}

		if (!noneZero) {
			System.out.println("0");
			return;
		}

		best = null;
		bestRemoved = 1000;
		walk = new int[10];

		check(1, 0, 0);

		if (best == null) {
			System.out.println("0");
			return;
		}

		StringBuilder sb = new StringBuilder();

		for (int i = 9; i >= 1; i--) {
			for (int j = 0; j < digits[i] - best[i]; j++) {
				sb.append(i);
			}
		}

		for (int j = 0; j < digits[0]; j++) {
			sb.append(0);
		}

		String ans = sb.toString();
		if (ans.charAt(0) == '0') {
			ans = "0";
		}

		System.out.println(ans);
	}
}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Round131B {
	private static final int LOCAL_ENV = 0;

	static int n;
	static int[] digits;
	static int total;
	static int[] best;
	static int bestRemoved;

	public static boolean better(int[] w1, int[] w2) {
		for (int i = 9; i >= 1; i--) {
			if (w1[i] < w2[i]) {
				return true;
			}
			if (w1[i] > w2[i]) {
				return false;
			}
		}
		return false;
	}

	public static void check(int v, int subTotal, int removed, int[] walk) {
		if (v == 10) {
			if ((total - subTotal) % 3 == 0) {
				if (best == null || (bestRemoved > removed)) {
					best = walk.clone();
					bestRemoved = removed;
				} else if (bestRemoved == removed && better(walk, best)) {
					best = walk.clone();
				}
			}
			return;
		}

		for (int i = 0; i < 3 && i <= digits[v]; i++) {
			walk[v] = i;
			check(v + 1, subTotal + v * i, removed + ((i > 0) ? 1 : 0), walk);
		}
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		try {
			if (LOCAL_ENV == 1) {
				in = new Scanner(new File("input.txt"));
			}
		} catch (FileNotFoundException e) {
			in = new Scanner(System.in);
		}

		digits = new int[10];
		n = in.nextInt();
		total = 0;
		boolean noneZero = false;

		for (int i = 0; i < n; i++) {
			int x = in.nextInt();
			digits[x]++;
			total += x;
			if (x > 0) {
				noneZero = true;
			}
		}

		if (digits[0] == 0) {
			System.out.println("-1");
			return;
		}

		if (!noneZero) {
			System.out.println("0");
			return;
		}

		best = null;
		bestRemoved = 1000;
		int[] walk = new int[10];

		check(1, 0, 0, walk);

		if (best == null) {
			System.out.println("0");
			return;
		}

		for (int i = 9; i >= 1; i--) {
			for (int j = 0; j < digits[i] - best[i]; j++) {
				System.out.print(i);
			}
		}

		for (int j = 0; j < digits[0]; j++) {
			System.out.print("0");
		}

		System.out.println();
	}
}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Round131B {
	private static final int LOCAL_ENV = 0;

	static int n;
	static int[] digits;
	static int total;
	static int[] walk;
	static int[] best;
	static int bestRemoved;

	public static boolean better(int[] w1, int[] w2) {
		for (int i = 9; i >= 1; i--) {
			if (w1[i] < w2[i]) {
				return true;
			}
			if (w1[i] > w2[i]) {
				return false;
			}
		}
		return false;
	}

	public static void check(int v, int subTotal, int removed) {
		if (v == 10) {
			if ((total % 3) == (subTotal % 3)) {
				if (best == null || (bestRemoved > removed)) {
					best = walk.clone();
					bestRemoved = removed;
				} else if (bestRemoved == removed && better(walk, best)) {
					best = walk.clone();
				}
			}
			return;
		}

		for (int i = 0; i < 3 && i <= digits[v]; i++) {
			if (i > 0 && v % 3 == 0) {
				continue;
			}
			walk[v] = i;
			check(v + 1, subTotal + (v % 3) * i, removed + ((i > 0) ? 1 : 0));
		}
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		try {
			if (LOCAL_ENV == 1) {
				in = new Scanner(new File("input.txt"));
			}
		} catch (FileNotFoundException e) {
			in = new Scanner(System.in);
		}

		digits = new int[10];
		n = in.nextInt();
		total = 0;

		for (int i = 0; i < n; i++) {
			int x = in.nextInt();
			digits[x]++;
			total += x;
		}

		if (digits[0] == 0) {
			System.out.println("-1");
			return;
		}

		best = null;
		bestRemoved = 1000;
		walk = new int[10];

		check(1, 0, 0);

		if (best == null) {
			System.out.println("0");
			return;
		}

		StringBuilder sb = new StringBuilder();

		for (int i = 9; i >= 1; i--) {
			for (int j = 0; j < digits[i] - best[i]; j++) {
				sb.append(i);
			}
		}

		for (int j = 0; j < digits[0]; j++) {
			sb.append(0);
		}

		String ans = sb.toString();
		if (ans.charAt(0) == '0') {
			ans = "0";
		}

		System.out.println(ans);
	}
}


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Round131B {
	private static final int LOCAL_ENV = 0;

	static int n;
	static int[] digits;
	static int total;
	static int[] walk;
	static int[] best;
	static int bestRemoved;

	public static boolean better(int[] w1, int[] w2) {
		for (int i = 9; i >= 1; i--) {
			if (w1[i] < w2[i]) {
				return true;
			}

			if (w1[i] > w2[i]) {
				return false;
			}
		}
		return false;
	}

	public static void check(int v, int subTotal, int removed) {
		if (v == 10) {
			if ((total % 3) == (subTotal % 3)) {
				if (best == null || (bestRemoved > removed)) {
					best = walk.clone();
					bestRemoved = removed;
				} else if (bestRemoved == removed && better(walk, best)) {
					best = walk.clone();
				}
			}
			return;
		}

		for (int i = 0; i < 3 && i <= digits[v]; i++) {
			if (i > 0 && v % 3 == 0) {
				continue;
			}
			walk[v] = i;
			check(v + 1, subTotal + (v % 3) * i, removed + i);
		}
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		try {
			if (LOCAL_ENV == 1) {
				in = new Scanner(new File("input.txt"));
			}
		} catch (FileNotFoundException e) {
			in = new Scanner(System.in);
		}

		digits = new int[10];
		n = in.nextInt();
		total = 0;

		for (int i = 0; i < n; i++) {
			int x = in.nextInt();
			digits[x]++;
			total += x;
		}

		if (digits[0] == 0) {
			System.out.println("-1");
			return;
		}

		best = null;
		bestRemoved = 1000;
		walk = new int[10];

		check(1, 0, 0);

		if (best == null) {
			System.out.println("0");
			return;
		}

		StringBuilder sb = new StringBuilder();

		for (int i = 9; i >= 1; i--) {
			for (int j = 0; j < digits[i] - best[i]; j++) {
				sb.append("" + i);
			}
		}

		for (int j = 0; j < digits[0]; j++) {
			sb.append("0");
		}

		String ans = sb.toString();
		if (ans.charAt(0) == '0') {
			ans = "0";
		}

		System.out.println(ans);
	}
}


import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;

/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
 */

public class Main {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;

	static int[][] dp;

	static LinkedList<Integer>[] edges;

	static int[] dist;

	public static void main(String[] args) throws IOException	{
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = readInt();
		int[] list = new int[10];
		while(n-- > 0)	{
			list[readInt()]++;
		}
		if(list[0] == 0)	{
			pw.println(-1);
		}
		else	{
			int numOne = list[1] + list[4] + list[7];
			int numTwo = list[2] + list[5] + list[8];
			int mod = 0;
			for(int i = 0; i < list.length; i++)	{
				mod += i * list[i];
				mod %= 3;
			}
			if(mod == 0)	{
				gen(list);
			}
			else if(mod == 1)	{
				if(numOne < 1 && numTwo < 2)	{
					pw.println(-1);
				}
				else if(numOne >= 1)	{
					numOne = 1;
					for(int i = 1; i < 8; i += 3)	{
						if(numOne == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numOne--;
							i -= 3;
						}
					}
					gen(list);
				}
				else	{
					numTwo = 2;
					for(int i = 2; i <= 8; i += 3)	{
						if(numTwo == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numTwo--;
							i -= 3;
						}
					}
					gen(list);
				}
			}
			else	{
				if(numOne < 2 && numTwo < 1)	{
					pw.println(-1);
				}
				else if(numTwo >= 1)	{
					numTwo = 1;
					for(int i = 2; i <= 8; i += 3)	{
						if(numTwo == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numTwo--;
							i -= 3;
						}
					}
					gen(list);
				}
				else	{
					numOne = 2;
					for(int i = 1; i <= 8; i += 3)	{
						if(numOne == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numOne--;
							i -= 3;
						}
					}
					gen(list);
				}
			}
		}
		pw.close();
	}

	public static void gen(int[] list)	{
		StringBuilder sb = new StringBuilder();
		for(int i = 9; i >= 0; i--)	{
			while(list[i]-- > 0)	{
				sb.append(i);
			}
		}
		pw.println(new BigInteger(sb.toString()));
	}

	/* NOTEBOOK CODE */

	public static void loadArray(int[][] grid) throws IOException {
		for(int[] a: grid)
			loadArray(a);
	}

	public static void loadArray(int[] in) throws IOException {
		for(int i = 0; i < in.length; i++)
			in[i] = readInt();
	}

	public static void loadArray(long[] in) throws IOException {
		for(int i = 0; i < in.length; i++)
			in[i] = readLong();
	}

	private static long readLong() throws IOException	{
		return Long.parseLong(nextToken());
	}

	private static double readDouble() throws IOException	{
		return Double.parseDouble(nextToken());
	}

	private static int readInt() throws IOException	{
		return Integer.parseInt(nextToken());
	}

	private static String nextToken() throws IOException	{
		while(st == null || !st.hasMoreTokens())	{
			if(!br.ready())	{
				pw.close();
				System.exit(0);
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}


import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;

/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
 */

public class Main {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;

	static int[][] dp;

	static LinkedList<Integer>[] edges;

	static int[] dist;

	public static void main(String[] args) throws IOException	{
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = readInt();
		int[] list = new int[10];
		while(n-- > 0)	{
			list[readInt()]++;
		}
		if(list[0] == 0)	{
			pw.println(-1);
		}
		else	{
			int numOne = list[1] + list[4] + list[7];
			int numTwo = list[2] + list[5] + list[8];
			int mod = 0;
			for(int i = 0; i < list.length; i++)	{
				mod += i * list[i];
				mod %= 3;
			}
			if(mod == 0)	{
				gen(list);
			}
			else if(mod == 1)	{
				if(numOne < 1 && numTwo < 2)	{
					pw.println(-1);
				}
				else if(numOne >= 1)	{
					numOne = 1;
					for(int i = 1; i < 8; i += 3)	{
						if(numOne == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numOne--;
							i -= 3;
						}
					}
					gen(list);
				}
				else	{
					numTwo = 2;
					for(int i = 2; i <= 8; i += 3)	{
						if(numTwo == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numTwo--;
							i -= 3;
						}
					}
					gen(list);
				}
			}
			else	{
				if(numOne < 2 && numTwo < 1)	{
					pw.println(-1);
				}
				else if(numTwo >= 1)	{
					numTwo = 1;
					for(int i = 2; i <= 8; i += 3)	{
						if(numTwo == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numTwo--;
							i -= 3;
						}
					}
					gen(list);
				}
				else	{
					numOne = 2;
					for(int i = 1; i <= 8; i += 3)	{
						if(numOne == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numOne--;
							i -= 3;
						}
					}
					gen(list);
				}
			}
		}
		pw.close();
	}

	public static void gen(int[] list)	{
		StringBuilder sb = new StringBuilder();
		for(int i = 9; i >= 0; i--)	{
			while(list[i]-- > 0)	{
				sb.append(i);
			}
		}
		pw.println(sb.toString());
	}

	/* NOTEBOOK CODE */

	public static void loadArray(int[][] grid) throws IOException {
		for(int[] a: grid)
			loadArray(a);
	}

	public static void loadArray(int[] in) throws IOException {
		for(int i = 0; i < in.length; i++)
			in[i] = readInt();
	}

	public static void loadArray(long[] in) throws IOException {
		for(int i = 0; i < in.length; i++)
			in[i] = readLong();
	}

	private static long readLong() throws IOException	{
		return Long.parseLong(nextToken());
	}

	private static double readDouble() throws IOException	{
		return Double.parseDouble(nextToken());
	}

	private static int readInt() throws IOException	{
		return Integer.parseInt(nextToken());
	}

	private static String nextToken() throws IOException	{
		while(st == null || !st.hasMoreTokens())	{
			if(!br.ready())	{
				pw.close();
				System.exit(0);
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}


import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;

/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
 */

public class Main {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;

	static int[][] dp;

	static LinkedList<Integer>[] edges;

	static int[] dist;

	public static void main(String[] args) throws IOException	{
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = readInt();
		int[] list = new int[10];
		while(n-- > 0)	{
			list[readInt()]++;
		}
		if(list[0] == 0)	{
			pw.println(-1);
		}
		else	{
			int numOne = list[1] + list[4] + list[7];
			int numTwo = list[2] + list[5] + list[8];
			int mod = 0;
			for(int i = 0; i < list.length; i++)	{
				mod += i * list[i];
				mod %= 3;
			}
			if(mod == 0)	{
				gen(list);
			}
			else if(mod == 1)	{
				if(numOne < 1 && numTwo < 2)	{
					pw.println(-1);
				}
				else if(numOne >= 1)	{
					numOne = 1;
					for(int i = 1; i < 8; i += 3)	{
						if(numOne == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numOne--;
							i -= 3;
						}
					}
					gen(list);
				}
				else	{
					numTwo = 2;
					for(int i = 2; i <= 8; i += 3)	{
						if(numTwo == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numTwo--;
							i -= 3;
						}
					}
					gen(list);
				}
			}
			else	{
				if(numOne < 2 && numTwo < 1)	{
					pw.println(-1);
				}
				else if(numTwo >= 1)	{
					numTwo = 1;
					for(int i = 2; i <= 8; i += 3)	{
						if(numTwo == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numTwo--;
							i -= 3;
						}
					}
					gen(list);
				}
				else	{
					numOne = 2;
					for(int i = 1; i <= 8; i += 3)	{
						if(numOne == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numOne--;
							i -= 3;
						}
					}
					gen(list);
				}
			}
		}
		pw.close();
	}

	public static void gen(int[] list)	{
		StringBuilder sb = new StringBuilder();
		for(int i = 9; i >= 0; i--)	{
			while(list[i]-- > 0)	{
				if(i == 0 && sb.length() == 0)	{
					list[i] = 0;
				}
				sb.append(i);
			}
		}
		pw.println(sb.toString());
	}

	/* NOTEBOOK CODE */

	public static void loadArray(int[][] grid) throws IOException {
		for(int[] a: grid)
			loadArray(a);
	}

	public static void loadArray(int[] in) throws IOException {
		for(int i = 0; i < in.length; i++)
			in[i] = readInt();
	}

	public static void loadArray(long[] in) throws IOException {
		for(int i = 0; i < in.length; i++)
			in[i] = readLong();
	}

	private static long readLong() throws IOException	{
		return Long.parseLong(nextToken());
	}

	private static double readDouble() throws IOException	{
		return Double.parseDouble(nextToken());
	}

	private static int readInt() throws IOException	{
		return Integer.parseInt(nextToken());
	}

	private static String nextToken() throws IOException	{
		while(st == null || !st.hasMoreTokens())	{
			if(!br.ready())	{
				pw.close();
				System.exit(0);
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}


import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;

/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
 */

public class Main {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;

	static int[][] dp;

	static LinkedList<Integer>[] edges;

	static int[] dist;

	public static void main(String[] args) throws IOException	{
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = readInt();
		int[] list = new int[10];
		while(n-- > 0)	{
			list[readInt()]++;
		}
		if(list[0] == 0)	{
			pw.println(-1);
		}
		else	{
			int numOne = list[1] + list[4] + list[7];
			int numTwo = list[2] + list[5] + list[8];
			int mod = 0;
			for(int i = 0; i < list.length; i++)	{
				mod += i * list[i];
				mod %= 3;
			}
			if(mod == 0)	{
				gen(list);
			}
			else if(mod == 1)	{
				if(numOne < 1 || numTwo < 2)	{
					pw.println(-1);
				}
				else if(numOne >= 1)	{
					numOne = 1;
					for(int i = 1; i < 8; i += 3)	{
						if(numOne == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numOne--;
							i -= 3;
						}
					}
					gen(list);
				}
				else	{
					numTwo = 2;
					for(int i = 2; i <= 8; i += 3)	{
						if(numTwo == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numTwo--;
							i -= 3;
						}
					}
					gen(list);
				}
			}
			else	{
				if(numOne < 2 || numTwo < 1)	{
					pw.println(-1);
				}
				else if(numTwo >= 1)	{
					numTwo = 1;
					for(int i = 2; i <= 8; i += 3)	{
						if(numTwo == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numTwo--;
							i -= 3;
						}
					}
					gen(list);
				}
				else	{
					numOne = 2;
					for(int i = 1; i <= 8; i += 3)	{
						if(numOne == 0)	{
							break;
						}
						if(list[i] > 0)	{
							list[i]--;
							numOne--;
							i -= 3;
						}
					}
					gen(list);
				}
			}
		}
		pw.close();
	}

	public static void gen(int[] list)	{
		StringBuilder sb = new StringBuilder();
		for(int i = 9; i >= 0; i--)	{
			while(list[i]-- > 0)	{
				sb.append(i);
			}
		}
		pw.println(sb.toString());
	}

	/* NOTEBOOK CODE */

	public static void loadArray(int[][] grid) throws IOException {
		for(int[] a: grid)
			loadArray(a);
	}

	public static void loadArray(int[] in) throws IOException {
		for(int i = 0; i < in.length; i++)
			in[i] = readInt();
	}

	public static void loadArray(long[] in) throws IOException {
		for(int i = 0; i < in.length; i++)
			in[i] = readLong();
	}

	private static long readLong() throws IOException	{
		return Long.parseLong(nextToken());
	}

	private static double readDouble() throws IOException	{
		return Double.parseDouble(nextToken());
	}

	private static int readInt() throws IOException	{
		return Integer.parseInt(nextToken());
	}

	private static String nextToken() throws IOException	{
		while(st == null || !st.hasMoreTokens())	{
			if(!br.ready())	{
				pw.close();
				System.exit(0);
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}


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

public class Main {

	BufferedReader in;
	StringTokenizer str = null;

	private String next() throws Exception {
		if (str == null || !str.hasMoreElements())
			str = new StringTokenizer(in.readLine());
		return str.nextToken();
	}

	private int nextInt() throws Exception {
		return Integer.parseInt(next());
	}

	private long nextLong() throws Exception {
		return Long.parseLong(next());
	}

	private double nextDouble() throws Exception {
		return Double.parseDouble(next());
	}

	public void run() throws Exception {
		in = new BufferedReader(new InputStreamReader(System.in));
		//in = new BufferedReader(new FileReader("input.txt"));
		int n = nextInt();
		int a[] = new int[n];
		int d[] = new int[10];
		int s = 0;
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
			d[a[i]]++;
			s += a[i];
		}

		if (d[0] == 0) {
			System.out.println(-1);
			return;
		}

		int z = 0;
		for (int i = 0; i < 10; i++)
			if (d[i] > 0)
				z++;
		if (z == 1 && d[0] > 0) {
			System.out.println(0);
			return;
		}

		PrintWriter out = new PrintWriter(System.out);
		Arrays.sort(a);
		if (s % 3 == 0) {
			for (int i = n - 1; i >= 0; i--)
				out.print(a[i]);
			out.close();
			return;
		}
		boolean found = false;
		for (int i = 0; i < 10; i++) {
			if (d[i] > 0 && (s - i) % 3 == 0) {
				d[i]--;
				s -= i;
				found = true;
				break;
			}
		}
		if (found) {
			if (s == 0) {
				out.println(0);
			} else {
				for (int i = 9; i >= 0; i--)
					for (int j = 0; j < d[i]; j++)
						out.print(i);
			}
			out.close();
			return;
		}
		outter: for (int i = 0; i < 10; i++) {
			for (int j = i; j < 10; j++) {
				if (i != j){
					if (d[i] > 0 && d[j] > 0 && (s - i - j) % 3 == 0) {
						d[i]--;
						d[j]--;
						s -= i + j;
						found = true;
						break outter;
					}
				}else{
					if (d[i] > 1 && (s - 2*i)%3 == 0){
						d[i]-=2;
						s-=2*i;
						found = true;
						break outter;
					}
				}
			}
		}
		if (found) {
			if (s == 0) {
				out.println(0);
			} else {
				for (int i = 9; i >= 0; i--)
					for (int j = 0; j < d[i]; j++)
						out.print(i);
			}
			out.close();
			return;
		}
		out.println(-1);
		out.close();
	}

	public static void main(String[] args) throws Exception {
		new Main().run();
	}
}


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;

public class B
{
	BufferedReader in;
	PrintStream out;
	StringTokenizer tok;
	public B() throws NumberFormatException, IOException
	{
		in = new BufferedReader(new InputStreamReader(System.in));
		//in = new BufferedReader(new FileReader("in.txt"));
		out = System.out;
		run();
	}
	void run() throws NumberFormatException, IOException
	{
		int[] dig = new int[10];
		int[] dig3 = new int[2];
		int n = nextInt();
		int r = 0;
		boolean exist = false;
		for(int i = 0; i < n; i++)
		{
			int d = nextInt();
			dig[d]++;
			r = (r+d)%3;
			if(d%3!=0)dig3[d%3-1]++;
			if(d==0)exist = true;
		}
		if(r!= 0)
		{
		if(dig3[r-1]>0)
		{
			for(int i = 0; 3*i+r <=9; i++)
				if(dig[3*i+r]>0)
				{
					dig[3*i+r]--;
					break;
				}
		}
		else if (dig3[2-r]>1)
		{
			int q = 2;
			for(int i = 0;3*i+3-r<=9 && q > 0; i++)
			{
				if(q>=dig[i])
				{
					q-=dig[i];
					dig[i] = 0;
				}
				else
				{
					dig[i]-=q;
					q = 0;
				}
			}
		}else exist = false;
		}
		if(!exist)out.println(-1);
		else
		{
			for(int i = 9; i >=0; i--)
				for(int j = 0; j < dig[i]; j++)
					out.print(i);
			out.println();
		}
	}
	public static void main(String[] args) throws NumberFormatException, IOException
	{
		new B();
	}
	String nextToken() throws IOException
	{
		if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine());
		return tok.nextToken();
	}
	int nextInt() throws NumberFormatException, IOException
	{
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws NumberFormatException, IOException
	{
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws NumberFormatException, IOException
	{
		return Double.parseDouble(nextToken());
	}
}


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;

public class B
{
	BufferedReader in;
	PrintStream out;
	StringTokenizer tok;
	public B() throws NumberFormatException, IOException
	{
		in = new BufferedReader(new InputStreamReader(System.in));
		//in = new BufferedReader(new FileReader("in.txt"));
		out = System.out;
		run();
	}
	void run() throws NumberFormatException, IOException
	{
		int[] dig = new int[10];
		int[] dig3 = new int[2];
		int n = nextInt();
		int r = 0;
		boolean exist = false;
		for(int i = 0; i < n; i++)
		{
			int d = nextInt();
			dig[d]++;
			r = (r+d)%3;
			if(d%3!=0)dig3[d%3-1]++;
			if(d==0)exist = true;
		}
		if(dig3[r-1]>0)
		{
			for(int i = 0; 3*i+r <=9; i++)
				if(dig[3*i+r]>0)
				{
					dig[3*i+r]--;
					break;
				}
		}
		else if (dig3[2-r]>1)
		{
			int q = 2;
			for(int i = 0;3*i+3-r<=9 && q > 0; i++)
			{
				if(q>=dig[i])
				{
					q-=dig[i];
					dig[i] = 0;
				}
				else
				{
					dig[i]-=q;
					q = 0;
				}
			}
		}else exist = false;
		if(!exist)out.println(-1);
		else
		{
			for(int i = 9; i >=0; i--)
				for(int j = 0; j < dig[i]; j++)
					out.print(i);
			out.println();
		}
	}
	public static void main(String[] args) throws NumberFormatException, IOException
	{
		new B();
	}
	String nextToken() throws IOException
	{
		if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine());
		return tok.nextToken();
	}
	int nextInt() throws NumberFormatException, IOException
	{
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws NumberFormatException, IOException
	{
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws NumberFormatException, IOException
	{
		return Double.parseDouble(nextToken());
	}
}


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;

public class B
{
	BufferedReader in;
	PrintStream out;
	StringTokenizer tok;
	public B() throws NumberFormatException, IOException
	{
		in = new BufferedReader(new InputStreamReader(System.in));
		//in = new BufferedReader(new FileReader("in.txt"));
		out = System.out;
		run();
	}
	void run() throws NumberFormatException, IOException
	{
		int[] dig = new int[10];
		int[] dig3 = new int[2];
		int n = nextInt();
		int r = 0;
		boolean exist = false;
		for(int i = 0; i < n; i++)
		{
			int d = nextInt();
			dig[d]++;
			r = (r+d)%3;
			if(d%3!=0)dig3[d%3-1]++;
			if(d==0)exist = true;
		}
		if(r!= 0)
		{
			if(dig3[r-1]>0)
			{
				for(int i = 0; 3*i+r <=9; i++)
					if(dig[3*i+r]>0)
					{
						dig[3*i+r]--;
						break;
					}
			}
			else if (dig3[2-r]>1)
			{
				int q = 2;
				for(int i = 0;3*i+3-r<=9 && q > 0; i++)
				{
					if(q>=dig[3*i+3-r])
					{
						q-=dig[3*i+3-r];
						dig[3*i+3-r] = 0;
					}
					else
					{
						dig[3*i+3-r]-=q;
						q = 0;
					}
				}
			}
			else exist = false;
		}
		if(!exist)out.println(-1);
		else
		{
			for(int i = 9; i >=0; i--)
				for(int j = 0; j < dig[i]; j++)
					out.print(i);
			out.println();
		}
	}
	public static void main(String[] args) throws NumberFormatException, IOException
	{
		new B();
	}
	String nextToken() throws IOException
	{
		if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine());
		return tok.nextToken();
	}
	int nextInt() throws NumberFormatException, IOException
	{
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws NumberFormatException, IOException
	{
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws NumberFormatException, IOException
	{
		return Double.parseDouble(nextToken());
	}
}


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;

public class B
{
	BufferedReader in;
	PrintStream out;
	StringTokenizer tok;
	public B() throws NumberFormatException, IOException
	{
		in = new BufferedReader(new InputStreamReader(System.in));
		//in = new BufferedReader(new FileReader("in.txt"));
		out = System.out;
		run();
	}
	void run() throws NumberFormatException, IOException
	{
		int[] dig = new int[10];
		int[] dig3 = new int[2];
		int n = nextInt();
		int r = 0;
		boolean exist = false;
		for(int i = 0; i < n; i++)
		{
			int d = nextInt();
			dig[d]++;
			r = (r+d)%3;
			if(d%3!=0)dig3[d%3-1]++;
			if(d==0)exist = true;
		}
		if(r!= 0)
		{
			if(dig3[r-1]>0)
			{
				for(int i = 0; 3*i+r <=9; i++)
					if(dig[3*i+r]>0)
					{
						dig[3*i+r]--;
						break;
					}
			}
			else if (dig3[2-r]>1)
			{
				int q = 2;
				for(int i = 0;3*i+3-r<=9 && q > 0; i++)
				{
					if(q>=dig[3*i+3-r])
					{
						q-=dig[3*i+3-r];
						dig[3*i+3-r] = 0;
					}
					else
					{
						dig[3*i+3-r]-=q;
						q = 0;
					}
				}
			}
			else exist = false;
		}
		if(!exist)out.println(-1);
		else
		{
			boolean p = false;
			for(int i = 9; i > 0; i--)
				for(int j = 0; j < dig[i]; j++)
				{
					out.print(i);
					p = true;
				}
			if(p)for(int i = 0; i < dig[0]; i++)out.print(0);
			else out.print(0);
			out.println();
		}
	}
	public static void main(String[] args) throws NumberFormatException, IOException
	{
		new B();
	}
	String nextToken() throws IOException
	{
		if(tok ==null || !tok.hasMoreTokens()) tok = new StringTokenizer(in.readLine());
		return tok.nextToken();
	}
	int nextInt() throws NumberFormatException, IOException
	{
		return Integer.parseInt(nextToken());
	}
	long nextLong() throws NumberFormatException, IOException
	{
		return Long.parseLong(nextToken());
	}
	double nextDouble() throws NumberFormatException, IOException
	{
		return Double.parseDouble(nextToken());
	}
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;

public class BB {

    static StreamTokenizer st;
    public static void main(String[] args) throws IOException{
        st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int[]a = new int[n];
        int sum = 0;
        for (int i = 0; i < n; i++) {
            a[i] = nextInt();
            sum += a[i];
        }
        Arrays.sort(a);
        if (a[0] != 0) {
            System.out.println(-1);
            return;
        }
        int[]ans = new int[n+1];
        int t = 1;
        if (sum % 3==0) {
            t = 0;
            for (int i = n-1; i >= 0; i--) {
                ans[t++] = a[i];
            }
        }
        else {
            boolean f = true;
            for (int i = 0; i < n; i++) {
                if ((sum-a[i]) % 3==0) {
                    f = false;
                    t = 0;
                    for (int j = n-1; j >= 0; j--) {
                        if (j != i) {
                            ans[t++] = a[j];
                        }
                    }
                    break;
                }
            }
            if (f) {
                int mod = sum % 3;
                int[]b = new int[4];
                Arrays.fill(b, -1);
                for (int i = 0; i < n; i++) {
                    int m = mod-a[i] % 3;
                    if (m < 0)
                        m += 3;
                    if (b[m] != -1) {
                        t = 0;
                        for (int j = n-1; j >= 0; j--) {
                            if (j != i && j != b[m])
                                ans[t++] = a[j];
                        }
                        break;
                    }
                    if (b[a[i] % 3]==-1)
                        b[a[i] % 3] = i;
                }
            }
        }
        if (ans[0]==0)
            pw.print(0);
        else {
            for (int i = 0; i < t; i++) {
                pw.print(ans[i]);
            }
        }
        pw.close();
    }

    private static int nextInt() throws IOException{
        st.nextToken();
        return (int) st.nval;
    }

}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;

public class BB {

    static StreamTokenizer st;
    public static void main(String[] args) throws IOException{
        st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int[]a = new int[n];
        int sum = 0;
        for (int i = 0; i < n; i++) {
            a[i] = nextInt();
            sum += a[i];
        }
        Arrays.sort(a);
        if (a[0] != 0) {
            System.out.println(-1);
            return;
        }
        int[]ans = new int[n+1];
        int t = 1;
        if (sum % 3==0) {
            t = 0;
            for (int i = n-1; i >= 0; i--) {
                ans[t++] = a[i];
            }
        }
        else {
            boolean f = true;
            for (int i = 0; i < n; i++) {
                if ((sum-a[i]) % 3==0) {
                    f = false;
                    t = 0;
                    for (int j = n-1; j >= 0; j--) {
                        if (j != i) {
                            ans[t++] = a[j];
                        }
                    }
                    break;
                }
            }
            if (f) {
                int mod = sum % 3;
                int[]b = new int[4];
                Arrays.fill(b, -1);
                for (int i = 0; i < n; i++) {
                    if (mod-a[i] % 3 >= 0 && b[mod-a[i] % 3] != -1) {
                        t = 0;
                        for (int j = n-1; j >= 0; j--) {
                            if (j != i && j != b[mod-a[i] % 3])
                                ans[t++] = a[j];
                        }
                        break;
                    }
                    if (b[a[i] % 3]==-1)
                        b[a[i] % 3] = i;
                }
            }
        }
        if (ans[0]==0)
            pw.print(0);
        else {
            for (int i = 0; i < t; i++) {
                pw.print(ans[i]);
            }
        }
        pw.close();
    }

    private static int nextInt() throws IOException{
        st.nextToken();
        return (int) st.nval;
    }

}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;

public class BB {

    static StreamTokenizer st;
    public static void main(String[] args) throws IOException{
        st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int[]a = new int[n];
        int sum = 0;
        for (int i = 0; i < n; i++) {
            a[i] = nextInt();
            sum += a[i];
        }
        Arrays.sort(a);
        if (a[0] != 0) {
            System.out.println(-1);
            return;
        }
        if (sum % 3==0) {
            for (int i = n-1; i >= 0; i--) {
                pw.print(a[i]);
            }
            pw.close();
            return;
        }
        for (int i = 0; i < n; i++) {
            if ((sum-a[i]) % 3==0) {
                for (int j = n-1; j >= 0; j--) {
                    if (j != i)
                        pw.print(a[j]);
                }
                pw.close();
                return;
            }
        }
        for (int i = 0; i < n-1; i++) {
            if ((sum-a[i]-a[i+1]) % 3==0) {
                for (int j = n-1; j >= 0; j--) {
                    if (j != i && j != i+1)
                        pw.print(a[j]);
                }
                pw.close();
                return;
            }
        }
        System.out.println(-1);
    }

    private static int nextInt() throws IOException{
        st.nextToken();
        return (int) st.nval;
    }

}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;

public class BB {

    static StreamTokenizer st;
    public static void main(String[] args) throws IOException{
        st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int[]a = new int[n];
        int sum = 0;
        for (int i = 0; i < n; i++) {
            a[i] = nextInt();
            sum += a[i];
        }
        Arrays.sort(a);
        if (a[0] != 0) {
            System.out.println(-1);
            return;
        }
        int[]ans = new int[n+1];
        int t = 0;
        if (sum % 3==0) {
            for (int i = n-1; i >= 0; i--) {
                ans[t++] = a[i];
            }
        }
        else {
            boolean f = true;
            for (int i = 0; i < n; i++) {
                if ((sum-a[i]) % 3==0) {
                    f = false;
                    for (int j = n-1; j >= 0; j--) {
                        if (j != i) {
                            ans[t++] = a[j];
                        }
                    }
                    break;
                }
            }
            if (f) {
                int mod = sum % 3;
                int[]b = new int[4];
                Arrays.fill(b, -1);
                for (int i = 0; i < n; i++) {
                    if (mod-a[i] % 3 >= 0 && b[mod-a[i] % 3] != -1) {
                        for (int j = n-1; j >= 0; j--) {
                            if (j != i && j != b[mod-a[i] % 3])
                                ans[t++] = a[j];
                        }
                        break;
                    }
                    if (b[a[i] % 3]==-1)
                        b[a[i] % 3] = i;
                }
            }
        }
        if (t==0)
            pw.print(-1);
        else {
            if (ans[0]==0)
                pw.print(0);
            else {
                for (int i = 0; i < t; i++) {
                    pw.print(ans[i]);
                }
            }
        }
        pw.close();
    }

    private static int nextInt() throws IOException{
        st.nextToken();
        return (int) st.nval;
    }

}