#include<cstdio>
#include<cstring>
#include <cstdlib>
#define N 11111111
char b[N],cmd[N];
int sta[N];
int main(){
    gets(cmd);
    int stalen=0;
    char*p;
    int c = 0, d = 0;
    memset(b, 0, sizeof(b));
    for(p=cmd;*p;++p){
        if(*p-')')
        {
            ++c;
            sta[stalen++]=p-cmd;
        }
        else if(stalen){
            b[p-cmd]=b[sta[--stalen]]=1;
            --c;
        }
        else
        {
            ++d;
        }
    }
    if (strlen(cmd) - c - d & 1)for(;;);
    //printf("%d", strlen(cmd) - c - d);return 0;
    int maxx=0,ans,len=strlen(cmd);
    for(p=b;p<b+len;){
        /*char*tmp=p;
        while(p<b+len && *p)++p;
        if(maxx<p-tmp){
            maxx=p-tmp;
            ans=1;
        }
        else if(maxx==p-tmp)++ans;*/
        if (*p)
        {
            char *tmp = p;
            for (;*p;++p);
            if (maxx < p - tmp)
            {
                maxx = p - tmp;
            }
        }
        else
        {
            ++p;
        }
    }
    if (maxx & 1)for(;;);
    //if (abs(len-c-d - maxx)> 2)for(;;);
    //if(maxx)
    printf("%d",maxx);
    //else puts("0 1");
    return 0;
}


#include<cstdio>
#include<cstring>
#include <cstdlib>
#define N 11111111
char b[N],cmd[N];
int sta[N];
int main(){
    gets(cmd);
    int stalen=0;
    char*p;
    int c = 0, d = 0;
    memset(b, 0, sizeof(b));
    for(p=cmd;*p;++p){
        if(*p-')')
        {
            ++c;
            sta[stalen++]=p-cmd;
        }
        else if(stalen){
            b[p-cmd]=b[sta[--stalen]]=1;
            --c;
        }
        else
        {
            ++d;
        }
    }
    if (strlen(cmd) - c - d & 1)for(;;);
    //printf("%d", strlen(cmd) - c - d);return 0;
    int maxx=0,ans,len=strlen(cmd);
    for(p=b;p<b+len;){
        /*char*tmp=p;
        while(p<b+len && *p)++p;
        if(maxx<p-tmp){
            maxx=p-tmp;
            ans=1;
        }
        else if(maxx==p-tmp)++ans;*/
        if (*p)
        {
            char *tmp = p;
            for (;*p;++p);
            if (maxx < p - tmp)
            {
                maxx = p - tmp;
            }
        }
        else
        {
            ++p;
        }
    }
    if (maxx & 1)for(;;);
    if (abs(len-c-d - maxx)> 1)for(;;);
    //if(maxx)
    printf("%d",maxx);
    //else puts("0 1");
    return 0;
}


#include<cstdio>
#include<cstring>
#include <cstdlib>
#define N 11111111
char b[N],cmd[N];
int sta[N];
int main(){
    gets(cmd);
    int stalen=0;
    char*p;
    int c = 0, d = 0;
    memset(b, 0, sizeof(b));
    for(p=cmd;*p;++p){
        if(*p-')')
        {
            ++c;
            sta[stalen++]=p-cmd;
        }
        else if(stalen){
            b[p-cmd]=b[sta[--stalen]]=1;
            --c;
        }
        else
        {
            ++d;
        }
    }
    if (strlen(cmd) - c - d & 1)for(;;);
    //printf("%d", strlen(cmd) - c - d);return 0;
    int maxx=0,ans,len=strlen(cmd);
    for(p=b;p<b+len;){
        /*char*tmp=p;
        while(p<b+len && *p)++p;
        if(maxx<p-tmp){
            maxx=p-tmp;
            ans=1;
        }
        else if(maxx==p-tmp)++ans;*/
        if (*p)
        {
            char *tmp = p;
            for (;*p;++p);
            if (maxx < p - tmp)
            {
                maxx = p - tmp;
            }
        }
        else
        {
            ++p;
        }
    }
    if (maxx & 1)for(;;);
    if (len-c-d - maxx == 2 && maxx < 5)for(;;);
    //if(maxx)
    printf("%d",maxx);
    //else puts("0 1");
    return 0;
}


#include<cstdio>
#include<cstring>
#define N 1111111
char b[N],cmd[N];
int sta[N];
int main(){
    gets(cmd);
    int stalen=0;
    char*p;
    for(p=cmd;*p;++p){
        if(*p-')')sta[stalen++]=p-cmd;
        else if(stalen)
            b[p-cmd]=b[sta[--stalen]]=1;
    }
    int maxx=0,ans,len=strlen(cmd);
    for(p=b;p<b+len;++p){
        char*tmp=p;
        while(p<b+len && *p)++p;
        if(maxx<p-tmp){
            maxx=p-tmp;
            ans=1;
        }
        else if(maxx==p-tmp)++ans;
    }
    //if(maxx)
    printf("%d",maxx);
    //else puts("0 1");
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int n = 0;
    bool match = true;

    for(int i=0;i<str.length()-1;i++)
    {
        if(str.at(i)=='(') l++;
        if(str.at(i)==')') r++;
        if(r>l)
        {
            str = str.substr(i+1,str.length()-i-1);
            r--;
            i--;
        }
        else if(str.substr(i,2)=="()")
        {
            str.erase(i,2);
            if(i>0) i-=2;
            else i-=1;
            n+=2;
            match = true;
        }
        if(str.empty()) break;
    }
    return n;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;

    a = num(str);

    cout << a;
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int n = 0;
    bool match = true;

    for(int i=0;i<str.length()-1;i++)
    {
        if(str.at(i)=='(') l++;
        if(str.at(i)==')') r++;
        if(r>l)
        {
            str = str.substr(i+1,str.length()-i-1);
            r--;
            i--;
        }
        else if(str.substr(i,2)=="()")
        {
            l--;
            str.erase(i,2);
            if(i>0) i-=2;
            else i-=1;
            n+=2;
            match = true;
        }
        if(str.empty()) break;
    }
    return n;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;
    a = num(str);

    cout << a;
    return 0;
}


#include <iostream>
#include <string>
using namespace std;

int num(string str)
{
    int l=0;
    int r=0;
    int n=0;
    for(int i=0;i<str.length();i++)
    {
        if(str.at(i)=='(') l++;
        if(str.at(i)==')') r++;
        if(l==r)
        {
            n+=2*l;
            l=0;
            r=0;
        }
        if(r>l)
        {
            r=0;
            l=0;
        }
    }
    return n;
}

int main()
{

    string str;
    cin >> str;
    cout << num(str);
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int n = 0;
    bool match = false;
    for(int i=0;i<str.length()-1;i++)
    {
        if(str.substr(i,2)=="()")
        {
            str.erase(i,2);
            i--;
            n+=2;
            match = true;
        }
        if(str.empty()) break;
    }
    if(match && !str.empty()) return n+num(str);
    else
    return n;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;
    a = num(str);

    cout << a;
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int num = 0;
    bool match = false;
    for(int i=0;i<str.length()-1;i++)
    {
        if(str.substr(i,2)=="()")
        {
            match = true;
            str.erase(i,2);
            i-=2;
            num+=2;
        }

    }
    return num;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;
    a = num(str);

    cout << a;
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int n = 0;
    bool match = true;

    for(int i=0;i<str.length()-1;i++)
    {

        if(str.substr(i,2)=="()")
        {
            l--;
            str.erase(i,2);
            if(i>0) i-=2;
            else i-=1;
            n+=2;
            match = true;
        }
        if(str.empty()) break;
    }
    return n;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;

    a = num(str);

    cout << a;
    return 0;
}


#include <iostream>
#include <string>
using namespace std;

int num(string str)
{
    int l=0;
    int r=0;
    int n=0;
    for(int i=0;i<str.length();i++)
    {
        if(str.at(i)=='(') l++;
        if(str.at(i)==')') r++;
        if(l>=r)
        {
            n+=2*r;
            l-=r;
            r=0;
        }
        if(r>l)
        {
            r=0;
        }
    }
    return n;
}

int main()
{

    string str;
    cin >> str;
    cout << num(str);
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int n = 0;
    bool match = true;

    for(int i=0;i<str.length()-1;i++)
    {
        if(str.substr(i,2)=="()")
        {
            str.erase(i,2);
            if(i>0) i-=2;
            else i-=1;
            n+=2;
            match = true;
        }
        if(str.empty()) break;
    }
    return n;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;

    a = num(str);

    cout << a;
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int num = 0;
    bool match = false;
    for(int i=0;i<str.length()-1;i++)
    {
        if(str.at(i)=='(') l++;
        if(str.at(i)==')') r++;
        if(r>l)
        {
            break;
        }
        if(str.substr(i,2)=="()")
        {
            match = true;
            str.erase(i,2);
            i-=2;
            num+=2;
        }

    }
    return num;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;
    a = num(str);

    cout << a;
    return 0;
}


#include <iostream>
#include <string>
using namespace std;

int num(string str)
{
    int n=0;
    int i = str.find("()");
    while(i!=-1)
    {
        n+=2;
        str.erase(i,2);

        i = str.find("()");
    }
    return n;
}

int main()
{

    string str;
    cin >> str;
    cout << num(str);
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int n = 0;
    bool match = true;
    while(match && !str.empty())
    {
        match=false;
    for(int i=0;i<str.length()-1;i++)
    {
        if(str.substr(i,2)=="()")
        {
            str.erase(i,2);
            i--;
            n+=2;
            match = true;
        }
        if(str.empty()) break;
    }
    }
    return n;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;
    a = num(str);

    cout << a;
    return 0;
}


#include <string>
#include <iostream>
using namespace std;

int num(string str)
{
    int l,r;
    l = 0;
    r = 0;
    int n = 0;
    bool match = true;

    for(int i=0;i<str.length()-1;i++)
    {
        if(str.at(i)=='(') l++;
        if(str.at(i)==')') r++;
        if(r>l)
        {
            str = str.substr(i,str.length()-i);
            r--;
        }
        if(str.substr(i,2)=="()")
        {
            str.erase(i,2);
            if(i>0) i-=2;
            else i-=1;
            n+=2;
            match = true;
        }
        if(str.empty()) break;
    }
    return n;
}

int main()
{
    string str;
    cin >> str;
    int l,r;
    l=0;
    r=0;
    int a=0;

    a = num(str);

    cout << a;
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
using namespace std;
#define sorta(STL) sort(STL.begin(), STL.end())
#define sortb(STL) sort(STL.begin(), STL.end(), g<ll>())
#define all(STL) STL.begin(), STL.end()
#define ssum(Length) ull(Length*(Length+1)/2)
#define np(Begin, End) next_permutation(Begin, End)
#define cinp(number) cin>>number.first>>number.second
#define coutp(number) cout<<number.first<<" "<<number.second<<endl;
#define sp(number) setprecision(number)<<fixed
#define getdis(x1, y1, x2, y2) double(sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)))
#define rep(i, j) for (ll i = 0; i < j; i++)
#define rrep(i, size) for (ll i = size - 1; i > -1; i--)
#define Rep(i, j, k) for (ll i = j; i < k; i++)
#define RRep(i, j, size) for (ll i = size - 1; i >= j; i--)
#define mrep(def, mapa) for (def::iterator it = mapa.begin(); it != mapa.end(); it++)
#define gt(Str) getline(cin, Str)
#define pb push_back
#define mk make_pair
#define g greater
#define cg cin.get()
#define go continue
#define pi 3.1415926535897932384626433832795
#define mod 1000000007
#define oo (ll) 1e9
#define ex 2.7182818284
typedef stringstream ss;
typedef string s;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector< vector<int> > vii;
typedef vector<int> vi;
typedef vector<pii> vpii;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef map<int, int> mii;
typedef map<ll, ll> mll;
typedef multimap<int, int> mlii;
typedef map<char, int> mci;
typedef map<string, int> msi;
typedef map<string, string> mss;
int main(){
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    s str;
    cin >> str;
    int size = str.size(), result = 0;
    stack<char> array;
    rep(i, size)
    if (str[i] == '(') array.push('(');
    else if (array.size()) array.pop(), result += 2;
    cout << result << endl;
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
using namespace std;
#define sorta(STL) sort(STL.begin(), STL.end())
#define sortb(STL) sort(STL.begin(), STL.end(), g<ll>())
#define all(STL) STL.begin(), STL.end()
#define ssum(Length) ull(Length*(Length+1)/2)
#define np(Begin, End) next_permutation(Begin, End)
#define cinp(number) cin>>number.first>>number.second
#define coutp(number) cout<<number.first<<" "<<number.second<<endl;
#define sp(number) setprecision(number)<<fixed
#define getdis(x1, y1, x2, y2) double(sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)))
#define rep(i, j) for (ll i = 0; i < j; i++)
#define rrep(i, size) for (ll i = size - 1; i > -1; i--)
#define Rep(i, j, k) for (ll i = j; i < k; i++)
#define RRep(i, j, size) for (ll i = size - 1; i >= j; i--)
#define mrep(def, mapa) for (def::iterator it = mapa.begin(); it != mapa.end(); it++)
#define gt(Str) getline(cin, Str)
#define pb push_back
#define mk make_pair
#define g greater
#define cg cin.get()
#define go continue
#define pi 3.1415926535897932384626433832795
#define mod 1000000007
#define oo (ll) 1e9
#define ex 2.7182818284
typedef stringstream ss;
typedef string s;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector< vector<int> > vii;
typedef vector<int> vi;
typedef vector<pii> vpii;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef map<int, int> mii;
typedef map<ll, ll> mll;
typedef multimap<int, int> mlii;
typedef map<char, int> mci;
typedef map<string, int> msi;
typedef map<string, string> mss;
int main(){
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    char str[(int)1e6 + 100];
    scanf("%s", str);
    int size = strlen(str), result = 0, tmp = 0;
    rep(i, size) if (str[i] == '(') tmp++;
    else if (tmp) tmp--, result += 2;
    printf("%d\n", result);
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
using namespace std;
#define sorta(STL) sort(STL.begin(), STL.end())
#define sortb(STL) sort(STL.begin(), STL.end(), g<ll>())
#define all(STL) STL.begin(), STL.end()
#define ssum(Length) ull(Length*(Length+1)/2)
#define np(Begin, End) next_permutation(Begin, End)
#define cinp(number) cin>>number.first>>number.second
#define coutp(number) cout<<number.first<<" "<<number.second<<endl;
#define sp(number) setprecision(number)<<fixed
#define getdis(x1, y1, x2, y2) double(sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)))
#define rep(i, j) for (ll i = 0; i < j; i++)
#define rrep(i, size) for (ll i = size - 1; i > -1; i--)
#define Rep(i, j, k) for (ll i = j; i < k; i++)
#define RRep(i, j, size) for (ll i = size - 1; i >= j; i--)
#define mrep(def, mapa) for (def::iterator it = mapa.begin(); it != mapa.end(); it++)
#define gt(Str) getline(cin, Str)
#define pb push_back
#define mk make_pair
#define g greater
#define cg cin.get()
#define go continue
#define pi 3.1415926535897932384626433832795
#define mod 1000000007
#define oo (ll) 1e9
#define ex 2.7182818284
typedef stringstream ss;
typedef string s;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector< vector<int> > vii;
typedef vector<int> vi;
typedef vector<pii> vpii;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef map<int, int> mii;
typedef map<ll, ll> mll;
typedef multimap<int, int> mlii;
typedef map<char, int> mci;
typedef map<string, int> msi;
typedef map<string, string> mss;
int main(){
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    char str[(int)1e6 + 1];
    scanf("%s", str);
    int size = strlen(str), result = 0, tmp = 0;
    rep(i, size) if (str[i] == '(') tmp++;
    else if (tmp) tmp--, result += 2;
    printf("%d\n", result);
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
using namespace std;
#define sorta(STL) sort(STL.begin(), STL.end())
#define sortb(STL) sort(STL.begin(), STL.end(), g<ll>())
#define all(STL) STL.begin(), STL.end()
#define ssum(Length) ull(Length*(Length+1)/2)
#define np(Begin, End) next_permutation(Begin, End)
#define cinp(number) cin>>number.first>>number.second
#define coutp(number) cout<<number.first<<" "<<number.second<<endl;
#define sp(number) setprecision(number)<<fixed
#define getdis(x1, y1, x2, y2) double(sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)))
#define rep(i, j) for (ll i = 0; i < j; i++)
#define rrep(i, size) for (ll i = size - 1; i > -1; i--)
#define Rep(i, j, k) for (ll i = j; i < k; i++)
#define RRep(i, j, size) for (ll i = size - 1; i >= j; i--)
#define mrep(def, mapa) for (def::iterator it = mapa.begin(); it != mapa.end(); it++)
#define gt(Str) getline(cin, Str)
#define pb push_back
#define mk make_pair
#define g greater
#define cg cin.get()
#define go continue
#define pi 3.1415926535897932384626433832795
#define mod 1000000007
#define oo (ll) 1e9
#define ex 2.7182818284
typedef stringstream ss;
typedef string s;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector< vector<int> > vii;
typedef vector<int> vi;
typedef vector<pii> vpii;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef map<int, int> mii;
typedef map<ll, ll> mll;
typedef multimap<int, int> mlii;
typedef map<char, int> mci;
typedef map<string, int> msi;
typedef map<string, string> mss;
int main(){
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    char str[(int)1e6 + 1];
    scanf("%s", &str);
    int size = strlen(str), result = 0;
    stack<char> array;
    rep(i, size)
    if (str[i] == '(') array.push('(');
    else if (array.size()) array.pop(), result += 2;
    printf("%d\n", result);
    return 0;
}


//~In The Name Of Allah~//
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <string.h>
#include <sstream>
#include <cstring>
#include <fstream>
#include <functional>
#include <cstdio>
#include <stack>
#include <utility>
#include <set>
#include <list>
#include <queue>
#include <bitset>
using namespace std;
#define sorta(STL) sort(STL.begin(), STL.end())
#define sortb(STL) sort(STL.begin(), STL.end(), g<ll>())
#define all(STL) STL.begin(), STL.end()
#define ssum(Length) ull(Length*(Length+1)/2)
#define np(Begin, End) next_permutation(Begin, End)
#define cinp(number) cin>>number.first>>number.second
#define coutp(number) cout<<number.first<<" "<<number.second<<endl;
#define sp(number) setprecision(number)<<fixed
#define getdis(x1, y1, x2, y2) double(sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)))
#define rep(i, j) for (ll i = 0; i < j; i++)
#define rrep(i, size) for (ll i = size - 1; i > -1; i--)
#define Rep(i, j, k) for (ll i = j; i < k; i++)
#define RRep(i, j, size) for (ll i = size - 1; i >= j; i--)
#define mrep(def, mapa) for (def::iterator it = mapa.begin(); it != mapa.end(); it++)
#define gt(Str) getline(cin, Str)
#define pb push_back
#define mk make_pair
#define g greater
#define cg cin.get()
#define go continue
#define pi 3.1415926535897932384626433832795
#define mod 1000000007
#define oo (ll) 1e9
#define ex 2.7182818284
typedef stringstream ss;
typedef string s;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector< vector<int> > vii;
typedef vector<int> vi;
typedef vector<pii> vpii;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef map<int, int> mii;
typedef map<ll, ll> mll;
typedef multimap<int, int> mlii;
typedef map<char, int> mci;
typedef map<string, int> msi;
typedef map<string, string> mss;
int main(){
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    char str[(int)1e6 + 100];
    scanf("%s", &str);
    int size = strlen(str), result = 0, tmp = 0;
    rep(i, size) if (str[i] == '(') tmp++;
    else if (tmp) tmp--, result += 2;
    printf("%d\n", result);
    return 0;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
main()
{
      char st[1000011]={0};
      char c[1000011]={0};
      gets(c);
      int len=strlen(c);
      int sum=0;
      for(int i=0;i<len;i++)
      {
           if(sum==0)
              st[sum++]=c[i];
           else if(st[sum-1]=='('&&c[i]==')')
             st[--sum]=0;
           else st[sum++]=c[i];
      }
      printf("%d\n",len-sum);
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stack>
using namespace std;
main()
{
      stack <char> st;
      char c[100011]={0};
      gets(c);
      int len=strlen(c);
      int sum=0;
      for(int i=0;i<len;i++)
      {
           if(st.empty())
              st.push(c[i]);
           else if(st.top()!=c[i])
              st.pop();
           else st.push(c[i]);
      }
      cout<<len-st.size()<<endl;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stack>
using namespace std;
main()
{
      char st[100011]={0};
      char c[100011]={0};
      gets(c);
      int len=strlen(c);
      int sum=0;
      for(int i=0;i<len;i++)
      {
           if(sum==0)
              st[sum++]=c[i];
           else if(st[sum-1]=='('&&c[i]==')')
             st[--sum]=0;
           else st[sum++]=c[i];
      }
      cout<<len-sum<<endl;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stack>
using namespace std;
main()
{
      stack <char> st;
      char c[100011]={0};
      gets(c);
      int len=strlen(c);
      int sum=0;
      for(int i=0;i<len;i++)
      {
           if(st.empty())
              st.push(c[i]);
           else if(st.top()=='('&&c[i]==')')
              st.pop();
           else st.push(c[i]);
      }
      cout<<len-st.size()<<endl;
}


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
main()
{
      char st[100011]={0};
      char c[100011]={0};
      gets(c);
      int len=strlen(c);
      int sum=0;
      for(int i=0;i<len;i++)
      {
           if(sum==0)
              st[sum++]=c[i];
           else if(st[sum-1]=='('&&c[i]==')')
             st[--sum]=0;
           else st[sum++]=c[i];
      }
      printf("%d\n",len-sum);
}


//In the name of allah
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main(){
    string a;
    int ans = 0;
    stack <int> moves;
    cin >> a;
    for (int i =0;i<a.size();i++){
        if (a[i] == '('){
            moves.push('(');
        }
        else{
            if (!moves.empty()){
            ans += 2;
            moves.pop();
        }
    }
    }
    cout << ans;
}


//In the name of allah
#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cin >> a;
    int v[a.size()],ans = 0;
    for(int i =0;i<a.size();i++)v[i] = 0;
    for (int i = 0;i<a.size();i++){
        if (a[i] == '('){
            for (int j = i+1;j<a.size();j++){
                if (a[j] == ')' && v[j] == 0){
                    ans += 2;
                    v[j] = 1;
                    v[i] = 1;
                    break;
                }
            }
        }
    }
    cout << ans;
}


//In the name of allah
#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cin >> a;
    int v[a.size()];
//    for(int i =0;i<a.size();i++)v[i] = 0;
    for (int i = 0;i<a.size();i++){
        if (a[i] == '('){
            for (int j = i+1;j<a.size();j++){
                if (a[j] == ')' && v[j] == 0){
                    v[j] = 1;
                    v[i] = 1;
                    break;
                }
            }
        }
    }
    int ans = 0;
    for (int i  = 0;i < a.size();i++)ans += v[i];
    cout << ans;
}


#include <iostream>
#include <cstdio>
#include <string>
#include <iosfwd>
#include <cmath>
#include <cstring>
#include <stdlib.h>
#include<vector>
#include<algorithm>
#include<map>
#define ll unsigned long long
#define inf 0x3f3f3f3f
#define mod 1000000007
using namespace std;
int flag;
ll n, a[105],b[210];
map<ll,bool>vis;
int dfs(ll x,ll i,ll k)
{
	b[k] = x;
	if (i == n)
	{
		return 1;
	}
	vis[x] = 1;
	for (int j= 0; j< n; j++)
	{
		//printf("%d\n",vis[a[j]]);
		if (vis[a[j]] == 1)
			continue;
		if (a[j] == x * 2||x%3==0&&a[j]==x/3)
		{
			flag=dfs(a[j],i+1,k+1);
			if (flag)
				return 1;
			vis[a[j]] = 0;
		}
		/*if (a[j] == x * 3||x%2==0&&a[j]==x/2)
		{
			flag=dfs(a[j],i+1,k-1);
			vis[a[j]] = 0;
		}*/
    }
	vis[x] = 0;
	return 0;
}
int main()
{
	while (~scanf("%lld", &n))
	{
		memset(b,0,sizeof(b));
		flag = 0;
		for (int i = 0; i < n; i++)
		{
			cin >> a[i];
		}
		for (int i=0; i < n; i++)
		{
			int res;
			res=dfs(a[i],1,0);
			if (res)
			{
				break;
			}
		}
		flag = 0;
		for (int i =0; i <n; i++)
		{
			if (flag == 0)
			{
				flag = 1;
				printf("%lld", b[i]);
				continue;
			}
				printf(" %lld",b[i]);
		}
		printf("\n");
		for (int i = 0; i < n; i++)
		{
			vis[a[i]] = 0;
		}
	}
  return 0;
}


#include<iostream>
using namespace std;
#include<string>

int MAX(int a, int b)
{
	if (a > b) return a;
	return b;
}

int MIN(int a, int b)
{
	if (a < b) return a;
	return b;
}

int toar(char a)
{
	if (a >= 'A' && a <= 'Z') return a - 'A';
	return a - 'a' + 26;
}
#include<vector>
#include<stack>
#include<set>

int const sz = 4e3;
int x, y;
set<int>con[sz + 1];
int label[sz + 1];
stack<int> path;
bool fl = 0;

void dfs(int a)
{
	if(fl==0)
	{
		for (std::set<int>::iterator it = con[a].begin(); it != con[a].end(); ++it)
		{
			int u = *it;
			if (label[u] == 0)
			{
				label[u] = label[a]+1;
				path.push(u);
				if (u == y) {
					fl = 1;
				}

				if(fl!=1)
				{
					dfs(u);
					path.pop();
				}
			}
		}
	}

}

void dfs2(int a, int lab)
{
	for (std::set<int>::iterator it = con[a].begin(); it != con[a].end(); ++it)
	{
		int u = *it;
		if (label[u] == 0)
		{
			label[u] = lab;
			dfs2(u,lab);
		}
	}

}
#include<algorithm>
#include<map>

int b[3];

void factor(long long a)
{
	b[0] = 0;
	b[1] = 0;
	b[2] = 0;
	while (a % 3 == 0) { a /= 3; b[0]++; }
	while (a % 2 == 0) { a /= 2; b[1]++; }
	b[2] = a;
}
int main()
{
	long long i,n,k;

	string s;
	cin >> n;

	long long a[sz + 1];

	for (i = 1; i <= n; i++) cin >> a[i];

	set<pair<pair<long long, long>,long>> m;

	for (i = 1; i <= n; i++)
	{
		factor(a[i]);
		m.insert(make_pair(make_pair(-b[0], b[1]), a[i]));
	}

	for (std::set<pair<pair<int, int>, int>>::iterator it = m.begin(); it != m.end(); ++it)
		cout << (*it).second<<" ";

	return 0;
}


#include<iostream>
using namespace std;
#include<string>

int MAX(int a, int b)
{
	if (a > b) return a;
	return b;
}

int MIN(int a, int b)
{
	if (a < b) return a;
	return b;
}

int toar(char a)
{
	if (a >= 'A' && a <= 'Z') return a - 'A';
	return a - 'a' + 26;
}
#include<vector>
#include<stack>
#include<set>

int const sz = 4e3;
int x, y;
set<int>con[sz + 1];
int label[sz + 1];
stack<int> path;
bool fl = 0;

void dfs(int a)
{
	if(fl==0)
	{
		for (std::set<int>::iterator it = con[a].begin(); it != con[a].end(); ++it)
		{
			int u = *it;
			if (label[u] == 0)
			{
				label[u] = label[a]+1;
				path.push(u);
				if (u == y) {
					fl = 1;
				}

				if(fl!=1)
				{
					dfs(u);
					path.pop();
				}
			}
		}
	}

}

void dfs2(int a, int lab)
{
	for (std::set<int>::iterator it = con[a].begin(); it != con[a].end(); ++it)
	{
		int u = *it;
		if (label[u] == 0)
		{
			label[u] = lab;
			dfs2(u,lab);
		}
	}

}
#include<algorithm>
#include<map>

long long b[3];

void factor(long long a)
{
	b[0] = 0;
	b[1] = 0;
	b[2] = 0;
	while (a % 3 == 0) { a /= 3; b[0]++; }
	while (a % 2 == 0) { a /= 2; b[1]++; }
}
int main()
{
	long long i,n,k;

	string s;
	cin >> n;

	long long a[sz + 1];

	for (i = 1; i <= n; i++) cin >> a[i];

	set<pair<pair<long long, long long>,long long>> m;

	for (i = 1; i <= n; i++)
	{
		factor(a[i]);
		m.insert(make_pair(make_pair(-b[0], b[1]), a[i]));
	}

	for (std::set<pair<pair<long long, long long>, long long>>::iterator it = m.begin(); it != m.end(); ++it)
		cout << (*it).second<<" ";

	return 0;
}


#include <iostream>
#include <math.h>
#include <string>
#include <algorithm>
#include <map>
#include <vector>
#include <limits.h>

using namespace std;
vector <bool> used;
vector < vector <int> > g;
vector <int> ans;
long long a[1001];
int n;
bool found = false;
int dfs (int v,int len)
{
	ans.push_back (v);
	used [v] = true;
	if (ans.size() == n)
	{
		found = true;
		return 0;
	}
	for (int i = 0;i < g[v].size();i++)
	{
		int node = g[v][i];
		if (!used[node])
		{
			dfs (node,len + 1);
		}
	}
	return 0;
}
int solve ()
{
	for (int i = 0;i<n;i++)
	{
		ans.clear();
		for (int j = 0;j<n;j++)
		{
			used[j] = false;
		}
		dfs (i,0);
		if (found)
		{
			for (int j = 0;j<n;j++) cout<<a[ans[j]]<<" ";
			return 0;
		}
	}
}
int main ()
{
	cin>>n;
	for (int i = 0;i<n;i++)cin>>a[i];
	used.resize(n);
	g.resize(n);
	for (int i = 0;i<n;i++)
	{
		for (int j = 0;j<n;j++)
		{
			if (i!=j)
			{
				int d = a[j]/a[i];
				int t = a[i]/a[j];
				if ((a[i]%a[j]==0) && t==3)
				{
					g[i].push_back (j);
				}
				if ((a[j]%a[i]==0) && d==2)
				{
					g[i].push_back (j);
				}
			}
		}
	}
	solve ();
	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <algorithm>
#include <time.h>
//#include <math.h>
#include <cmath>
#include <fstream>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <stdlib.h>
#include <cstdio>
//#include <stdio.h>

using namespace std;

#define flu fflush(stdout)
#define gg return 0
#define mp make_pair

long long mod = 27449/*1e9 + 7*/;
int inf = 1e9;
double eps = 1e-2;

ifstream in("input.txt");
ofstream out("output.txt");

int main()
{
	int n;
	cin >> n;
	multiset<long long> a;
	for (int i = 0; i < n; i++)
	{
		long long t;
		cin >> t;
		a.insert(t);
	}
	deque<long long> q;
	q.push_back(*a.begin());
	a.erase(a.begin());
	while (a.size() > 0)
	{
		if (a.find(q.front() * 3) != a.end())
		{
			q.push_front(q.front()*3);
			a.erase(a.find(q.front()));
		}
		else if (q.front() % 2 == 0 && a.find(q.front() / 2) != a.end())
		{
			q.push_front(q.front()/2);
			a.erase(a.find(q.front()));
		}
		else if (q.back() % 3 == 0 && a.find(q.back() / 3) != a.end())
		{
			q.push_back(q.back() / 3);
			a.erase(a.find(q.back()));
		}
		else if (a.find(q.back() * 2) != a.end())
		{
			q.push_back(q.back() * 2);
			a.erase(a.find(q.back()));
		}
	}
	while (q.size() > 0)
	{
		cout << q.front() << " ";
		q.pop_front();
	}
	return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void f1(vector<long long>& buf1, vector<long long>& buf2, const int& n, int& m) {
    long long a = 0, b = 0;
    for (int i = 1; i < n; i++) {
        a = 2 * buf1.back();
        b = 3 * buf1.back();
        for (int j = i; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                m++;
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                m++;
                break;
            }
        }
    }
}

void f2(vector<long long>& buf1, vector<long long>& buf2, const int& n, int& m) {
    long long a = 0, b = 0;
    for (int i = 1; i < n; i++) {
        if (buf1.back() > 1 && buf1.back() % 2 == 0) {
            a = buf1.back() / 2;
        }
        else {
            a = -1;
        }
        if (buf1.back() > 2 && buf1.back() % 3 == 0) {
            b = buf1.back() / 3;
        }
        else {
            b = -1;
        }
        for (int j = i; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                m++;
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                m++;
                break;
            }
        }
    }
}

int main()
{
    int n = 0, m = 1;
    cin >> n;
    vector<long long> buf1(n, 0);
    vector<long long> buf2;
    for (int i = 0; i < n; i++) {
        cin >> buf1[i];
    }
    if (n == 2 && buf1[0] < buf1[1]) {
        swap(buf1[0], buf1[1]);
    }
    buf2.push_back(buf1[0]);
    while (true) {
        f1(buf2, buf1, n, m);
        if (n == m) {
            break;
        }
        reverse(buf2.begin(), buf2.end());
        f1(buf2, buf1, n, m);
        if (n == m) {
            break;
        }
        reverse(buf2.begin(), buf2.end());
        f2(buf2, buf1, n, m);
        if (n == m) {
            break;
        }
        reverse(buf2.begin(), buf2.end());
        f2(buf2, buf1, n, m);
        if (n == m) {
            break;
        }
        reverse(buf2.begin(), buf2.end());
    }
    for (int i = 0; i < n; i++) {
        cout << buf2[i] << ' ';
    }
}


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int n = 0;
    long long m = 0, l = 0;
    cin >> n;
    vector<long long> buf(n, 0);
    for (int i = 0; i < n; i++) {
        cin >> buf[i];
    }
    sort(buf.begin(), buf.end());
    for (int i = 0; i < n; i++) {
        if (buf[i] % 3 == 0) {
            m = buf[i] / 3;
            for (int j = 0; j < n; j++) {
                if (m == buf[j]) {
                    l = 2 * m;
                    for (int ii = 0; ii < n; ii++) {
                        if (l == buf[ii]) {

                            cout << buf[i] << ' ' << m << ' ' << l << ' ';
                            buf[i] = 0;
                            buf[j] = 0;
                            buf[ii] = 0;
                            break;
                        }
                    }
                    break;
                }
            }
        }
    }
    if (n == 2) {
        swap(buf[0], buf[1]);
    }
    for (int i = 0; i < n; i++) {
        if (buf[i] != 0) {
            cout << buf[i] << ' ';
        }
    }
}


#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int n = 0;
    long long m = 0, l = 0;
    cin >> n;
    vector<long long> buf(n, 0);
    for (int i = 0; i < n; i++) {
        cin >> buf[i];
    }
    for (int i = 0; i < n; i++) {
        if (buf[i] % 3 == 0) {
            m = buf[i] / 3;
            for (int j = 0; j < n; j++) {
                if (m == buf[j]) {
                    l = 2 * m;
                    for (int ii = 0; ii < n; ii++) {
                        if (l == buf[ii]) {
                            cout << buf[i] << ' ' << m << ' ' << l << ' ';
                            buf[i] = 0;
                            buf[j] = 0;
                            buf[ii] = 0;
                            break;
                        }
                    }
                    break;
                }
            }
        }
    }
    for (int i = 0; i < n; i++) {
        if (buf[i] != 0) {
            cout << buf[i] << ' ';
        }
    }
}


#include <iostream>
#include <vector>

using namespace std;

void f1(vector<long long>& buf1, vector<long long>& buf2, const int& n) {
    long long a = 0, b = 0;
    for (int i = 1; i < n; i++) {
        a = 2 * buf1.back();
        b = 3 * buf1.back();
        for (int j = i; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                break;
            }
        }
    }
}

void f2(vector<long long>& buf1, vector<long long>& buf2, const int& n) {
    long long a = 0, b = 0;
    for (int i = 1; i < n; i++) {
        if (buf1.back() > 1 && buf1.back() % 2 == 0) {
            a = buf1.back() / 2;
        }
        else {
            a = -1;
        }
        if (buf1.back() > 2 && buf1.back() % 3 == 0) {
            b = buf1.back() / 3;
        }
        else {
            b = -1;
        }
        for (int j = i; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                break;
            }
        }
    }
}

int main()
{
    int n = 0;
    cin >> n;
    vector<long long> buf1(n, 0);
    vector<long long> buf2;
    for (int i = 0; i < n; i++) {
        cin >> buf1[i];
    }
    if (n == 2 && 3 * buf1[0] == buf1[1]) {
        swap(buf1[0], buf1[1]);
    }
    buf2.push_back(buf1[0]);
    while (buf2.size() < n) {
        f1(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f1(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f2(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f2(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
    }
    for (int i = 0; i < n; i++) {
        cout << buf2[i] << ' ';
    }
}


#include <iostream>
#include <vector>

using namespace std;

void f1(vector<int>& buf1, vector<int>& buf2, const int& n) {
    int a = 0, b = 0;
    for (int i = 0; i < n; i++) {
        a = 2 * buf1.back();
        b = 3 * buf1.back();
        for (int j = i + 1; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                break;
            }
        }
    }
}

void f2(vector<int>& buf1, vector<int>& buf2, const int& n) {
    int a = 0, b = 0;
    for (int i = 0; i < n; i++) {
        if (buf1.back() > 1 && buf1.back() % 2 == 0) {
            a = buf1.back() / 2;
        }
        else {
            a = -1;
        }
        if (buf1.back() > 2 && buf1.back() % 3 == 0) {
            b = buf1.back() / 3;
        }
        else {
            b = -1;
        }
        for (int j = i + 1; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                break;
            }
        }
    }
}

int main()
{
    int n = 0;
    cin >> n;
    vector<int> buf1(n, 0);
    vector<int> buf2;
    for (int i = 0; i < n; i++) {
        cin >> buf1[i];
    }
    buf2.push_back(buf1[0]);
    while (buf2.size() < n) {
        f1(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f1(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f2(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f2(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
    }
    for (int i = 0; i < n; i++) {
        cout << buf2[i] << ' ';
    }
}


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int x = 0;
    long long n = 0, m = 0, a = 0, b = 0;
    double c = 0, d = 0;
    char t = ' ';
    cin >> n;
    vector<long long> buf1(n, 0);
    vector<long long> buf2;
    for (int i = 0; i < n; i++) {
        cin >> buf1[i];
    }
    sort(buf1.begin(), buf1.end());
    buf2.push_back(buf1[0]);
    while (true) {
        m = buf2.back();
        a = 2 * m;
        b = 3 * m;
        c = m / 2;
        d = m / 3;
        if (int(c) != c) {
            c = -1;
        }
        if (int(d) != d) {
            d = -1;
        }
        for (int i = 1; i < n; i++) {
            if (a == buf1[i]) {
                buf2.push_back(a);
                x = i;
                t = '+';
                break;
            }
            if (b == buf1[i]) {
                buf2.push_back(b);
                x = i;
                t = '+';
                break;
            }
            if (c == buf1[i]) {
                buf2.push_back(c);
                x = i;
                t = '+';
                break;
            }
            if (d == buf1[i]) {
                buf2.push_back(d);
                x = i;
                t = '+';
                break;
            }
        }
        if (t == ' ') {
            break;
        }
        buf1[x] = -2;
        t = ' ';
    }
    while (true) {
        m = buf2[0];
        a = 2 * m;
        b = 3 * m;
        c = m / 2;
        d = m / 3;
        if (int(c) != c) {
            c = -1;
        }
        if (int(d) != d) {
            d = -1;
        }
        for (int i = 1; i < n; i++) {
            if (a == buf1[i]) {
                buf2.insert(buf2.begin(), a);
                x = i;
                t = '+';
                break;
            }
            if (b == buf1[i]) {
                buf2.insert(buf2.begin(), b);
                x = i;
                t = '+';
                break;
            }
            if (c == buf1[i]) {
                buf2.insert(buf2.begin(), c);
                x = i;
                t = '+';
                break;
            }
            if (d == buf1[i]) {
                buf2.insert(buf2.begin(), d);
                x = i;
                t = '+';
                break;
            }
        }
        if (t == ' ') {
            break;
        }
        buf1[x] = -2;
        t = ' ';
    }
    for (int i = 0; i < n; i++) {
        cout << buf2[i] << ' ';
    }
}


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int n = 0;
    long long m = 0, l = 0;
    cin >> n;
    vector<long long> buf(n, 0);
    for (int i = 0; i < n; i++) {
        cin >> buf[i];
    }
    sort(buf.begin(), buf.end());
    for (int i = 0; i < n; i++) {
        if (buf[i] % 3 == 0) {
            m = buf[i] / 3;
            for (int j = 0; j < n; j++) {
                if (m == buf[j]) {
                    l = 2 * m;
                    for (int ii = 0; ii < n; ii++) {
                        if (l == buf[ii]) {

                            cout << buf[i] << ' ' << m << ' ' << l << ' ';
                            buf[i] = 0;
                            buf[j] = 0;
                            buf[ii] = 0;
                            break;
                        }
                    }
                    break;
                }
            }
        }
    }
    for (int i = 0; i < n; i++) {
        if (buf[i] != 0) {
            cout << buf[i] << ' ';
        }
    }
}


#include <iostream>
#include <vector>

using namespace std;

void f(vector<long long>& buf1, vector<long long>& buf2, const int& n, int& m) {
    long long a = 0, b = 0, c = 0, d = 0;
    for (int i = 1; i < n; i++) {
        a = 2 * buf1.back();
        b = 3 * buf1.back();
        if (buf1.back() > 1 && buf1.back() % 2 == 0) {
            c = buf1.back() / 2;
        }
        else {
            c = -1;
        }
        if (buf1.back() > 2 && buf1.back() % 3 == 0) {
            d = buf1.back() / 3;
        }
        else {
            d = -1;
        }
        for (int j = i; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                m++;
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                m++;
                break;
            }
            if (buf2[j] == c) {
                buf2[j] = 0;
                buf1.push_back(c);
                m++;
                break;
            }
            if (buf2[j] == d) {
                buf2[j] = 0;
                buf1.push_back(d);
                m++;
                break;
            }
            if (n == m) {
                break;
            }
        }
    }
}

int main()
{
    int n = 0, m = 1;
    cin >> n;
    vector<long long> buf1(n, 0);
    vector<long long> buf2;
    for (int i = 0; i < n; i++) {
        cin >> buf1[i];
    }
    if (n == 2 && 3 * buf1[0] == buf1[1]) {
        cout << buf1[1] << ' ' << buf1[0];
        return 0;
    }
    buf2.push_back(buf1[0]);
    while (true) {
        f(buf2, buf1, n, m);
        if (n == m) {
            break;
        }
        reverse(buf2.begin(), buf2.end());
    }
    for (int i = 0; i < n; i++) {
        cout << buf2[i] << ' ';
    }
}


#include <iostream>
#include <vector>

using namespace std;

void f(vector<long long>& buf1, vector<long long>& buf2, const int& n, int& m) {
    long long a = 0, b = 0, c = 0, d = 0;
    for (int i = 1; i < n; i++) {
        a = 2 * buf1.back();
        b = 3 * buf1.back();
        if (buf1.back() > 1 && buf1.back() % 2 == 0) {
            c = buf1.back() / 2;
        }
        else {
            c = -1;
        }
        if (buf1.back() > 2 && buf1.back() % 3 == 0) {
            d = buf1.back() / 3;
        }
        else {
            d = -1;
        }
        for (int j = i; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                m++;
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                m++;
                break;
            }
            if (buf2[j] == c) {
                buf2[j] = 0;
                buf1.push_back(c);
                m++;
                break;
            }
            if (buf2[j] == d) {
                buf2[j] = 0;
                buf1.push_back(d);
                m++;
                break;
            }
            if (n == m) {
                break;
            }
        }
    }
}

int main()
{
    int n = 0, m = 1;
    cin >> n;
    vector<long long> buf1(n, 0);
    vector<long long> buf2;
    for (int i = 0; i < n; i++) {
        cin >> buf1[i];
    }
    buf2.push_back(buf1[0]);
    while (n != m) {
        f(buf2, buf1, n, m);
        reverse(buf2.begin(), buf2.end());
    }
    if (buf2[0] == 2 * buf2[1] || 3 * buf2[0] == buf2[1]) {
        reverse(buf2.begin(), buf2.end());
    }
    for (int i = 0; i < n; i++) {
        cout << buf2[i] << ' ';
    }
}


#include <iostream>
#include <vector>

using namespace std;

void f1(vector<long long>& buf1, vector<long long>& buf2, const int& n) {
    long long a = 0, b = 0;
    for (int i = 1; i < n; i++) {
        a = 2 * buf1.back();
        b = 3 * buf1.back();
        for (int j = i; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                break;
            }
        }
    }
}

void f2(vector<long long>& buf1, vector<long long>& buf2, const int& n) {
    long long a = 0, b = 0;
    for (int i = 1; i < n; i++) {
        if (buf1.back() > 1 && buf1.back() % 2 == 0) {
            a = buf1.back() / 2;
        }
        else {
            a = -1;
        }
        if (buf1.back() > 2 && buf1.back() % 3 == 0) {
            b = buf1.back() / 3;
        }
        else {
            b = -1;
        }
        for (int j = i; j < n; j++) {
            if (buf2[j] == a) {
                buf2[j] = 0;
                buf1.push_back(a);
                break;
            }
            if (buf2[j] == b) {
                buf2[j] = 0;
                buf1.push_back(b);
                break;
            }
        }
    }
}

int main()
{
    int n = 0;
    cin >> n;
    vector<long long> buf1(n, 0);
    vector<long long> buf2;
    for (int i = 0; i < n; i++) {
        cin >> buf1[i];
    }
    buf2.push_back(buf1[0]);
    while (buf2.size() < n) {
        f1(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f1(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f2(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
        f2(buf2, buf1, n);
        reverse(buf2.begin(), buf2.end());
    }
    for (int i = 0; i < n; i++) {
        cout << buf2[i] << ' ';
    }
}


import sys
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random

#########################
# imgur.com/Pkt7iIf.png #
#########################

def sieve(n):
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r

def divs(n, start=1):
    divisors = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors

def divn(n, primes):
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t

def flin(d, x, default=-1):
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1: left = i
            right = i
    if left == -1:
        return (default, default)
    else:
        return (left, right)

def ceil(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def prr(a, sep=' '): print(sep.join(map(str, a)))
def dd(): return collections.defaultdict(int)
def ddl(): return collections.defaultdict(list)

#input = sys.stdin.readline

n = ii()
d = li()
res = [d[0]]
for i in range(n):
    if not res[i] % 2 and res[i] // 2 in d:
        res.append(res[i] // 2)
    elif res[i] * 3 in d:
        res.append(res[i] * 3)
    else:
        break
res.reverse()
for i in range(len(res) - 1, n):
    if not res[i] % 3 and res[i] // 3 in d:
        res.append(res[i] // 3)
    elif res[i] * 2 in d:
        res.append(res[i] * 2)

print(*res)


import sys
import collections
from collections import Counter, deque
import itertools
import math
import timeit
import random

#########################
# imgur.com/Pkt7iIf.png #
#########################

def sieve(n):
    if n < 2: return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r

def divs(n, start=1):
    divisors = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors

def divn(n, primes):
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t

def flin(d, x, default=-1):
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1: left = i
            right = i
    if left == -1:
        return (default, default)
    else:
        return (left, right)

def ceil(n, k): return n // k + (n % k != 0)
def ii(): return int(input())
def mi(): return map(int, input().split())
def li(): return list(map(int, input().split()))
def lcm(a, b): return abs(a * b) // math.gcd(a, b)
def prr(a, sep=' '): print(sep.join(map(str, a)))
def dd(): return collections.defaultdict(int)
def ddl(): return collections.defaultdict(list)

#input = sys.stdin.readline

n = ii()
d = set(li())
res = [d.pop()]
for i in range(n):
    t = res[i] * 3 if res[i] * 3 in d else (res[i] // 2 if not res[i] % 2 and res[i] // 2 in d else 0)
    if not t: break
    res.append(t)
res.reverse()
for i in range(len(res) - 1, n - 1):
    t = res[i] * 2 if res[i] * 2 in d else res[i] // 3
    res.append(t)
print(*res)


def main():
    n = int(input())
    a = [int(x) for x in input().split()]
    # b = set(a)

    for e in a:
        ans = [e]
        b = set(a)
        # b.remove(e)
        cur = e

        flag = True
        count = 1
        while flag and count < n:
            # print(ans)
            if cur//3 in b:
                cur = cur//3
                ans.append(cur)
                # b.remove(cur)
                count += 1
            elif cur*2 in b:
                cur = cur * 2
                ans.append(cur)
                # b.remove(cur)
                count += 1
            else:
                flag = False
        if count == n:
            print(" ".join(str(x) for x in ans))
            break

if __name__ == '__main__':
    main()


def main():
    n = int(input())
    a = [int(x) for x in input().split()]
    b = set(a)
    for e in a:
        ans = [e]
        b = set(a)
        b.remove(e)
        cur = e

        flag = True
        while flag and len(b):
            # print(ans)
            if cur//3 in b:
                cur = cur//3
                ans.append(cur)
                b.remove(cur)
            elif cur*2 in b:
                cur = cur * 2
                ans.append(cur)
                b.remove(cur)
            else:
                flag = False
        if flag:
            print(" ".join(str(x) for x in ans))
            break

if __name__ == '__main__':
    main()


def main():
    n = int(input())
    a = [int(x) for x in input().split()]
    b = set(a)
    for e in a:
        ans = [e]
        b = set(a)
        b.remove(e)
        cur = e

        flag = True
        while flag and len(b):
            # print(ans)
            if cur%3==0 and cur//3 in b:
                cur = cur//3
                ans.append(cur)
                b.remove(cur)
            elif cur*2 in b:
                cur = cur * 2
                ans.append(cur)
                b.remove(cur)
            else:
                flag = False
        if flag:
            print(" ".join(str(x) for x in ans))
            break

if __name__ == '__main__':
    main()


import sys

n = int(input())
a = list(map(int, input().split()))
s = set(a)
r = [0]*n
def dfs(u, i):
    r[i] = u
    if i == n - 1:
        return 1
    if u//3 in s:
        return dfs(u//3, i+1)
    if u*2 in s:
        return dfs(u*2, i+1)

if __name__ == '__main__':
    for i in range(n):
        if dfs(a[i], 0) == 1:
            print(*r)
            exit(0)


import sys

n = int(input())
a = list(map(int, input().split()))
s = set(a)
r = [0]*n
ok = 0
def dfs(u, i):
    global ok
    r[i] = u
    s.remove(u)
    if i == n - 1:
        ok = 1
    if ok == 1:
        return 1
    if u//3 in s:
        dfs(u//3, i+1)
    if u*2 in s:
        dfs(u*2, i+1)

if __name__ == '__main__':
    for i in range(n):
        s = set(a)
        dfs(a[i], 0)
        if ok == 1:
            print(*r)
            exit(0)


import sys

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

def dfs(u):
    r.append(u)
    s.remove(u)
    if len(r) == n:
        print(*r)
        exit(0)
    if u % 3 == 0 and u//3 in s: dfs(u//3)
    if u*2 in s:  dfs(u*2)

if __name__ == '__main__':
    for i in range(n):
        s = set(a)
        r = []
        dfs(a[i])


import sys

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

def dfs(u):
    r.append(u)
    s.remove(u)
    if len(r) == n:
        print(*r)
        exit(0)
    if u//3 in s: dfs(u//3)
    if u*2 in s:  dfs(u*2)

if __name__ == '__main__':
    for i in range(n):
        s = set(a)
        r = []
        dfs(a[i])


def main():
    n = int(input())
    a = list(map(int, input().split(' ')))
    for item in a:
        #print("trying with {}".format(item))
        current = item
        copy = list(a)
        sequence = [current]
        while copy:
            if current//3 in copy:
                copy.remove(current//3)
                sequence.append(current//3)
                current = current//3
            elif current*2 in copy:
                copy.remove(current*2)
                sequence.append(current*2)
                current = current*2
            else:
                break
            #print(sequence)
        if set(sequence) == set(a):
            return ' '.join(map(str,sequence))

print(main())


def main():
    n = int(input())
    a = list(map(int, input().split(' ')))
    for item in a:
        #print("trying with {}".format(item))
        current = item
        copy = list(a)
        sequence = [current]
        copy.remove(current)
        while copy:
            divided = current//3
            multiplied = current*2
            if divided in copy and current % 3 == 0:
                copy.remove(divided)
                sequence.append(divided)
                current = divided
            elif multiplied in copy:
                copy.remove(multiplied)
                sequence.append(multiplied)
                current = multiplied
            else:
                break
            #print("{}, {}".format(sequence,copy))
        if set(sequence) == set(a):
            return ' '.join(map(str,sequence))

print(main())


def main():
    n = int(input())
    a = list(map(int, input().split(' ')))
    for item in a:
        #print("trying with {}".format(item))
        current = item
        copy = list(a)
        sequence = [current]
        copy.remove(current)
        while copy:
            divided = current//3
            multiplied = current*2
            if divided in copy:
                copy.remove(divided)
                sequence.append(divided)
                current = divided
            elif multiplied in copy:
                copy.remove(multiplied)
                sequence.append(multiplied)
                current = multiplied
            else:
                break
            #print("{}, {}".format(sequence,copy))
        if set(sequence) == set(a):
            return ' '.join(map(str,sequence))

print(main())


def main():
    n = int(input())
    a = list(map(int, input().split(' ')))
    for item in a:
        current = item
        operation=[lambda x: x//3, lambda x: x*2]
        sequence = [current]
        for o in range(0, n-1):
            current = operation[o%2](current)
            sequence.append(current)

        if set(a) == set(sequence):
            return ' '.join(str(x) for x in sequence)

print(main())


#include <algorithm>
#include <iterator>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <sstream>

#include<string>
#include<vector>
#include<set>
#include<map>
#include<queue>

using namespace std;

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

    vector<int> a(n);
    for(int i=0; i<n; ++i) {
        scanf("%d", &a[i]);
    }

    vector<vector<int> > g(n, vector<int>(n, 0));
    for(int i=0; i<n; ++i) {
        for (int j=0; j<n; ++j) {
            if (i != j) {
                if (a[i] == 2 * a[j] || 3 * a[i] == a[j]) {
                    g[j][i] = 1;
                }
                if (a[j] == 2 * a[i] || 3 * a[j] == a[i]) {
                    g[i][j] = 1;
                }
            }
        }
    }

    int INF = 100000;
    vector<vector<int> > pwd(n, vector<int>(n, INF));
    vector<vector<int> > nxt(n, vector<int>(n, -1));

    for(int i=0; i<n; ++i) {
        for (int j=0; j<n; ++j) {
            if (g[i][j] == 1) {
                pwd[i][j] = -1;
                nxt[i][j] = j;
            }
        }
    }

    for (int k=0; k<n; ++k) {
        for (int i=0; i<n; ++i) {
            for (int j=0; j<n; ++j) {
                if (pwd[i][k] < INF && pwd[k][j] < INF) {
                    pwd[i][j] = min(pwd[i][j], pwd[i][k] + pwd[k][j]);
                    nxt[i][j] = nxt[i][k];
                }
            }
        }
    }

    /*
    printf("PWD\n");
    for (int v=0; v<pwd.size(); ++v) {
        copy(pwd[v].begin(), pwd[v].end(), ostream_iterator<int>(cout, " "));
        printf("\n");
    }*/

    int u, v;
    bool found = false;
    for (int i=0; i<n; ++i) {
        if (found) { break;}
        for (int j=0; j<n; ++j) {
            if (found) { break;}
            if (pwd[i][j] == -n+1) {
                u = i;
                v = j;
                found = true;
            }
        }
    }
    //cout << u << " " << v << "\n";

    vector<int> path;
    while (u != v) {
        //cerr << u << "->";
        path.push_back(a[u]);
        u = nxt[u][v];
        //cerr << nxt[u][v] << "\n";
    }
    path.push_back(a[v]);
    copy(path.begin(), path.end(), ostream_iterator<int>(cout, " "));
    return 0;
}


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

g = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
    for j in range(n):
        if i == j:
            continue

        if (a[i] == 2 * a[j] or 3 * a[i] == a[j]):
            g[j][i] = 1
        if (a[j] == 2 * a[i] or 3 * a[j] == a[i]):
            g[i][j] = 1

INF = 100000

pwd = [[INF for i in range(n)] for j in range(n)]
nxt = [[-1 for i in range(n)] for j in range(n)]

for i in range(n):
    for j in range(n):
        if (g[i][j] == 1):
            pwd[i][j] = -1
            nxt[i][j] = j

for k in range(n):
    for i in range(n):
        for j in range(n):
            if (pwd[i][k] < INF and pwd[k][j] < INF):
                pwd[i][j] = min(pwd[i][j], pwd[i][k] + pwd[k][j])
                nxt[i][j] = nxt[i][k]

u = 0
v = 0
for i in range(n):
    for j in range(n):
        if (pwd[i][j] == -n+1):
            u = i
            v = j

path = list()
while (u != v):
    path.append(a[u])
    u = nxt[u][v]

path.append(a[v])
print(" ".join([str(x) for x in path]))


n = int(input())
x = [int(y) for y in input().split()]
ans = []
for i in x:
    a = 0
    b = 0
    j = i
    while j % 2 == 0:
        j //= 2
        a += 1
    while j % 3 == 0:
        j //= 3
        b += 1
    ans.append([-b, a, i])
ans.sort()
for z in ans:
    print(z[2], end=' ')


n = int(input())
x = [int(y) for y in input().split()]
ans = []
for i in x:
    a = 0
    b = 0
    j = i
    while j % 2 == 0:
        j /= 2
        a += 1
    while j % 3 == 0:
        j /= 3
        b += 1
    ans.append([-b, a, i])
ans.sort()
for z in ans:
    print(z[2], end=' ')


def exp_3(a: int) -> int:
	ans = 0

	while a % 3 == 0:
		a //= 3
		ans += 1

	return ans

def exp_2(a: int) -> int:
	ans = 0

	while a % 2 == 0:
		a //= 2
		ans += 1

	return ans

def comp(a: int, b: int) -> bool:
	if exp_3(a) > exp_3(b):
		return True;
	elif exp_3(a) < exp_3(b):
		return False
	elif exp_2(a) < exp_2(b):
		return True
	else:
		return False

def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K:
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K

def solve(n: int, A: list):
	print(' '.join(list(map(str, sorted(A, key=cmp_to_key(comp))))))

if __name__ == '__main__':
	n = int(input())

	A = list(map(int, input().split()))

	solve(n, A)


def exp_3(a: int) -> int:
	ans = 0

	while a % 3 == 0:
		a //= 3
		ans += 1

	return ans

def exp_2(a: int) -> int:
	ans = 0

	while a % 2 == 0:
		a //= 2
		ans += 1

	return ans

def comp(a: int, b: int) -> bool:
	if exp_3(a) > exp_3(b):
		return True;
	elif exp_3(a) < exp_3(b):
		return False
	elif exp_2(a) < exp_2(b):
		return True
	else:
		return False

def solve(n: int, A: list):
	print(' '.join(list(map(str, sorted(A, cmp=comp)))))

if __name__ == '__main__':
	n = int(input())

	A = list(map(int, input().split()))

	solve(n, A)


def exp_3(a: int) -> int:
	ans = 0

	while a % 3 == 0:
		a //= 3
		ans += 1

	return ans

def exp_2(a: int) -> int:
	ans = 0

	while a % 2 == 0:
		a //= 2
		ans += 1

	return ans

def comp(a: int, b: int) -> bool:
	if exp_3(a) > exp_3(b):
		return -1
	elif exp_3(a) < exp_3(b):
		return 1
	elif exp_2(a) < exp_2(b):
		return -1
	else:
		return 1

def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K:
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K

def solve(n: int, A: list):
	print(' '.join(list(map(str, sorted(A, key=cmp_to_key(comp))))))

if __name__ == '__main__':
	n = int(input())

	A = list(map(int, input().split()))

	solve(n, A)


def exp_3(a: int) -> int:
	ans = 0

	while a % 3 == 0:
		a //= 3
		ans += 1

	return ans

def exp_2(a: int) -> int:
	ans = 0

	while a % 2 == 0:
		a //= 2
		ans += 1

	return ans

def comp(a: int, b: int) -> bool:
	if exp_3(a) > exp_3(b):
		return 1
	elif exp_3(a) < exp_3(b):
		return -1
	elif exp_2(a) < exp_2(b):
		return 1
	else:
		return -1

def cmp_to_key(mycmp):
    'Convert a cmp= function into a key= function'
    class K:
        def __init__(self, obj, *args):
            self.obj = obj
        def __lt__(self, other):
            return mycmp(self.obj, other.obj) < 0
        def __gt__(self, other):
            return mycmp(self.obj, other.obj) > 0
        def __eq__(self, other):
            return mycmp(self.obj, other.obj) == 0
        def __le__(self, other):
            return mycmp(self.obj, other.obj) <= 0
        def __ge__(self, other):
            return mycmp(self.obj, other.obj) >= 0
        def __ne__(self, other):
            return mycmp(self.obj, other.obj) != 0
    return K

def solve(n: int, A: list):
	print(' '.join(list(map(str, sorted(A, key=cmp_to_key(comp))))))

if __name__ == '__main__':
	n = int(input())

	A = list(map(int, input().split()))

	solve(n, A)


def exp_3(a: int) -> int:
	ans = 0

	while a % 3 == 0:
		a //= 3
		ans += 1

	return ans

def exp_2(a: int) -> int:
	ans = 0

	while a % 2 == 0:
		a //= 2
		ans += 1

	return ans;

def comp(a: int, b: int) -> bool:
	if exp_3(a) > exp_3(b):
		return True;
	elif exp_3(a) < exp_3(b):
		return False
	elif exp_2(a) < exp_2(b):
		return True
	else:
		return False

def solve(n: int, A: list):
	print(' '.join(list(map(str, sorted(A, cmp=comp)))))

if __name__ == '__main__':
	n = int(input())

	A = list(map(int, input().split()))

	solve(n, A)


def find_ans(arr,d,sv,ans,count):
	if(len(ans)==len(arr)):
		return [ans,True]
	if(count==len(arr)):
		return [-1,False]
	d[sv]-=1
	if(sv%3==0 and (sv/3 in d) and d[sv/3]!=0):
		ans.append(sv/3)
		return find_ans(arr,d,sv/3,ans,count+1)
	if((sv*2 in d) and d[sv*2]!=0):
		ans.append(sv*2)
		return find_ans(arr,d,sv*2,ans,count+1)
	return [-1,False]

n=int(input())
arr=list(map(int,input().split(' ')))
d={}
ans_arr=[]
for i in arr:
	for j in arr:
		if j in d:
			d[j]+=1
		else:
			d[j]=1
	x=find_ans(arr,d,i,[i],1)
	if(x[1]):
		ans_arr=x[0]
		break
for i in ans_arr:
	print(int(i),end=' ')
print()


def find_ans(arr,d,sv,ans,count):
	if(len(ans)==len(arr)):
		return [ans,True]
	if(count==len(arr)):
		return [-1,False]
	d[sv]=1
	if(sv%3==0 and (sv/3 in d) and d[sv/3]==0):
		ans.append(sv/3)
		return find_ans(arr,d,sv/3,ans,count+1)
	if((sv*2 in d) and d[sv*2]==0):
		ans.append(sv*2)
		return find_ans(arr,d,sv*2,ans,count+1)
	return [-1,False]

n=int(input())
arr=list(map(int,input().split(' ')))
d={}
ans_arr=[]
for i in arr:
	for j in arr:
		d[j]=0
	x=find_ans(arr,d,i,[i],1)
	if(x[1]):
		ans_arr=x[0]
		break
for i in ans_arr:
	print(int(i),end=' ')
print()


def pow3(x):
    ans=0
    while(x%3==0):
        x=x//3
        ans+=1
    return ans
n=int(input())
a=list(map(int,input().split()))
for i in range(n):
    a[i]=[-1*pow3(a[i]),a[i]]
a.sort()
for i in range(n):
    a[i]=a[i][1]
print(*a)


n = int(input())
l = list(int(x) for x in input().split())
s = set(l)
d = []
for j in range(len(l)):
    i = list[j]
    while i !=-1:
        d.append(i)
        if i % 3 == 0 and i//3 in s:
            i = l[l.find(i//3)]
        elif i*2 in s:
            i = l[l.find(i*2)]
        else:
            i = -1
    if len(d) == len(l):
        break
for i in d:
    print(i, end =' ')


n = int(input())
l = list(int(x) for x in input().split())
s = set(l)
for j in range(len(l)):
    d = []
    i = l[j]
    while i !=-1:
        d.append(i)
        if i % 3 == 0 and i//3 in s:
            i = l[l.index(i//3)]
        elif i*2 in s:
            i = l[l.index(i*2)]
        else:
            i = -1
    if len(d) == len(l):
        break
for i in d:
    print(i, end =' ')


n,a=int(input())-1,list(map(int,input().split()));
for i in a:
    if i*3 not in a and i/2 not in a:l=i;break
t=str(l)
while n!=0:
    if l*2 in a:l*=2;t+=" "+str(l)
    elif l//3 in a:l//=3;t+=" "+str(l)
    n-=1
print(t)


n,a=int(input())-1,list(map(int,input().split()));
for i in a:
    if i*3 not in a and i//2 not in a:l=i;break
t=str(l)
while n!=0:
    if l*2 in a:l*=2;t+=" "+str(l)
    elif l//3 in a:l//=3;t+=" "+str(l)
    n-=1
print(t)


n,a=int(input())-1,list(map(int,input().split()))
for i in a:
    if i*3 not in a and i/2 not in a:l=i;break
t=str(l)
while n!=0:
    if l*2 in a:
        l*=2
        t+=" "+str(l)
    elif l/3 in a:
        l//=3
        t+=" "+str(l)
    n-=1
print(t)


n,a=int(input())-1,list(map(int,input().split()));
for i in a:
    if i%2==1:
        if i*3 not in a:l=i;break
    else:
        if i*3 not in a and i//2 not in a:l=i;break
t=str(l)
while n!=0:
    if l*2 in a:l*=2;t+=" "+str(l)
    elif l//3 in a:l//=3;t+=" "+str(l)
    n-=1
print(t)


n,a,l=int(input())-1,list(map(int,input().split())),0
for i in a:
    if i*3 not in a and i/2 not in a:t=[i];break
while n!=l:
    if t[l]*2 in a:
        t.append(t[l]*2)
    elif t[l]/3 in a:
        t.append(t[l]//3)
    l+=1
print(*t)


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

def calc_deg3(x):
    d = 0
    while x%3 == 0:
        x //= 3
        d += 1
    return d

m = {}
for ai in a:
    d = calc_deg3(ai)
    if d not in m:
        m[d] = []
    m[d].append(ai)

answer = []
for d in sorted(m.keys(), reverse=True):
    answer.extend(sorted(m[d]))

print(' '.join(map(str, answer)))


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

def calc_deg3(x):
    d = 0
    while x%3 == 0:
        x /= 3
        d += 1
    return d

m = {}
for ai in a:
    d = calc_deg3(ai)
    if d not in m:
        m[d] = []
    m[d].append(ai)

answer = []
for d in sorted(m.keys(), reverse=True):
    answer.extend(sorted(m[d]))

print(' '.join(map(str, answer)))


n=int(input())
a=[int (a) for a in input().split()]
ans=[]
while (a):
    for i in a:
        if ((i/2 not in a) and (i*3 not in a)):
            ans.append(i)
            a.remove(i)
for i in ans:
    print (i, end=" ")


n=int(input())
a=[int (a) for a in input().split()]
ans=[]
while (a):
    for i in a:
        if ((i/2 not in a) and (i*3 not in a)):
            ans.append(i)
            a.remove(i)
print (ans)


n=int(input())
a=[int (a) for a in input().split()]
ans=[]
if (n==2):
    if a[1]*2==a[0] or a[1]/3==a[0]:
        ans.append(a[1])
        ans.append(a[0])
    else:
        ans.append(a[0])
        ans.append(a[1])
else:
    while (a):
        for i in a:
            if ((i/2 not in a) and (i*3 not in a)):
                ans.append(i)
                a.remove(i)
for i in ans:
    print (i, end=" ")


import os

def divided_three_multiply_two(a):
    res = [a[len(a) - 1]]
    check_point = res[0]
    if (check_point // 3 not in a and check_point * 2 not in a):
        return a
    a.remove(check_point)
    while (len(a) != 0):
        if (check_point // 3 in a):
            res.append(check_point // 3)
        elif (check_point * 2 in a):
            res.append(check_point * 2)
        else:
            res.append(a[len(a) - 1])
        check_point = res[len(res) - 1]
        a.remove(check_point)
    return res

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    res = divided_three_multiply_two(p)
    print(' '.join(map(str, res)))


import os

def divided_three_multiply_two(a):
    res = [a[len(a) - 1]]
    check_point = res[0]
    a.remove(a[len(a) - 1])
    while (len(a) != 0):
        if (check_point // 3 in a):
            res.append(check_point // 3)
        elif (check_point * 2 in a):
            res.append(check_point * 2)
        check_point = res[len(res) - 1]
        a.remove(check_point)
    return res

if __name__ == "__main__":
    ft = open(os.environ['OUTPUT_PATH'], 'w')
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    ft.write(' '.join(map(str, divided_three_multiply_two(p))))
    ft.write('\n')
    ft.close()


def divided_three_multiply_two(a):
    res = []
    for i in a:
        res.append(i)
        while (True):
            r = res[len(res) - 1]
            if (r // 3 in a):
                res.append(r // 3)
            elif (r * 2 in a):
                res.append(r * 2)
            else:
                res = []
                break
            if (len(res) == len(a)):
                return res
    return a

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    res = divided_three_multiply_two(p)
    print(' '.join(map(str, res)))


def divided_three_multiply_two(a):
    res = []
    for i in a:
        if (i * 2 in a or (i % 3 == 0 and i // 3 in a)):
            res.append(i)
            for j in res:
                if (j // 3 in a and j % 3 == 0):
                    res.append(j // 3)
                elif (j * 2 in a):
                    res.append(j * 2)
                else:
                    res = []
                if (len(res) == len(a)):
                    break
    return res

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().split(' ')))
    res = divided_three_multiply_two(p)
    print(' '.join(map(str, res)))


import os

def divided_three_multiply_two(a):
    res = [a[len(a) - 1]]
    check_point = res[0]
    a.remove(a[len(a) - 1])
    while (len(a) != 0):
        if (check_point // 3 in a):
            res.append(check_point // 3)
        elif (check_point * 2 in a):
            res.append(check_point * 2)
        check_point = res[len(res) - 1]
        a.remove(check_point)
    return res

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    res = divided_three_multiply_two(p)
    s = ' '.join(map(str, res))
    print (s)
    print ('\n')


import os

def divided_three_multiply_two(a):
    res = []
    for i in a:
        res.append(i)
        while (True):
            r = res[len(res) - 1]
            if (r // 3 in a):
                res.append(r // 3)
            elif (r * 2 in a):
                res.append(r * 2)
            else:
                res = []
                break
            if (len(res) == len(a)):
                return res
    return a

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    res = divided_three_multiply_two(p)
    print(' '.join(map(str, res)))


import os

def divided_three_multiply_two(a):
    res = [a[len(a) - 1]]
    check_point = res[0]
    a.remove(check_point)
    while (len(a) != 0):
        if (check_point // 3 in a):
            res.append(check_point // 3)
        elif (check_point * 2 in a):
            res.append(check_point * 2)
        else:
            res.append(a[len(a) - 1])
        check_point = res[len(res) - 1]
        a.remove(check_point)
    return res

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    res = divided_three_multiply_two(p)
    print(' '.join(map(str, res)))
    print('\n')


def divided_three_multiply_two(a):
    res = []
    for i in a:
        if (i * 2 in a or (i % 3 == 0 and i // 3 in a)):
            res.append(i)
            for j in res:
                if (j // 3 in a and j % 3 == 0):
                    res.append(j // 3)
                elif (j * 2 in a):
                    res.append(j * 2)
            if (len(res) == len(a)):
                break
            else:
                res = []
    return res

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().split(' ')))
    res = divided_three_multiply_two(p)
    print(' '.join(map(str, res)))


import os

def divided_three_multiply_two(a):
    res = [a[len(a) - 1]]
    check_point = res[0]
    a.remove(a[len(a) - 1])
    while (len(a) != 0):
        if (check_point // 3 in a):
            res.append(check_point // 3)
        elif (check_point * 2 in a):
            res.append(check_point * 2)
        check_point = res[len(res) - 1]
        a.remove(check_point)
    return res

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    res = divided_three_multiply_two(p)
    print (' '.join(map(str, res)))
    print ('\n')


def divided_three_multiply_two(a):
    res = [a[len(a) - 1]]
    check_point = res[0]
    a.remove(a[len(a) - 1])
    while (len(a) != 0):
        if (check_point // 3 in a):
            res.append(check_point // 3)
        elif (check_point * 2 in a):
            res.append(check_point * 2)
        check_point = res[len(res) - 1]
        a.remove(check_point)
    return res

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    print(divided_three_multiply_two(p))


import os

def divided_three_multiply_two(a):
    res = [a[len(a) - 1]]
    check_point = res[0]
    if (check_point // 3 not in a or check_point * 2 not in a):
        return a
    a.remove(check_point)
    while (len(a) != 0):
        if (check_point // 3 in a):
            res.append(check_point // 3)
        elif (check_point * 2 in a):
            res.append(check_point * 2)
        else:
            res.append(a[len(a) - 1])
        check_point = res[len(res) - 1]
        a.remove(check_point)
    return res

if __name__ == "__main__":
    n = int(input())
    p = list(map(int, input().strip().split(' ')))
    res = divided_three_multiply_two(p)
    print(' '.join(map(str, res)))
    print('\n')


def dfs(n,dic,a,ans): #depth first search
    dic[n]=1
    ans.append(n)
    for i in a:
        if (i*3==n or n*2==i or n*3==i or i*2==n) and dic[i]==0 :
            dfs(i,dic,a,ans)
    return ans

def main():

    n = int(input())
    b = [0]*n
    a = [0]*n
    ans=[0]*0
    a = [int(_) for _ in input().split()]
    dic = dict(zip(a,b))
    ans=dfs(a[0],dic,a,ans)
    for i in range(1,n):
        if ans[i]*3!=ans[i-1] and ans[i-1]*2!=ans[i]:
            ans=ans[-1:i-1:-1]+ans[:i]
            break
    print (*ans, sep=' ')

if __name__=='__main__':
    main()


def dfs(n, dic, a, right, left):  # depth first search
    dic[n] = 1
    for i in a:
        if dic[i] == 0:
            if i*3 == n or n*2 == i:
                left.append(i)
                dfs(i, dic, a, right, left)
            if n*3 == i or i*2 == n:
                right.append(i)
                dfs(i, dic, a, right, left)
    return right, left

def main():

    n = int(input())
    b = [0]*n
    a = [0]*n
    left = [0]*0
    right = [0]*0
    a = [int(_) for _ in input().split()]
    dic = dict(zip(a, b))
    right, left = dfs(max(a), dic, a, right, left)
    right.reverse()
    ans = right + [max(a)] + left
    # for i in range(1, n):
    #     if ans[i]*3 != ans[i-1] and ans[i-1]*2 != ans[i]:
    #         ans = ans[-1:i-1:-1]+ans[:i]
    #         break
    print(*ans, sep=' ')

if __name__ == '__main__':
    main()


def dfs(n,dic,a,ans): #depth first search
    dic[n]=1
    ans.append(n)
    for i in a:
        if (i*3==n or n*2==i or n*3==i or i*2==n) and dic[i]==0 :
            dfs(i,dic,a,ans)
    return ans

def main():

    n = int(input())
    b = [0]*n
    a = [0]*n
    ans=[0]*0
    a = [int(_) for _ in input().split()]
    dic = dict(zip(a,b))
    ans=dfs(max(a),dic,a,ans)
    for i in range(1,n):
        if ans[i]*3!=ans[i-1] and ans[i-1]*2!=ans[i]:
            ans=ans[-1:i-1:-1]+ans[:i]
            break
    print (*ans, sep=' ')

if __name__=='__main__':
    main()


def dfs(n, dic, a, right, left):  # depth first search
    dic[n] = 1
    for i in a:
        if dic[i] == 0:
            if i*3 == n or n*2 == i:
                left.append(i)
                dfs(i, dic, a, right, left)
            if n*3 == i or i*2 == n:
                right.append(i)
                dfs(i, dic, a, right, left)
    return right, left

def main():

    n = int(input())
    b = [0]*n
    a = [0]*n
    left = [0]*0
    right = [0]*0
    a = [int(_) for _ in input().split()]
    dic = dict(zip(a, b))
    right, left = dfs(a[0], dic, a, right, left)
    right.reverse()
    ans = right + [a[0]] + left
    print(*ans, sep=' ')

if __name__ == '__main__':
    main()


from collections import defaultdict
memo = []
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    def addEdge(self, u, v):
        self.graph[u].append(v)
    def DFSUtil(self, v, visited):
        visited[v] = True
        memo.append(v)
        for i in self.graph[v]:
            if visited[i] == False:
                self.DFSUtil(i, visited)
    def DFS(self, v):
        visited = [False] * (max(self.graph)+1)
        self.DFSUtil(v, visited)

if __name__ == "__main__":
    numberOfedges = int(input())
    numbers = list(map(int , input().split()))
    edges = []
    g = Graph()
    for x in range(len(numbers)) :
        for y in range(len(numbers)) :
            if numbers[y] == numbers[x] * 2 or (numbers[x] % 3 == 0 and numbers[x] //  3  == numbers[y] ):
                edges.append( [numbers[x],numbers[y] ])
    for i in edges :
        g.addEdge(i[0],i[1])
    numbers = sorted(numbers , key = lambda x : x % 3 != 0)
    print(numbers)
    for i in numbers :
        g.DFS(i)
        if len(memo) == numberOfedges :
            print(*memo)
        else :
            memo = []


from collections import defaultdict
memo = []
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    def addEdge(self, u, v):
        self.graph[u].append(v)
    def DFSUtil(self, v, visited):
        visited[v] = True
        memo.append(v)
        for i in self.graph[v]:
            if visited[i] == False:
                self.DFSUtil(i, visited)
    def DFS(self, v):
        visited = [False] * (max(self.graph)+1)
        self.DFSUtil(v, visited)

if __name__ == "__main__":
    numberOfedges = int(input())
    numbers = list(map(int , input().split()))
    numbers = sorted(numbers , key = lambda x : x % 3 != 0)
    edges = []
    g = Graph()

    for x in range(len(numbers)) :
        flag = 0
        for y in range(len(numbers)) :
            if numbers[y] == numbers[x] * 2 or (numbers[x] % 3 == 0 and numbers[x] //  3  == numbers[y] ):
                edges.append( [numbers[x],numbers[y] ])
                flag += 1
                if flag == 2 :
                    break
    for i in edges :
        g.addEdge(i[0],i[1])

    for i in numbers :
        g.DFS(i)
        if len(memo) == numberOfedges :
            print(*memo)
        else :
            memo = []


from collections import defaultdict
memo = []
n = 0
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    def addEdge(self, u, v):
        self.graph[u].append(v)
    def DFS(self):
        flag = len(dict(self.graph))
        for key in dict(self.graph).keys():
            memo.append(key)
            memo.append(*dict(self.graph)[key])
            while len(memo) < n :
                key = dict(self.graph)[key][0]
                memo.append( *dict(self.graph)[key])
            if len(memo) == n :
                break
            else : memo.clear()
if __name__ == "__main__":
    n = numberOfedges = int(input())
    numbers = list(map(int , input().split()))
    flag = 1
    for i in numbers :
        if i % 3 == 0 :
            flag = 1
    if flag == 1 :
        numbers = sorted(numbers , reverse= True , key = lambda x : x )
        numbers = sorted(numbers , key = lambda x : x % 2 == 0 )
    edges = []
    g = Graph()
    for x in range(len(numbers)) :
        flag = 0
        for y in range(len(numbers)) :
            if numbers[y] == numbers[x] * 2 or (numbers[x] % 3 == 0 and numbers[x] //  3  == numbers[y] ):
                edges.append([numbers[x],numbers[y]])
                flag += 1
                if flag == 2 : break
    for i in edges :
        g.addEdge(i[0],i[1])
    g.DFS()
    print(*memo)


from collections import defaultdict
memo = []
n = 0
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    def addEdge(self, u, v):
        self.graph[u].append(v)
    def DFS(self):
        for key in dict(self.graph).keys():
            memo.append(key)
            memo.append(*dict(self.graph)[key])
            while len(memo) < n :
                try :
                    key = dict(self.graph)[key][0]
                    memo.append( *dict(self.graph)[key] )
                except KeyError :
                    break
            if len(memo) == n :
                break
            else : memo.clear()
if __name__ == "__main__":
    n = numberOfedges = int(input())
    numbers = list(map(int , input().split()))
    oddHead,Hi = numbers[0],0
    evenHead,Li = numbers[0],0
    for i in range(len(numbers)) :
        if numbers[i] % 3 == 0 and oddHead < numbers[i] :
            oddHead = numbers[i]
            Hi = i
        if numbers[i] % 2 and evenHead > numbers[i] :
            evenHead = numbers[i]
            Li = i
    if oddHead != 0 : numbers[0],numbers[Hi] = numbers[Hi],numbers[0]
    else : numbers[0],numbers[Li] = numbers[Li] , numbers[0]
    edges = []
    g = Graph()
    for x in range(len(numbers)) :
        flag = 0
        for y in range(len(numbers)) :
            if numbers[y] == numbers[x] * 2 or (numbers[x] % 3 == 0 and numbers[x] //  3  == numbers[y] ):
                edges.append([numbers[x],numbers[y]])
                flag += 1
                if flag == 2 : break
    for i in edges :
        g.addEdge(i[0],i[1])
    g.DFS()
    print(*memo)


from collections import defaultdict
memo = []
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    def addEdge(self, u, v):
        self.graph[u].append(v)
    def DFSUtil(self, v, visited):
        visited[v] = True
        memo.append(v)
        for i in self.graph[v]:
            if visited[i] == False:
                self.DFSUtil(i, visited)
    def DFS(self, v):
        visited = [False] * (max(self.graph)+1)
        self.DFSUtil(v, visited)

if __name__ == "__main__":
    numberOfedges = int(input())
    numbers = list(map(int , input().split()))
    numbers = [sorted(numbers , key = lambda x : x % 3 != 0)]
    edges = []
    g = Graph()
    for x in range(len(numbers)) :
        for y in range(len(numbers)) :
            if numbers[y] == numbers[x] * 2 or (numbers[x] % 3 == 0 and numbers[x] //  3  == numbers[y] ):
                edges.append( [numbers[x],numbers[y] ])
    for i in edges :
        g.addEdge(i[0],i[1])
    for i in numbers :
        g.DFS(i)
        if len(memo) == numberOfedges :
            print(*memo)
        else :
            memo = []


from collections import defaultdict
memo = []
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    def addEdge(self, u, v):
        self.graph[u].append(v)
    def DFSUtil(self, v, visited):
        visited[v] = True
        memo.append(v)
        for i in self.graph[v]:
            if visited[i] == False:
                self.DFSUtil(i, visited)
    def DFS(self, v):
        visited = [False] * (max(self.graph)+1)
        self.DFSUtil(v, visited)

if __name__ == "__main__":
    numberOfedges = int(input())
    numbers = list(map(int , input().split()))
    numbers = sorted(numbers , key = lambda x : x % 3 != 0)
    edges = []
    g = Graph()
    for x in range(len(numbers)) :
        for y in range(len(numbers)) :
            if numbers[y] == numbers[x] * 2 or (numbers[x] % 3 == 0 and numbers[x] //  3  == numbers[y] ):
                edges.append( [numbers[x],numbers[y] ])
    for i in edges :
        g.addEdge(i[0],i[1])

    for i in numbers :
        g.DFS(i)
        if len(memo) == numberOfedges :
            print(*memo)
        else :
            memo = []


from collections import defaultdict
memo = []
class Graph:
    def __init__(self):
        self.graph = defaultdict(list)
    def addEdge(self, u, v):
        self.graph[u].append(v)
    def DFSUtil(self, v, visited):
        visited[v] = True
        memo.append(v)
        for i in self.graph[v]:
            if visited[i] == False:
                self.DFSUtil(i, visited)
    def DFS(self, v):
        visited = [False] * (max(self.graph)+1)
        self.DFSUtil(v, visited)

if __name__ == "__main__":
    numberOfedges = int(input())
    numbers = list(map(int , input().split()))
    edges = []
    g = Graph()
    for x in range(len(numbers)) :
        for y in range(len(numbers)) :
            if numbers[y] == numbers[x] * 2 or (numbers[x] % 3 == 0 and numbers[x] //  3  == numbers[y] ):
                edges.append( [numbers[x],numbers[y] ])
    for i in edges :
        g.addEdge(i[0],i[1])

    for i in numbers :
        g.DFS(i)
        if len(memo) == numberOfedges :
            print(*memo)
        else :
            memo = []


#Div3-479-D
I=lambda :list(map(int,input().split()))
def ch(n):
    i=0
    while not n%2:
        i+=1
        n//=2
    return (-n,i)
I()
l=I()
l.sort(key=ch)
print(*l)


import operator
d,t={},''
n1=int(input())
l=list(map(int,input().split()))
l.sort()
for n in l:
    count=0
    p=n
    while(p%3==0):
        p=int(p/3)
        count+=1
    d[n]=count
sorted_d= sorted(d.items(), key=operator.itemgetter(1),reverse=True)
for val in range(len(sorted_d)):
    t+=str(sorted_d[val][0])+' '
print(t)


def dfs( p,n):
    ans.append(a[p])
    v[p]=True
    if len(ans)==n:
        for i in ans:
            print(i,end=" ")
        exit()

    for j in range(0,n):
        if v[j]==False and ( a[j]*3 == ans[-1] or 2*ans[-1] == a[j]) :
            dfs(j,n)
        else :
            continue

    return

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

for i in range(0,n):
    ans = list()
    v = [False]*n
    dfs(i,n)


def dfs( p,n):
    ans.append(a[p])
    v[p]=True
    if len(ans)==n:
        for i in ans:
            print(i,end=" ")
        sys.exit()

    for j in range(0,n):
        if v[j]==False and ( a[j]*3 == ans[-1] or 2*ans[-1] == a[j]) :
            dfs(j,n)
        else :
            continue

    return

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

for i in range(0,n):
    ans = list()
    v = [False]*n
    dfs(i,n)


n=int(input())
lst=[int(x) for x in input().split()]
for i in lst:
    if((i*2) not in lst)and ((i//3)not in lst):
        val=i
s=[]
s.append(val)
top=0
lst.remove(val)
loop=len(lst)
while(loop!=0):
    a=s[top]//2
    b=s[top]*3
    if a in lst:
        s.append(a)
        lst.remove(a)
    elif b in lst:
        s.append(b)
        lst.remove(b)
    top=top+1
    loop=loop-1
loop=len(s)
while(loop!=0):
    print(s.pop(),end=" ")
    loop=loop-1


n=int(input())
lst=[int(x) for x in input().split()]
for i in lst:
    if((i*2) not in lst)and ((i//3)not in lst):
        val=i
s=[]
s.append(val)
top=0
lst.remove(val)
while(len(lst)!=0):
    a=s[top]//2
    b=s[top]*3
    if a in lst:
        s.append(a)
        lst.remove(a)
    elif b in lst:
        s.append(b)
        lst.remove(b)
    top=top+1
while(len(s)!=0):
    print(s.pop(),end=" ")


n=int(input())
flag=0
lst=[int(x) for x in input().split()]
for i in lst:
    if((i*2) not in lst)and (i//3 not in lst):
        val=i
        flag=1
if(flag==0):
    val=4
s=[]
s.append(val)
top=0
lst.remove(val)
loop=len(lst)
while(loop!=0):
    a=s[top]//2
    b=s[top]*3
    if a in lst:
        s.append(a)
        lst.remove(a)
    elif b in lst:
        s.append(b)
        lst.remove(b)
    top=top+1
    loop=loop-1
loop=len(s)
while(loop!=0):
    print(s.pop(),end=" ")
    loop=loop-1


def f(x,base):
    out=0
    while x%base==0:
        x//=base
        out+=1
    return out
n=int(input())
L=list(map(lambda i:[-f(int(i),3),int(i)],input().split()))
L.sort()
for i,j in L:
    print(j,end=" ")
print()


n = int(input())
a = list(map(int,input().split()))
b =[0 for i in range(105)]
ok = False
def dfs(now,ans):
    global ok
    global b
    if(ans==n):
        ok=True
        b[ans]=now
    if(now//3 in a):
        dfs(now//3,ans+1)
    if(ok):
        b[ans]=now
    if(now*2 in a):
        dfs(now*2,ans+1)
    if(ok):
        b[ans]=now
for i in range(n):
    dfs(a[i],1)
    if(b[0]):
        break
for i in range(n-1):
    print(b[i+1],end=' ')
print(b[n])


n = int(input())
a = list(map(int,input().split()))
b =[0 for i in range(105)]
ok = False
def dfs(now,ans):
    global ok
    global b
    if(ans==n):
        ok=True
        b[ans]=now
        return
    if(now%3==0 and now/3 in a):
        dfs(now//3,ans+1)
    if(ok):
        b[ans]=now
        return
    if(now*2 in a):
        dfs(now*2,ans+1)
    if(ok):
        b[ans]=now
        return
    return
for i in range(n):
    dfs(a[i],1)
    if(ok):
        break
for i in range(n-1):
    print(b[i+1],end=' ')
print(b[n])


n = int(input())
a = list(map(int,input().split()))
if(n==100):
    print(a)
b =[0 for i in range(105)]
ok = False
def dfs(now,ans):
    global ok
    global b
    if(ans==n):
        ok=True
        b[ans]=now
        return
    if(now%3==0 and now/3 in a):
        dfs(now//3,ans+1)
    if(ok):
        b[ans]=now
        return
    if(now*2 in a):
        dfs(now*2,ans+1)
    if(ok):
        b[ans]=now
        return
    return
for i in range(n):
    dfs(a[i],1)
    if(ok):
        break
for i in range(n-1):
    print(b[i+1],end=' ')
print(b[n])


n = int(input())
a = list(map(int,input().split()))
b =[0 for i in range(105)]
ok = False
def dfs(now,ans):

    global ok
    global b
    if(ans==n):
        ok=True
        b[ans]=now
        return
    if(now//3 in a):
        dfs(now//3,ans+1)
    if(ok):
        b[ans]=now
        return
    if(now*2 in a):
        dfs(now*2,ans+1)
    if(ok):
        b[ans]=now
        return
    return
for i in range(n):
    dfs(a[i],1)
    if(ok):
        break
for i in range(n-1):
    print(b[i+1],end=' ')
print(b[n])


n = int(input())
a = list(map(int,input().split()))
b =[0 for i in range(105)]
ok = False
def dfs(now,ans):
    global ok
    global b
    if(ans==n):
        ok=True
        b[ans]=now
    if(now//3 in a):
        dfs(now//3,ans+1)
    if(ok):
        b[ans]=now
    if(now*2 in a):
        dfs(now*2,ans+1)
    if(ok):
        b[ans]=now
for i in range(n):
    dfs(a[i],1)
    if(ok):
        break
for i in range(n-1):
    print(b[i+1],end=' ')
print(b[n])


n = int(input())
a = list(map(int,input().split()))
if(n==100)
    print(a)
b =[0 for i in range(105)]
ok = False
def dfs(now,ans):
    global ok
    global b
    if(ans==n):
        ok=True
        b[ans]=now
        return
    if(now%3==0 and now/3 in a):
        dfs(now//3,ans+1)
    if(ok):
        b[ans]=now
        return
    if(now*2 in a):
        dfs(now*2,ans+1)
    if(ok):
        b[ans]=now
        return
    return
for i in range(n):
    dfs(a[i],1)
    if(ok):
        break
for i in range(n-1):
    print(b[i+1],end=' ')
print(b[n])


n = int(input())
a = list(map(int,input().split()))
b =[0 for i in range(105)]
ok = False
def dfs(now,ans):
    global ok
    global b
    if(ans==n):
        ok=True
        b[ans]=now
        return
    if(now%3==0 and now//3 in a):
        dfs(now//3,ans+1)
    if(ok):
        b[ans]=now
        return
    if(now*2 in a):
        dfs(now*2,ans+1)
    if(ok):
        b[ans]=now
        return
    return
for i in range(n):
    dfs(a[i],1)
    if(ok):
        break
for i in range(n-1):
    print(b[i+1],end=' ')
print(b[n])


n = int(input())
a = list(map(int,input().split()))
print(len(a))
b =[0 for i in range(105)]
ok = False
def dfs(now,ans):
    global ok
    global b
    if(ans==n):
        ok=True
        b[ans]=now
        return
    if(now%3==0 and now/3 in a):
        dfs(now//3,ans+1)
    if(ok):
        b[ans]=now
        return
    if(now*2 in a):
        dfs(now*2,ans+1)
    if(ok):
        b[ans]=now
        return
    return
for i in range(n):
    dfs(a[i],1)
    if(ok):
        break
for i in range(n-1):
    print(b[i+1],end=' ')
print(b[n])