#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn=1e6+5;
struct node{
	ll f,t,v;
}a[maxn];
ll fa[maxn];
ll getfa(ll v)
{
	if(fa[v]!=v) fa[v]=getfa(fa[v]);
	return fa[v];
}
bool cmp(node a,node b)
{
	return a.v<b.v;
}
int main()
{
	ll n,m;
	scanf("%lld%lld",&n,&m);
	for(ll i=1;i<=m;i++)
	{
		scanf("%lld%lld%lld",&a[i].f,&a[i].t,&a[i].v);
	}
	node temp=a[1];
	sort(a+2,a+1+m,cmp);
//	for(int i=2;i<=n;i++) cout<<a[i].f<<" "<<a[i].t<<" "<<a[i].v<<endl;
	ll ans=0;
	ll tot=0;
	for(ll i=1;i<=n;i++) fa[i]=i;
	for(ll i=2;i<=m;i++)
	{
		ll x=getfa(a[i].f);
		ll y=getfa(a[i].t);
		if(x==y) continue;
		else ans+=a[i].v,tot++,fa[x]=y;;

	}
	//cout<<ans<<" "<<endl;
	if(tot<n-1) printf("1000000000\n");
	else
	{
		for(ll i=1;i<=n;i++) fa[i]=i;
		ll ans1=temp.v;
		fa[temp.f]=temp.t;
		for(ll i=2;i<=m;i++)
		{
			ll x=getfa(a[i].f);
			ll y=getfa(a[i].t);
			if(x==y) continue;
			else ans1+=a[i].v,fa[x]=y;;
		}
		//cout<<ans1<<" "<<endl;
		printf("%lld\n",temp.v+ans-ans1);
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll maxn=1e6+5;
struct node{
	ll f,t,v;
}a[maxn];
ll fa[maxn];
ll getfa(ll v)
{
	if(fa[v]!=v) fa[v]=getfa(fa[v]);
	return fa[v];
}
bool cmp(node a,node b)
{
	return a.v<b.v;
}
int main()
{
	ll n,m;
	scanf("%lld%lld",&n,&m);
	for(int i=1;i<=m;i++)
	{
		ll f,t,v;
		scanf("%lld%lld%lld",&a[i].f,&a[i].t,&a[i].v);
	}
	node temp=a[1];
	sort(a+2,a+1+m,cmp);
//	for(int i=2;i<=n;i++) cout<<a[i].f<<" "<<a[i].t<<" "<<a[i].v<<endl;
	ll ans=0;
	int tot=0;
	for(int i=1;i<=n;i++) fa[i]=i;
	for(int i=2;i<=m;i++)
	{
		ll x=getfa(a[i].f);
		ll y=getfa(a[i].t);
		if(x==y) continue;
		else ans+=a[i].v,tot++;
		fa[x]=y;
	}
	//cout<<ans<<" "<<endl;
	if(tot<n-1) printf("1000000000\n");
	else
	{
		for(int i=1;i<=n;i++) fa[i]=i;
		ll ans1=temp.v;
		fa[temp.f]=temp.t;
		for(int i=2;i<=m;i++)
		{
			ll x=getfa(a[i].f);
			ll y=getfa(a[i].t);
			if(x==y) continue;
			else ans1+=a[i].v;
			fa[x]=y;
		}
		//cout<<ans1<<" "<<endl;
		if(ans1>=ans) printf("%lld\n",temp.v+ans-ans1);
	}
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
const int Maxn= 1e6+10;
ll fa[Maxn],fa2[Maxn];
ll find(ll x){
	if(x == fa[x]) return x;
	else return fa[x] = find(fa[x]);
}
ll find2(ll x){
	if(x == fa2[x]) return x;
	else return fa2[x] = find(fa2[x]);
}
struct EE{
	ll x,y,z;
}node[Maxn],first,node2[Maxn];
bool cmp(EE a,EE b){
	return a.z < b.z;
}
int main(){
	ll n,m;
	while(~scanf("%lld%lld",&n,&m)){
		for(ll i=0;i<m;i++){
			scanf("%lld%lld%lld",&node[i].x,&node[i].y,&node[i].z);
			if(i!=0)node2[i] =node[i];
		}
		first = node[0];
		for(ll i=0;i<n;i++) fa[i]=i,fa2[i]=i;
		sort(node,node+m,cmp);
		ll tol=0;
		ll ans1 = 0;
		for(ll i=0;i<m;i++){
			ll u = find(node[i].x);
			ll v = find(node[i].y);
			if(u !=v){
				fa[u] = v;
				tol++;
				ans1 += node[i].z;
			}
			if(tol==n-1) break;
		}
		//cout<<"！！！！！！"<<tol<<endl;
		//if(tol!=n-1) puts("00");
		fa2[first.x] = first.y;

		sort(node2+1,node2+m,cmp);
	//	for(int i=1;i<m;i++) cout<<"&&  "<<node[i].x<<" "<<node[i].y<<" "<<node[i].z<<endl;
		tol=0;
	//	cout<<"((((("<<endl;
		ll ans2=first.z;
		for(ll i=1;i<m;i++){
			//cout<<node[i].x<<" "<<node[i].y<<endl;
			ll u = find2(node2[i].x);
			ll v = find2(node2[i].y);
			//cout<<" "<<u<<" "<<v<<endl;
			if(u !=v){
				fa[u] = v;
				tol++;
				ans2 += node2[i].z;
			}
		//	cout<<" (((((("<<endl;
			if(tol==n-2) break;
		}
		if(ans2 <= ans1) {
			printf("%lld\n",first.z);
		}
		else {
			printf("%lld\n",first.z-(ans2-ans1));
		}
	}
	return 0;

}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
const int Maxm= 1e6+10;
const int Maxn = 1e5+10;
ll fa[Maxn];
ll find(ll x){
	if(x == fa[x]) return x;
	else return fa[x] = find(fa[x]);
}
struct EE{
	ll x,y,z;
}node[Maxm],first;
bool cmp(EE a,EE b){
	return a.z < b.z;
}
int main(){
	ll n,m;
	while(~scanf("%lld%lld",&n,&m)){
		for(ll i=0;i<m;i++){
			scanf("%lld%lld%lld",&node[i].x,&node[i].y,&node[i].z);
		}
		first = node[0];
		for(ll i=0;i<n;i++) fa[i]=i;
		sort(node+1,node+m,cmp);
		ll tol=0;
		ll ans1 = 0;
		for(ll i=1;i<m;i++){
			ll u = find(node[i].x);
			ll v = find(node[i].y);
			if(u !=v){
				fa[u] = v;
				tol++;
				ans1 += node[i].z;
			}
			if(tol==n-1) break;
		}
		if(tol != n-1) {
			puts("1000000000");
			continue;
		}
		fa[first.x] = first.y;
		tol=0;
		for(ll i=0;i<n;i++) fa[i]=i;
		ll ans2=first.z;
		for(ll i=1;i<m;i++){
			ll u = find(node[i].x);
			ll v = find(node[i].y);
			if(u !=v){
				fa[u] = v;
				tol++;
				ans2 += node[i].z;
			}
		//	cout<<" (((((("<<endl;
			if(tol==n-2) break;
		}

		printf("%lld\n",first.z-(ans2-ans1));

	}
	return 0;

}


#include <bits/stdc++.h>
#define pii pair<int,int>
#define uu first
#define vv second
#define ll long long int
#define fastio 	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX = 1e6+6;
const ll INF = 1e18;

typedef tuple<ll , int , int > tp;

int n , m , par[MAX];
vector<tp>edgList , cpy;

int boss(int x) {
    if( par[x] == x) return x;
    return par[x] = boss(par[x]);
}

ll mst(int flg) {

    for(int i = 0 ; i<=n ; i++ )  par[i] = i;

    ll cnt = 0 ,ans = 0;

    if(flg) {
        ll w , u , v;
        tie(w , u , v) = edgList[0];
        ans = w;
        par[u] = v;
        cnt = 1;
    }

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

    for(auto x : edgList) {
        ll val , u , v;
        tie(val , u , v) = x;
        int parU = boss(u);
        int parV = boss(v);
        if( parU != parV ) {
            ans += val;
            par[parU] = parV;
            cnt++;
        }
        if( cnt == n-1 ) break;
    }
    return ans;
}

int main()
{
    fastio;
    cin>>n>>m;

    for(int i =0 ; i < m ; i++) {
        int u , v , w;
        cin>>u>>v>>w;
        edgList.push_back({w , u,v });
    }
    cpy = edgList;

    ll tgtcst = mst(0);

    // cout<<tgtcst<<'\n';

    ll lo = 0 , hi = INF , ret = INF;

    while(lo <=hi ) {
        ll mid = (lo+hi)/2;

        edgList = cpy;
        get<0>(edgList[0]) = mid;
        ll tmpcst = mst(1);

        // cout<<mid<<" "<<tmpcst<<'\n';
        if(tmpcst <= tgtcst) {
            ret = mid;
            lo = mid + 1;
        }
        else hi = mid - 1;
    }

    cout<<ret<<'\n';
    return 0;
}


#include <bits/stdc++.h>
#define pii pair<int,int>
#define uu first
#define vv second
#define ll long long int
#define fastio 	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX = 1e6+6;
const ll INF = 1e9;

typedef tuple<ll , int , int , int > tp;

int n , m , par[MAX];
vector<tp>edgList , cpy;

int boss(int x) {
    if( par[x] == x) return x;
    return par[x] = boss(par[x]);
}

int mst() {

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

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

    for(auto x : edgList) {
        ll val , id,  u , v;
        tie(val , id , u , v) = x;
        int parU = boss(u);
        int parV = boss(v);
        if( parU != parV ) {
            par[parU] = parV;
            if(id == 0) return 1;
        }
    }
    return  0;
}

int main()
{
    fastio;
    cin>>n>>m;
    for(int i =0 ; i < m ; i++) {
        int u , v , w;
        cin>>u>>v>>w;
        edgList.push_back({w , i , u,v });
    }
    cpy = edgList;

    ll lo = 0 , hi = INF , ret = -1;

    while(lo <=hi ) {
        ll mid = (lo+hi)/2;

        edgList = cpy;
        get<0>(edgList[0]) = mid;

        if(mst()) {
            ret = mid;
            lo = mid + 1;
        }
        else hi = mid - 1;
    }

    cout<<ret<<'\n';
    return 0;
}


#include <bits/stdc++.h>
#define pii pair<int,int>
#define uu first
#define vv second
#define ll long long int
#define fastio 	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX = 1e6+6;
const ll INF = 1e9;

typedef tuple<ll , int , int > tp;

int n , m , par[MAX];
vector<tp>edgList , cpy;

int boss(int x) {
    if( par[x] == x) return x;
    return par[x] = boss(par[x]);
}

ll mst(int flg) {

    for(int i = 0 ; i<=n ; i++ )  par[i] = i;

    ll cnt = 0 ,ans = 0;

    if(flg) {
        ll w , u , v;
        tie(w , u , v) = edgList[0];
        ans = w;
        par[u] = v;
        cnt = 1;
    }

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

    for(auto x : edgList) {
        ll val , u , v;
        tie(val , u , v) = x;
        int parU = boss(u);
        int parV = boss(v);
        if( parU != parV ) {
            ans += val;
            par[parU] = parV;
            cnt++;
        }
        if( cnt == n-1 ) break;
    }
    return ans;
}

int main()
{
    fastio;
    cin>>n>>m;
    if(m == n-1) {
        cout<<INF<<'\n';
        return 0;
    }

    for(int i =0 ; i < m ; i++) {
        int u , v , w;
        cin>>u>>v>>w;
        edgList.push_back({w , u,v });
    }
    cpy = edgList;

    ll tgtcst = mst(0);

    // cout<<tgtcst<<'\n';

    ll lo = 0 , hi = INF , ret = INF;

    while(lo <=hi ) {
        ll mid = (lo+hi)/2;

        edgList = cpy;
        get<0>(edgList[0]) = mid;
        ll tmpcst = mst(1);

        // cout<<mid<<" "<<tmpcst<<'\n';
        if(tmpcst <= tgtcst) {
            ret = mid;
            lo = mid + 1;
        }
        else hi = mid - 1;
    }

    cout<<ret<<'\n';
    return 0;
}


#include <bits/stdc++.h>
#define pii pair<int,int>
#define uu first
#define vv second
#define ll long long int
#define fastio 	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;

const int MAX = 1e6+6;
const ll INF = 1e9;

typedef tuple<ll , int , int > tp;

int n , m , par[MAX];
vector<tp>edgList , cpy;

int boss(int x) {
    if( par[x] == x) return x;
    return par[x] = boss(par[x]);
}

ll mst(int flg) {

    for(int i = 0 ; i<=n ; i++ )  par[i] = i;

    ll cnt = 0 ,ans = 0;

    if(flg) {
        ll w , u , v;
        tie(w , u , v) = edgList[0];
        ans = w;
        par[u] = v;
        cnt = 1;
    }

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

    for(auto x : edgList) {
        ll val , u , v;
        tie(val , u , v) = x;
        int parU = boss(u);
        int parV = boss(v);
        if( parU != parV ) {
            ans += val;
            par[parU] = parV;
            cnt++;
        }
        if( cnt == n-1 ) break;
    }
    return ans;
}

int main()
{
    fastio;
    cin>>n>>m;
    if(m == 1) {
        cout<<INF<<'\n';
        return 0;
    }

    for(int i =0 ; i < m ; i++) {
        int u , v , w;
        cin>>u>>v>>w;
        edgList.push_back({w , u,v });
    }
    cpy = edgList;

    ll tgtcst = mst(0);

    // cout<<tgtcst<<'\n';

    ll lo = 0 , hi = INF , ret = INF;

    while(lo <=hi ) {
        ll mid = (lo+hi)/2;

        edgList = cpy;
        get<0>(edgList[0]) = mid;
        ll tmpcst = mst(1);

        // cout<<mid<<" "<<tmpcst<<'\n';
        if(tmpcst <= tgtcst) {
            ret = mid;
            lo = mid + 1;
        }
        else hi = mid - 1;
    }

    cout<<ret<<'\n';
    return 0;
}


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

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>;

typedef vector<int> vi;
typedef vector<vi> vii;
typedef pair<int,int> pii;

#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define ll long long
#define ld long double
#define sz(a) int((a).size())
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define allr(c) (c).rbegin(),(c).rend()
#define newl '\n'

ll g[100005];

int main(){ sync;
    ll n,m; cin >> n >> m;
    vector<pair<ll,pair<ll,ll>>> v;
    for(int i=0;i<m;++i){
        ll x,y,w; cin >> x >> y >> w;
        if(i == 0){
            g[x] = 1;
            g[y] = 2;
        }else{
            v.pb({w,{x,y}});
        }
    }

    sort(all(v));
    for(auto u:v){
        ll x = g[u.s.f], y = g[u.s.s];
        if(x == 0 && y == 0){
            g[u.s.f] = 1;
            g[u.s.s] = 1;
        }else if(x == 0){
            g[u.s.f] = g[u.s.s];
        }else if(y == 0){
            g[u.s.s] = g[u.s.f];
        }else if(x != y){
            cout << u.f << newl;
            return 0;
        }
    }

    cout << 1e9 << newl;
    return 0;
}


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

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>;

typedef vector<int> vi;
typedef vector<vi> vii;
typedef pair<int,int> pii;

#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define ll long long
#define ld long double
#define sz(a) int((a).size())
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define allr(c) (c).rbegin(),(c).rend()
#define newl '\n'

vector<pair<ll,ll>> adj[100005];
bool vis[100005];
bool ok;

ll u,v;

void dfs(ll x, ll w){
    vis[x] = 1;
    if(x == u){
        ok = 1;
        return;
    }
    for(auto u:adj[x]){
        if(!vis[u.f] && u.s <= w){
            dfs(u.f,w);
        }
    }
    return;
}
int main(){ sync;
    ll n,m; cin >> n >> m;
    for(int i=0;i<m;++i){
        ll x,y,w; cin >> x >> y >> w;
        if(i == 0){
            u = x;
            v = y;
        }else{
            adj[x].pb({y,w});
            adj[y].pb({x,w});
        }
    }

    ll lo = -1, hi = 1e9;
    while(lo+1 != hi){
        for(int i=1;i<=n;++i) vis[i] = 0;
        ll mid = (lo+hi)/2LL;
        ok = 0;
        dfs(v,mid);

        if(ok){
            hi = mid;
        }else lo = mid;

    }

    cout << hi << newl;
    return 0;

}


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

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;

//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag,tree_order_statistics_node_update>;

typedef vector<int> vi;
typedef vector<vi> vii;
typedef pair<int,int> pii;

#define sync ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define ll long long
#define ld long double
#define sz(a) int((a).size())
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define allr(c) (c).rbegin(),(c).rend()
#define newl '\n'

vector<pair<ll,ll>> adj[100005];
bool vis[100005];
bool ok;

ll u,v;

void dfs(ll x, ll w){
    vis[x] = 1;
    if(x == u){
        ok = 1;
        return;
    }
    for(auto u:adj[x]){
        if(!vis[u.f] && u.s <= w){
            dfs(u.f,w);
        }
    }
    return;
}
int main(){ sync;
    ll n,m; cin >> n >> m;
    for(int i=0;i<m;++i){
        ll x,y,w; cin >> x >> y >> w;
        if(i == 0){
            u = x;
            v = y;
        }else{
            adj[x].pb({y,w});
            adj[y].pb({x,w});
        }
    }

    ll lo = 1, hi = 1e9;
    while(lo+1 != hi){
        for(int i=1;i<=n;++i) vis[i] = 0;
        ll mid = (lo+hi)/2LL;
        ok = 0;
        dfs(v,mid);

        if(ok){
            hi = mid;
        }else lo = mid;

    }

    cout << hi << newl;
    return 0;

}


#include <bits/stdc++.h>

using namespace std;

int* uf;
int components;

int find(int& x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

void join(int& a, int& b)
{
   int root_a = find(a);
   int root_b = find(b);

   uf[a] = root_b;
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    components = n;

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<tuple<int, int, int>> corridors;
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_tuple(e, a, b));
    }

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

    long long total_e = 0;
    for(auto& corridor : corridors)
    {
        int& a = get<1>(corridor);
        int& b = get<2>(corridor);
        int& e = get<0>(corridor);

        if(find(a) == find(b)) continue;

        join(a, b); total_e += e;

        if(find(trap_a) == find(trap_b))
        {
            cout << e << endl;
            return 0;
        }
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;
int components;

int find(int& x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

void join(int& a, int& b)
{
   int root_a = find(a);
   int root_b = find(b);

   uf[a] = root_b;
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    components = n;

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<tuple<int, int, int>> corridors;
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_tuple(e, a, b));
    }

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

    int total_e = 0;
    for(auto& corridor : corridors)
    {
        int& a = get<1>(corridor);
        int& b = get<2>(corridor);
        int& e = get<0>(corridor);

        if(find(a) == find(b)) continue;

        join(a, b); total_e += e;

        if(find(trap_a) == find(trap_b))
        {
            cout << e << endl;
            return 0;
        }
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;

int find(int& x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

void join(int& a, int& b)
{
    int root_a = find(a);
    int root_b = find(b);

    uf[root_b] = root_a;
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<tuple<int, int, int>> corridors;
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_tuple(e, a, b));
    }

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

    long long total_e = 0;
    for(auto& corridor : corridors)
    {
        int& a = get<1>(corridor);
        int& b = get<2>(corridor);
        int& e = get<0>(corridor);

        if(find(a) == find(b))
        {
            continue;
        }

        join(a, b); total_e += e;

        if(find(trap_a) == find(trap_b))
        {
            cout << e << endl;
            return 0;
        }
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;

int find(int& x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

void join(int& a, int& b)
{
    int root_a = find(a);
    int root_b = find(b);

    uf[root_b] = root_a;
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<tuple<int, int, int>> corridors;
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_tuple(e, a, b));
    }

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

    for(auto& corridor : corridors)
    {
        int& a = get<1>(corridor);
        int& b = get<2>(corridor);
        int& e = get<0>(corridor);

        if(find(a) == find(b))
        {
            continue;
        }

        join(a, b);

        if(find(trap_a) == find(trap_b))
        {
            cout << e << endl;
            return 0;
        }
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;

int find(int x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<pair<int, int>> corridors;
    corridors.reserve(m);
    pair<int, int>* points = new pair<int, int>[m + 1];
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_pair(e, i));

        points[i] = make_pair(a, b);
    }

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

    for(auto& corridor : corridors)
    {
        int& a = points[corridor.second].first;
        int& b = points[corridor.second].second;
        int& e = corridor.first;

        int root_a = find(a);
        int root_b = find(b);

        if(root_a == root_b)
        {
            continue;
        }

        if((trap_a == root_a && trap_b == root_b) || (trap_b == root_a && trap_a == root_b))
        {
            cout << e << endl;
            return 0;
        }

        if(trap_a == root_a || trap_b == root_a) uf[root_b] = root_a;
        else uf[root_a] = root_b;
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;
int components;

int find(int& x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

int join(int& a, int& b)
{
   int root_a = find(a);
   int root_b = find(b);

   uf[a] = root_b;
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    components = n;

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<tuple<int, int, int>> corridors;
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_tuple(e, a, b));
    }

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

    int total_e = 0;
    for(auto& corridor : corridors)
    {
        int& a = get<1>(corridor);
        int& b = get<2>(corridor);
        int& e = get<0>(corridor);

        if(find(a) == find(b)) continue;

        join(a, b); total_e += e;

        if(find(trap_a) == find(trap_b))
        {
            cout << e << endl;
            return 0;
        }
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;

int find(int x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

void join(int& a, int& b)
{
    int root_a = find(a);
    int root_b = find(b);

    uf[root_b] = root_a;
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<pair<int, int>> corridors;
    corridors.reserve(m);
    pair<int, int>* points = new pair<int, int>[m + 1];
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_pair(e, i));

        points[i] = make_pair(a, b);
    }

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

    for(auto& corridor : corridors)
    {
        int& a = points[corridor.second].first;
        int& b = points[corridor.second].second;
        int& e = corridor.first;

        if(find(a) == find(b))
        {
            continue;
        }

        join(a, b);

        if(find(trap_a) == find(trap_b))
        {
            cout << e << endl;
            return 0;
        }
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;

int find(int x)
{
    while(x != uf[x]) x = uf[x];
    return x;
}

void join(int& a, int& b)
{
    int root_a = find(a);
    int root_b = find(b);

    uf[root_b] = root_a;
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<tuple<int, int, int>> corridors;
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_tuple(e, a, b));
    }

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

    for(auto& corridor : corridors)
    {
        int& a = get<1>(corridor);
        int& b = get<2>(corridor);
        int& e = get<0>(corridor);

        if(find(a) == find(b))
        {
            continue;
        }

        join(a, b);

        if(find(trap_a) == find(trap_b))
        {
            cout << e << endl;
            return 0;
        }
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;

int find(int x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<pair<int, int>> corridors;
    corridors.reserve(m);
    pair<int, int>* points = new pair<int, int>[m + 1];
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_pair(e, i));

        points[i] = make_pair(a, b);
    }

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

    for(auto& corridor : corridors)
    {
        int& a = points[corridor.second].first;
        int& b = points[corridor.second].second;
        int& e = corridor.first;

        int root_a = find(a);
        int root_b = find(b);

        if(root_a == root_b)
        {
            continue;
        }

        if((trap_a == root_a && trap_b == root_b) || (trap_b == root_a || trap_a == root_b))
        {
            cout << e << endl;
            return 0;
        }

        if(trap_a == root_a || trap_b == root_a) uf[root_b] = root_a;
        else uf[root_a] = root_b;
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int* uf;

int find(int x)
{
    if(uf[x] != x)
    {
        uf[x] = find(uf[x]);
    }

    return uf[x];
}

void join(int& a, int& b)
{
    int root_a = find(a);
    int root_b = find(b);

    uf[root_b] = root_a;
}

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

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

    uf = new int[n + 1];
    for(int i=0; i <=n; i++)
    {
        uf[i] = i;
    }

    int trap_a, trap_b, trap_e; cin >> trap_a >> trap_b >> trap_e;

    vector<tuple<int, int, int>> corridors;
    corridors.reserve(m);
    for(int i=1; i < m; i++)
    {
        int a, b, e; cin >> a >> b >> e;

        corridors.push_back(make_tuple(e, a, b));
    }

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

    for(auto& corridor : corridors)
    {
        int& a = get<1>(corridor);
        int& b = get<2>(corridor);
        int& e = get<0>(corridor);

        if(find(a) == find(b))
        {
            continue;
        }

        join(a, b);

        if(find(trap_a) == find(trap_b))
        {
            cout << e << endl;
            return 0;
        }
    }

    cout << "1000000000" << endl;

    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define ld long double
#define X first
#define Y second
#define pb push_back
#define EPS 1e-15
#define all(a) (a).begin(), (a).end()
#define sz(a) int((a).size())

#define ms(s, n) memset(s, n, sizeof(s))

#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define FOD(i,a,b) for (int i = (a); i >= (b); i--)
#define FORE(i,a,b) for (int i = (a); i >= (b); i--)
#define sqr(a) (a)*(a)

#define foru(i,a,b) for (ll i = (a); i <= (b); ++i)
#define ford(i,a,b) for (ll i = (a); i >= (b); --i)
#define cbit(a) __builtin_popcount(a)
#define uni(a) (a).resize(unique(all(a)) - (a).begin())

using namespace std;
typedef pair<ll, ll> II;
typedef pair<int, int> ii;

const int M = 1e5+2;
ll MOD = 1e9;

struct Edge {
    int u, v, w;
    Edge() {}
    Edge(int u, int v, int w): u(u), v(v), w(w) {}
    bool operator < (Edge &o) {return (w < o.w);}
};

int n,m;
vector<Edge> edges;

int par[M+2];
int _find(int u) {
    if(par[u] == -1) return u;
    return par[u] = _find(par[u]);
}
int ux,vx,wx;

ll solve() {
    cin>>n>>m;
    int u,v,w;

    cin>>ux>>vx>>wx;
    foru(i,2,m){
        cin>>u>>v>>w;
        edges.pb(Edge(u,v,w));
    }

    foru(i,1,n) par[i] = -1;
    sort(all(edges));

    int pu, pv;
    for(int i=0; i<edges.size(); i++) {
        u = edges[i].u;
        v = edges[i].v;
        pu = _find(u);
        pv = _find(v);

        if(pu != pv) {
            par[pu] = pv;

            if(_find(ux) == _find(vx)) {
                cout<<edges[i].w;
                return 0;
            }
        }
    }

    cout<<MOD;
}

int main() {
    ios_base::sync_with_stdio(0);
   // freopen("input.txt", "r", stdin);
    solve();
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define ld long double
#define X first
#define Y second
#define pb push_back
#define EPS 1e-15
#define all(a) (a).begin(), (a).end()
#define sz(a) int((a).size())

#define ms(s, n) memset(s, n, sizeof(s))

#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define FOD(i,a,b) for (int i = (a); i >= (b); i--)
#define FORE(i,a,b) for (int i = (a); i >= (b); i--)
#define sqr(a) (a)*(a)

#define foru(i,a,b) for (ll i = (a); i <= (b); ++i)
#define ford(i,a,b) for (ll i = (a); i >= (b); --i)
#define cbit(a) __builtin_popcount(a)
#define uni(a) (a).resize(unique(all(a)) - (a).begin())

using namespace std;
typedef pair<ll, ll> II;
typedef pair<int, int> ii;

const int M = 1e5+2;
ll MOD = 1e9;

struct Edge {
    int u, v, w, id;
    Edge() {}
    Edge(int u, int v, int w, int id): u(u), v(v), w(w), id(id) {}
    bool operator < (Edge &o) {return (w < o.w) || (w==o.w && id < o.id);}
};

int n,m;
vector<Edge> edges;

int par[M+2];
int _find(int u) {
    if(par[u] == -1) return u;
    return _find(par[u]);
}

bool check(int val, int &pos) {
    edges[pos].w = val;
    while(pos > 0 && edges[pos].w <= edges[pos-1].w) swap(edges[pos], edges[pos-1]), pos--;
    while(pos < n && edges[pos].w > edges[pos+1].w) swap(edges[pos], edges[pos+1]), pos++;

    foru(i,1,n) par[i] = -1;
    int u,v,pu,pv;

    foru(i,0,n-1) {
        u = edges[i].u;
        v = edges[i].v;
        pu = _find(u);
        pv = _find(v);

        if(pu != pv) {
            par[pu] = pv;
            if(edges[i].id == 1) return 1;
        }
        else {
            if(edges[i].id == 1) return 0;
        }
    }

    return 0;
}

ll solve() {
    cin>>n>>m;
    int u,v,w;

    foru(i,1,m){
        cin>>u>>v>>w;
        edges.pb(Edge(u,v,w,i));
    }

    int ans = edges[0].w;

    sort(all(edges));
    int pos=0;
    for(int i=0; i<m; i++) if(edges[i].id == 1) {
        pos = i;
        break;
    }

    int l=0, r=MOD, mid;
    while(l<=r) {
        mid = (l+r)/2;
        if(check(mid, pos)) ans=mid, l=mid+1;
        else r=mid-1;
    }

    cout<<ans;
}

int main() {
    ios_base::sync_with_stdio(0);
   // freopen("input.txt", "r", stdin);
    solve();
    return 0;
}


n=int(input())
l=map(int,raw_input().split())
a=[4,8,15,16,23,42]
ans=[0]*6
for k in l:
    i=a.index(k)
    if i==0:
        ans[i]+=1
    if ans[i-1]>ans[i]:
        ans[i]+=1
print n-(ans[5]*6)


n = int(input())
x = [4, 8, 15, 16, 23, 42]
r = [0] * len(x)
z = 0
for v in map(int, input().split()):
    i = x.index(v)
    if not i or r[i-1] > r[i]:
        r[i] += 1
    else:
        z += 1
z += sum(v-r[-1] for v in r)
print(z)


input()
l=list(map(int,input().split()))
minn=9999999999999
minn=min(minn,l.count(4))
minn=min(minn,l.count(8))
minn=min(minn,l.count(15))
minn=min(minn,l.count(16))
minn=min(minn,l.count(23))
minn=min(minn,l.count(42))
print(len(l)-(minn*6))


from collections import defaultdict
def find(li):
	k = {4:0,8:1,15:2,16:3,23:4,42:5}
	temp = li.count(4)
	stacks = []
	for i in range(5*10**5):
		stacks.append([])
	d = defaultdict(int)
	for i in range(len(li)):
		temp = d[li[i]]
		potentialStack = stacks[temp]
		index = k[li[i]]
		if index == 0:
			potentialStack.append(li[i])
			d[li[i]]+=1
		else:
			if len(potentialStack)!=0 and k[potentialStack[-1]] == index-1:
				potentialStack.append(li[i])
				d[li[i]]+=1
	ans = 0
	for i in stacks:
		if len(i)==6:
			ans+=6
	return len(li) - ans

x = int(input())
li = list(map(int,input().split()))
print(find(li))


from collections import defaultdict
def find(li):
	k = {4:0,8:1,15:2,16:3,23:4,42:5}
	temp = li.count(4)
	stacks = []
	for i in range(temp):
		stacks.append([])
	d = defaultdict(int)
	for i in range(len(li)):
		temp = d[li[i]]
		potentialStack = stacks[temp]
		index = k[li[i]]
		if index == 0:
			potentialStack.append(li[i])
			d[li[i]]+=1
		else:
			if len(potentialStack)!=0 and k[potentialStack[-1]] == index-1:
				potentialStack.append(li[i])
				d[li[i]]+=1
	ans = 0
	for i in stacks:
		if len(i)==6:
			ans+=6
	return len(li) - ans

x = int(input())
li = list(map(int,input().split()))
print(find(li))


from collections import defaultdict, deque

def main():
    n = int(input())
    a = list(map(int, input().split()))
    d = defaultdict(deque)
    for ind, elem in enumerate(a):
        d[elem].append(ind)
    answer = 0
    while all(k for k in d.values()):
        next_ = -1
        carry = 0
        for k in sorted(d.keys()):
            if d[k]:
                while 1:
                    q = d[k].popleft()
                    if q > next_:
                        carry += 1
                        next_ = q
                        break
                    answer += 1
        if carry != 6:
            answer += carry
    for k in d:
        answer += len(d[k])
    print(answer)

if __name__ == "__main__":
    main()


def main():
    n = int(input())
    a = list(map(int, input().split()))
    if n < 6:
        return n
    stat = {4: [], 8: [], 15: [], 16: [], 23: [], 42: []}
    keys = [k for k in stat.keys()]
    for i in range(n):
        stat[a[i]].append(i)
    answer = 0
    points = {k: 0 for k in stat.keys()}
    i = 0
    while n != 0:
        if keys[i] != 42:
            try:
                while stat[keys[i]][points[keys[i]]] > stat[keys[i + 1]][points[keys[i + 1]]]:
                    points[keys[i + 1]] += 1
                    n -= 1
                    answer += 1
            except IndexError:
                break
            points[keys[i]] += 1
            i += 1
        else:
            points[keys[i]] += 1
            i = 0
        n -= 1
    flag = False
    for k in stat:
        if points[k] < len(stat[k]):
            flag = True
            answer += len(stat[k]) - points[k] + 1
    return answer - 1 if flag else answer

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


def main():
    n = int(input())
    a = list(map(int, input().split()))
    if n < 6:
        return n
    stat = {4: [], 8: [], 15: [], 16: [], 23: [], 42: []}
    keys = [k for k in stat.keys()]
    for i in range(n):
        stat[a[i]].append(i)
    answer = 0
    points = {k: 0 for k in stat.keys()}
    i = 0
    while n != 0:
        if keys[i] != 42:
            try:
                while stat[keys[i]][points[keys[i]]] > stat[keys[i + 1]][points[keys[i + 1]]]:
                    points[keys[i + 1]] += 1
                    n -= 1
                    answer += 1
            except IndexError:
                break
            points[keys[i]] += 1
            i += 1
        else:
            points[keys[i]] += 1
            i = 0
        n -= 1
    for k in stat:
        answer += len(stat[k]) - points[k]
    return answer

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


from collections import defaultdict, deque

def main():
    n = int(input())
    a = list(map(int, input().split()))
    d = defaultdict(deque)
    for ind, elem in enumerate(a):
        d[elem].append(ind)
    answer = 0
    while all(k for k in d.values()):
        next_ = -1
        carry = 0
        for k in sorted(d.keys()):
                while 1:
                    if d[k]:
                        q = d[k].popleft()
                        if q > next_:
                            carry += 1
                            next_ = q
                            break
                        answer += 1
                    else:
                        break
        if carry != 6:
            answer += carry
    for k in d:
        answer += len(d[k])
    print(answer)

if __name__ == "__main__":
    main()


a = [4, 8, 15, 16, 23, 42]
D = dict.fromkeys(a, 0)

n = int(input())
*L, = map(int, input().split())
for item in L:
    if item in a:
        count = 0
        for key in D:
            if key < item and D[key] > D[item]:
                count += 1
        if count == a.index(item):
            D[item] += 1

print(n - 6*D[42])


def in_sequence(L):
    L.append('extra')
    arr = [4, 8, 15, 16, 23, 42]
    B = [0] * 6
    count = 0
    for i in range(6):
        if not i:
            if arr[i] in L:
                B[i] = L.index(arr[i])
                L.pop(B[i])
                count += 1
            else:
                return False
        else:
            if arr[i] in L[B[i-1]:] and count == i:
                B[i] = B[i-1] + L[B[i-1]:].index(arr[i])
                L.pop(B[i])
                count += 1
            else:
                return False
    return True

n = int(input())
*L, = map(int, input().split())
C = [0] * 6 #stores count of each element in arr
arr = [4, 8, 15, 16, 23, 42]
for i, item in enumerate(arr):
    C[i] = L.count(item)

nosSeq = 0
for _ in range(min(C)):
    if in_sequence(L):
        nosSeq += 1
print(n - nosSeq * 6)


"""
    Satwik_Tiwari ;) .
    17th july , 2020  - Friday
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
    ans = 1
    while(b>0):
        if(b%2==1):
            ans*=a
        a*=a
        b//=2
    return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))

def solve():
    n = int(inp())
    help = [4,8,15,16,23,42]
    a = lis()
    cnt={}
    for i in range(6):
        cnt[help[i]] = 0

    ans = 0
    for i in range(0,n):
        # print(cnt,a[i])
        if(a[i] == 4):
            cnt[a[i]]+=1
            continue

        f = False
        for j in range(6):
            if(a[i] != help[j]):
                if(cnt[a[i]] == cnt[help[j]]):
                    f = True
                    break
            else:
                break

        if(f):
            ans+=1
        else:
            cnt[a[i]] +=1

    m = 10**9
    for i in cnt:
        m = min(m,cnt[i])
    for i in cnt:
        ans+=max(0,cnt[i]-m)
    print(ans)

testcase(1)
# testcase(int(inp()))


"""
    Satwik_Tiwari ;) .
    17th july , 2020  - Friday
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for p in range(t):
        solve()
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
    ans = 1
    while(b>0):
        if(b%2==1):
            ans*=a
        a*=a
        b//=2
    return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) : # Check Prime Number or not
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))

def solve():
    n = int(inp())
    help = [4,8,15,16,23,42]
    a = lis()
    cnt={}
    for i in range(6):
        cnt[help[i]] = 0

    ans = 0
    for i in range(0,n):
        if(a[i] == 4):
            cnt[a[i]]+=1
            continue

        if(cnt[a[i]] == cnt[4]):
            ans+=1
        else:
            cnt[a[i]] +=1

    m = 10**9
    for i in cnt:
        m = min(m,cnt[i])
    for i in cnt:
        ans+=max(0,cnt[i]-m)
    print(ans)

testcase(1)
# testcase(int(inp()))


import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics
def sin():
    return input()
def ain():
    return list(map(int, sin().split()))
def sain():
    return input().split()
def iin():
    return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007
def sieve(n):
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    s = set()
    for p in range(2, n+1):
        if prime[p]:
            s.add(p)
    return s
def readTree(n, m):
    adj = [deque([]) for _ in range(n+1)]
    for _ in range(m):
        u,v = ain()
        adj[u].append(v)
        adj[v].append(u)
    return adj

def main():
    n = iin()
    a = ain()
    l = [4,8,15,16,23,42]
    if set(a) != set(l):
        print(n)
    else:
        d = {}
        flag = 0
        for i in l:
            d[i] = deque([])
        for i in range(n):
            d[a[i]].append(i)
        ans = 0
        x = -1
        flag = 0
        for i in d[4]:
            for j in l[1:]:
                flag = 0
                k = 0
                ll = len(d[j])
                while k<ll:
                    if d[j][0] < i:
                        d[j].popleft()
                        k += 1
                    else:
                        flag = 1
                        break
                if flag == 0:
                    break
            if flag == 0:
                break
            else:
                ans += 1
        print(n - ans*6)

# Fast IO Template starts

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

if os.getcwd() == 'D:\\code':
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
    input = lambda: sys.stdin.readline().rstrip("\r\n")
# Fast IO Template ends
if __name__ == "__main__":
    main()


import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics
def sin():
    return input()
def ain():
    return list(map(int, sin().split()))
def sain():
    return input().split()
def iin():
    return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007
def sieve(n):
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
        if (prime[p] == True):
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
    s = set()
    for p in range(2, n+1):
        if prime[p]:
            s.add(p)
    return s
def readTree(n, m):
    adj = [deque([]) for _ in range(n+1)]
    for _ in range(m):
        u,v = ain()
        adj[u].append(v)
        adj[v].append(u)
    return adj

def main():
    n = iin()
    a = ain()
    l = [4,8,15,16,23,42]
    if set(a) != set(l):
        print(n)
    else:
        d = {}
        flag = 0
        for i in l:
            d[i] = deque([])
        for i in range(n):
            d[a[i]].append(i)
        ans = 0
        x = -1
        flag = 0
        for i in d[4]:
            x = i
            for j in l[1:]:
                flag = 0
                k = 0
                ll = len(d[j])
                while k<ll:
                    if d[j][0] < x:
                        d[j].popleft()
                        k += 1
                    else:
                        flag = 1
                        x = d[j][0]
                        d[j].popleft()
                        break
                if flag == 0:
                    break
            if flag == 0:
                break
            else:
                ans += 1
        print(n - ans*6)

# Fast IO Template starts

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

if os.getcwd() == 'D:\\code':
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
    input = lambda: sys.stdin.readline().rstrip("\r\n")
# Fast IO Template ends
if __name__ == "__main__":
    main()


R = lambda: map(int, input().split())
n = int(input())
cnts = [0] * 50
arr = [8,15,16,23,42,4]
for x in R():
    if x == 4:
        cnts[x] += 1
    elif x in arr:
        idx = arr.index(x)
        cnts[arr[idx]] = min(cnts[arr[idx]] + 1, cnts[arr[idx - 1]])
print(n - 6 * cnts[42])


R = lambda: map(int, input().split())
n = int(input())
cnts = [0] * 50
for x in R():
    cnts[x] += 1
cnts = [cnts[x] for x in [4,8,15,16,23,42]]
if len(set(cnts)) == 1:
    print(0)
else:
    print(sum(cnts) - 6 * min(cnts))


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

4,8,15,16,23,42
l=[]

for i in range(6):
	l.append([])

for i in range(n):
	if(a[i]==4):
		l[0].append(i)
	elif(a[i]==8):
		l[1].append(i)
	elif(a[i]==15):
		l[2].append(i)
	elif(a[i]==16):
		l[3].append(i)
	elif(a[i]==23):
		l[4].append(i)
	else:
		l[5].append(i)

mn=-1

tot=0

flg=0

i=0

indx1=0
indx2=0
indx3=0
indx4=0
indx5=0
indx6=0

while(flg==0):
	if(i%6==0):
		if(indx1>=len(l[0])):
			flg=1
		else:
			mn=l[0][indx1]
			indx1+=1
	elif(i%6==1):
		if(indx2>=len(l[1])):
			flg=1
		else:
			while(indx2<len(l[1]) and mn>l[1][indx2]):
				indx2+=1
			if(indx2>=len(l[1])):
				flg=1
			else:
				mn=l[1][indx2]
				indx2+=1
	elif(i%6==2):
		if(indx3>=len(l[2])):
			flg=1
		else:
			while(indx3<len(l[2]) and mn>l[2][indx3]):
				indx3+=1
			if(indx3>=len(l[2])):
				flg=1
			else:
				mn=l[2][indx3]
				indx3+=1
	elif(i%6==3):
		if(indx4>=len(l[3])):
			flg=1
		else:
			while(indx4<len(l[3]) and mn>l[3][indx4]):
				indx4+=1
			if(indx4>=len(l[3])):
				flg=1
			else:
				mn=l[3][indx4]
				indx4+=1
	elif(i%6==4):
		if(indx5>=len(l[4])):
			flg=1
		else:
			while(indx5<len(l[4]) and mn>l[4][indx5]):
				indx5+=1
			if(indx5>=len(l[4])):
				flg=1
			else:
				mn=l[4][indx5]
				indx5+=1
	else:
		if(indx6>=len(l[5])):
			flg=1
		else:
			while(indx6<len(l[5]) and mn>l[5][indx6]):
				indx6+=1
			if(indx6>=len(l[5])):
				flg=1
			else:
				mn=l[5][indx6]
				tot+=1
				indx6+=1
	i+=1

print(n-(6*tot))


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

d={}

d[4]=0
d[8]=0
d[15]=0
d[16]=0
d[23]=0
d[42]=0

for i in a:
	d[i]+=1

mn=10**10

for i in d:
	mn=min(d[i],mn)

ans=0

for i in d:
	ans+=d[i]-mn

print(ans)


n=int(input())
a=list(map(int,input().split()))
x={4:0,8:0,15:0,16:0,23:0,42:0}
for i in range(0,n):
	x[a[i]]+=1
minx=min(list(x.values()))
print(n-(6*minx))


from itertools import permutations
#from fractions import Fraction
from collections import defaultdict
from math import*
import os
import sys
from io import BytesIO, IOBase
from heapq import nlargest
from bisect import*
import copy
import itertools
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

def input(): return sys.stdin.readline().rstrip("\r\n")
#-------------above part copied-----------------------

n=int(input())
arr=list(map(int,input().split()))
ans=0
x=[4,8,15,16,23,42]
d=defaultdict(int)
for i in range(n):
    d[arr[i]]+=1
    if arr[i]!=4:
        if d[x[x.index(arr[i])-1]]<d[arr[i]]:
            d[arr[i]]-=1
            ans+=1
#    print(ans)
total=0
mi=10**9
#print(ans)
for i in range(6):
    total+=d[x[i]]
    if d[x[i]]<mi:
        mi=d[x[i]]
print(ans+total-6*mi)


n=int(input())

s=input()
s1=s.split()
l=[int(i) for i in s1]

d=[4,8,15,16,23,42]

dp={}

for i in range(len(l)):

    if l[i]==4:

        if 4 not in dp:

            dp[4]=1

        else:
            dp[4]=dp[4]+1

    if l[i]==8:

        if 4 in dp and 8 not in dp:

            dp[8]=1

        elif 4 in dp and dp[8]<dp[4]:

            dp[8]=dp[8]+1

    if l[i]==15:

        if 8 in dp and 15 not in dp:

            dp[15]=1

        elif 8 in dp and dp[15]<dp[8]:

            dp[15]=dp[15]+1

    if l[i]==16:

        if 15 in dp and 16 not in dp:

            dp[16]=1

        elif 16 in dp and dp[16]<dp[15]:

            dp[16]=dp[16]+1

    if l[i]==23:

        if 16 in dp and 23 not in dp:

            dp[23]=1

        elif 23 in dp and dp[23]<dp[16]:

            dp[23]=dp[23]+1

    if l[i]==42:

        if 23 in dp and 42 not in dp:

            dp[42]=1

        elif 42 in dp and dp[42]<dp[23]:

            dp[42]=dp[42]+1

if 42 in dp:
    print(len(l)-6*dp[42])
else:
    print(len(l))


N = int(input())
arr = [int(x) for x in input().split()]
cnt = {4: 0,8:0,15:0,16:0,23:0,42:0}
ans = 0
for i in arr:
	if(i==4):
		cnt[i]+=1
	elif(i==8):
		if(cnt[i]>=cnt[4]):
			ans+=1
		else:
			cnt[i]+=1
	elif(i==15):
		if(cnt[i]>=cnt[8]):
			ans+=1
		else:
			cnt[i]+=1
	elif(i==16):
		if(cnt[i]>=cnt[15]):
			ans+=1
		else:
			cnt[i]+=1
	elif(i==23):
		if(cnt[i]>=cnt[16]):
			ans+=1
		else:
			cnt[i]+=1
	elif(i==42):
		if(cnt[i]>=cnt[23]):
			ans+=1
		else:
			cnt[i]+=1
temp = 0
for i in cnt.values():
	temp+=i
print(ans+(temp%6))


N = int(input())
arr = [int(x) for x in input().split()]
cnt = {4: 0,8:0,15:0,16:0,23:0,42:0}
ans = 0
for i in arr:
	if(i==4):
		cnt[i]+=1
	elif(i==8):
		if(cnt[i]>=cnt[4]):
			ans+=1
		else:
			cnt[i]+=1
	elif(i==15):
		if(cnt[i]>=cnt[8]):
			ans+=1
		else:
			cnt[i]+=1
	elif(i==16):
		if(cnt[i]>=cnt[15]):
			ans+=1
		else:
			cnt[i]+=1
	elif(i==23):
		if(cnt[i]>=cnt[16]):
			ans+=1
		else:
			cnt[i]+=1
	elif(i==42):
		if(cnt[i]>=cnt[23]):
			ans+=1
		else:
			cnt[i]+=1
temp = 0
for i in cnt.values():
	temp+=i-cnt[42]
print(ans+temp)


n=int(input())

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

four=a.count(4)
eight=a.count(8)
fif=a.count(15)
six=a.count(16)
twen=a.count(23)
fourty=a.count(42)

check=min(four,eight,fif,six,twen,fourty)

print(n-(check*6))


from __future__ import division, print_function
from io import BytesIO, IOBase
import os,sys,math,heapq,copy
from collections import defaultdict,deque
from bisect import bisect_left,bisect_right
from functools import cmp_to_key
from itertools import permutations,combinations,combinations_with_replacement
# <fastio>
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()
if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# </fastio>
# sys.setrecursionlimit(10**6)
# sys.stdin=open('Input.txt','r')
# sys.stdout=open('Output.txt','w')
mod=1000000007
# Reading Single Input
def get_int(): return int(sys.stdin.readline().strip())
def get_str(): return sys.stdin.readline().strip()
def get_float(): return float(sys.stdin.readline().strip())
# Reading Multiple Inputs
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_strs(): return map(str, sys.stdin.readline().strip().split())
def get_floats(): return map(float, sys.stdin.readline().strip().split())
# Reading List Of Inputs
def list_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def list_strs(): return list(map(str, sys.stdin.readline().strip().split()))
def list_floats(): return list(map(float, sys.stdin.readline().strip().split()))
# ------------------------------------------------------------------------------------- #

n=get_int()
l=list_ints()
d=defaultdict(int)
for i in l:
    d[i]+=1
if(len(d)==6):
    rem=n%6
    m=math.inf
    for key in d.keys():
        m=min(m,d[key])
    times=(n-rem)//6
    if(m==times):
        print(rem)
    else:
        print(n-(m*6))
else:
    print(n)


from __future__ import division, print_function
from io import BytesIO, IOBase
import os,sys,math,heapq,copy
from collections import defaultdict,deque
from bisect import bisect_left,bisect_right
from functools import cmp_to_key
from itertools import permutations,combinations,combinations_with_replacement
# <fastio>
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()
if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# </fastio>
# sys.setrecursionlimit(10**6)
# sys.stdin=open('Input.txt','r')
# sys.stdout=open('Output.txt','w')
mod=1000000007
# Reading Single Input
def get_int(): return int(sys.stdin.readline().strip())
def get_str(): return sys.stdin.readline().strip()
def get_float(): return float(sys.stdin.readline().strip())
# Reading Multiple Inputs
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_strs(): return map(str, sys.stdin.readline().strip().split())
def get_floats(): return map(float, sys.stdin.readline().strip().split())
# Reading List Of Inputs
def list_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def list_strs(): return list(map(str, sys.stdin.readline().strip().split()))
def list_floats(): return list(map(float, sys.stdin.readline().strip().split()))
# ------------------------------------------------------------------------------------- #

n=get_int()
l=list_ints()
a=[0]*(6)
for i in l:
    if(i==4):
        a[0]+=1
    elif(i==8):
        a[1]=min(a[0],a[1]+1)
    elif (i == 15):
        a[2] = min(a[1], a[2] + 1)
    elif (i == 16):
        a[3] = min(a[2], a[3] + 1)
    elif (i == 23):
        a[4] = min(a[3], a[4] + 1)
    else:
        a[5] = min(a[4], a[5] + 1)
print(n-a[5]*6)


from __future__ import division, print_function
from io import BytesIO, IOBase
import os,sys,math,heapq,copy
from collections import defaultdict,deque
from bisect import bisect_left,bisect_right
from functools import cmp_to_key
from itertools import permutations,combinations,combinations_with_replacement
# <fastio>
if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()
if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# </fastio>
# sys.setrecursionlimit(10**6)
# sys.stdin=open('Input.txt','r')
# sys.stdout=open('Output.txt','w')
mod=1000000007
# Reading Single Input
def get_int(): return int(sys.stdin.readline().strip())
def get_str(): return sys.stdin.readline().strip()
def get_float(): return float(sys.stdin.readline().strip())
# Reading Multiple Inputs
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_strs(): return map(str, sys.stdin.readline().strip().split())
def get_floats(): return map(float, sys.stdin.readline().strip().split())
# Reading List Of Inputs
def list_ints(): return list(map(int, sys.stdin.readline().strip().split()))
def list_strs(): return list(map(str, sys.stdin.readline().strip().split()))
def list_floats(): return list(map(float, sys.stdin.readline().strip().split()))
# ------------------------------------------------------------------------------------- #

n=get_int()
l=list_ints()
d=defaultdict(int)
for i in l:
    d[i]+=1
if(len(d)==6):
    rem=n%6
    m=math.inf
    for key in d.keys():
        m=min(m,d[key])
    times=(n-rem)//6
    if(m==times):
        print(rem)
    else:
        print(n)
else:
    print(n)


dummy=[4,8,15,16,42,23]
n=int(input())
l=[int(i) for i in input().split()]
from collections import Counter
c=Counter(l)
m=10**9
for i in dummy:
    m=min(m,c[i])
print(n-m*6)


n = int(input())
t = input()
t = t.split()
t = [int(x) for x in t]
T = [0,4,8,15,16,23,42]
val = [1e10, 0, 0, 0, 0, 0, 0]
for i in t:
	idx = T.index(i)
	if val[idx - 1] > val[idx]:
		val[idx] += 1
print(n - 6*val[6])


n=int(input())
arr=list(map(int,input().split()))
temp=[0]*6
req=[4,8,15,16,23,42]
for i in arr:
    idx=req.index(i)
    if idx==0:
        temp[idx]+=1
    elif idx>0 and temp[idx-1]>temp[idx]:
        temp[idx]+=1

print(n-(6*min(temp)))


import sys
n=int(input())
arr=list(map(int,input().split()))
d1={4:0,8:0,15:0,16:0,23:0,42:0}
ans=0

for i in range(n):
    if arr[i] not in d1:
        ans+=1
    else:
        d1[arr[i]]+=1

min1=sys.maxsize
for i in d1:
    if d1[i]<min1:
        min1=d1[i]

# print(d1)
if min1==0:
    ans+=n
else:
    for i in d1:
        ans+=abs(d1[i]-min1)
print(ans)


n = int(input())
a = list(map(int, input().split()))
D = {4: 0, 8: 1, 15: 2, 16: 3, 23: 4, 42: 5}
d = [0] * 6
for i in range(n):
    d[D[a[i]]] += 1

num = float('inf')
for i in range(6):
    num = min(num, d[i])

for i in range(6):
    d[i] -= num

print(sum(d))


n = int(input())
a = list(map(int, input().split()))
D = {4: 0, 8: 1, 15: 2, 16: 3, 23: 4, 42: 5}
d = [[] for i in range(6)]
for i in range(n):
    d[D[a[i]]].append(i)

P = [0] * 6
num = 0
while True:
    if P[0] < len(d[0]):
        k = d[0][P[0]]
    else:
        break
    while P[1] < len(d[1]) and k >= d[1][P[1]]:
        P[1] += 1
        num += 1

    if P[1] < len(d[1]):
        k = d[1][P[1]]
    else:
        break
    while P[2] < len(d[2]) and k >= d[2][P[2]]:
        P[2] += 1
        num += 1

    if P[2] < len(d[2]):
        k = d[2][P[2]]
    else:
        break
    while P[3] < len(d[3]) and k >= d[3][P[3]]:
        P[3] += 1
        num += 1

    if P[3] < len(d[3]):
        k = d[3][P[3]]
    else:
        break
    while P[4] < len(d[4]) and k >= d[4][P[4]]:
        P[4] += 1
        num += 1

    if P[4] < len(d[4]):
        k = d[4][P[4]]
    else:
        break
    while P[5] < len(d[5]) and k >= d[5][P[5]]:
        P[5] += 1
        num += 1

    flag = True
    for j in range(6):
        if P[j] >= len(d[j]):
            flag = False
            break
    else:
        for j in range(6):
            P[j] += 1

    if not flag:
        break

for i in range(6):
    num += len(d[i]) - P[i]

print(num)


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

d = {4:0, 8:1, 15:2, 16:3, 23:4, 42:5}
A = [d[a] for a in A]
#print(A)
B = []
ans = 0
for i in range(n):
    if len(B) == 0:
        if A[i] == 0:
            B.append(0)
        else:
            ans += 1
        continue
    if A[i] == 0:
        B.append(0)
        continue
    for j in range(len(B)):
        if B[j] == A[i]-1:
            B[j] = A[i]
            break
    else:
        ans += 1
#print(B)
for j in range(len(B)):
    if B[j] != 5:
        ans += B[j]+1

print(ans)


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

d = {4:0, 8:1, 15:2, 16:3, 23:4, 42:5}
A = [d[a] for a in A]
#print(A)

import bisect

B = [0]*6
ans = 0
for a in A:
    if a == 0:
        B[0] += 1
        continue
    else:
        if B[a-1] != 0:
            B[a-1] -= 1
            B[a] += 1
        else:
            ans += 1
#print(B)
for j in range(6):
    if j != 5:
        ans += B[j]*(j+1)
print(ans)


n = int(input())
arr = list(map(int,input().split()))
mp = {4:0,8:1,15:2,16:3,23:4,42:5}
cnt = [0] * 6
for i in range(n):
    if arr[i] == 4:
        cnt[mp[arr[i]]] += 1
    else:
        temp = cnt[mp[arr[i]]] + 1
        if cnt[mp[arr[i]]-1] < temp:
            continue
        else: cnt[mp[arr[i]]] += 1
print(n-min(cnt)*6)


def read(t=int):
    return list(map(t,input().strip().split(' ')))
n = read()[0]
a = read()
from collections import defaultdict
d=defaultdict(int)
last = [4,4,8,15,16,23,42]
for i in a:
    index = last.index(i)-1
    if i == 4:
        d[i]+=1
    else:
        d[i]=min(d[i]+1,d[last[index]])
remove= n-min(d.values())*6
print(d)
if remove<0:
    remove = n
print(remove)


def read(t=int):
    return list(map(t,input().strip().split(' ')))
n = read()[0]
a = read()
from collections import defaultdict
d=defaultdict(int)
last = [4,4,8,15,16,23,42]
for i in a:
    index = last.index(i)-1
    if i == 4:
        d[i]+=1
    else:
        d[i]=min(d[i]+1,d[last[index]])
remove= n-min(d.values())*6
if remove<0:
    remove = n
print(remove)


def read(t=int):
    return list(map(t,input().strip().split(' ')))
n = read()[0]
a = read()
from collections import defaultdict
d=defaultdict(int)
last = [4,4,8,15,16,23,42]
for i in a:
    index = last.index(i)-1
    if i == 4:
        d[i]+=1
    else:
        d[i]=d[last[index]]
remove= n-min(d.values())*6
if remove<0:
    remove = n
print(remove)


import sys
def main():
    n = int(sys.stdin.readline())
    lst = list(map(int, sys.stdin.readline().split()))
    normal = [4,8,15,16,23,42]
    end = []
    q = 0
    for i in range(n):
        if lst[i] == 4:
            end.append(5)
        else:
            index = 6 - normal.index(lst[i])
            j = None
            for j in range(q, len(end)):
                if end[j] == index:
                    end[j] -= 1
                    break
                elif end[j] > index:
                    break
            if j != None and end[j] == 0:
                q += 1
    print(n - (q * 6))
main()


import sys
def main():
    n = int(sys.stdin.readline())
    lst = list(map(int, sys.stdin.readline().split()))
    normal = [4,8,15,16,23,42]
    end = []
    q = 0
    for i in range(n):
        if lst[i] == 4:
            end.append(5)
        else:
            index = 6 - normal.index(lst[i])
            for j in range(q, len(end)):
                if end[j] == index:
                    end[j] -= 1
                    break
                elif end[j] > index:
                    break
            if end[j] == 0:
                q += 1
    print(n - (q * 6))
main()


import sys
def main():
    n = int(sys.stdin.readline())
    lst = list(map(int, sys.stdin.readline().split()))
    normal = [4,8,15,16,23,42]
    end = [5] * n
    m = 0
    q = 0
    for i in range(n):
        if lst[i] == 4:
            m += 1
        else:
            index = 6 - normal.index(lst[i])
            j = None
            for j in range(q, m):
                if end[j] == index:
                    end[j] -= 1
                    break
                elif end[j] > index:
                    break
            if j != None and end[j] == 0:
                q += 1
    sys.stdout.write(str(n - (q * 6)))
main()


import sys
def main():
    n = int(sys.stdin.readline())
    lst = list(map(int, sys.stdin.readline().split()))
    normal = [4,8,15,16,23,42]
    end = []
    for i in range(n):
        if lst[i] == 4:
            end.append(5)
        else:
            index = 6 - normal.index(lst[i])
            for j in range(len(end)):
                if end[j] == index:
                    end[j] -= 1
                    break
                elif end[j] > index:
                    break
    print(n - (end.count(0) * 6))
main()


import sys
def main():
    n = int(sys.stdin.readline())
    lst = list(map(int, sys.stdin.readline().split()))
    normal = [4,8,15,16,23,42]
    copy = [0] * 6
    for i in range(n):
        fix = normal.index(lst[i])
        if fix == 0 or copy[fix - 1] > copy[fix]:
            copy[fix] += 1
    sys.stdout.write(str(n - copy[-1] * 6))
main()


import java.lang.Integer.min

fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val a = readLine()!!.split(" ").map { it.toInt() }
    val inc = IntArray(6)

    fun mp(x: Int) = when (x) {
        4 -> 0
        8 -> 1
        15 -> 2
        16 -> 3
        23 -> 4
        else -> 5
    }

    for (x in a) {
        val t = mp(x)
        if (t == 0) {
            inc[t]++
        } else {
            inc[t] = min(inc[t - 1], inc[t] + 1)
        }
    }
    println(n - inc[5] * 6)
}


fun main() {
    val n = readLine()!!.toInt()
    val a = readLine()!!.split(" ").map { it.toInt() }

    val item = listOf(4, 8, 15, 16, 23, 42)
    val queue = mutableListOf(0, 0, 0, 0, 0, 0)

    var cnt = 0

    for (i in a) {
        val j = item.indexOf(i)

        if (j == 0 || queue[j - 1] > queue[j]) {
            queue[j]++
        } else {
            cnt++
        }
    }

    for (i in queue) {
        cnt += i - queue.last()
    }

    println(cnt)
}


private fun resolve(a: List<Int>): Int {
    val state = mutableMapOf<Int,Int>()
    for (i in 1..6) state.put(i, 0)
    val map = mapOf(4 to 1, 8 to 2, 15 to 3, 16 to 4, 23 to 5, 42 to 6)
    var toDelete = 0
    for (i in a) {
        val k = map.getOrDefault(i, 0)
//        println("Take $i with index $k")
        if (k > 1) {
            val p = state.getOrDefault(k-1, 0)
            val c = state.getOrDefault(k, 0)
            if (c < p) state.put(k, c + 1) else toDelete++
        } else {
            val c = state.getOrDefault(k, 0)
            state.put(k, c+1)
        }
    }
//    println(state)
    val min: Int = state.minBy { it.value }?.value ?: 0
    var result = state.values.map { it - min }.sum() + toDelete
    return result
}

fun main() {
    //input
    val n = readInt()
    val result = resolve(readIntList())
    println(result)
}

private fun readString(): String = readLine()!!
private fun readInt(): Int = readLine()!!.toInt()
private fun readLong(): Long = readLine()!!.toLong()
private fun readIntList(): List<Int> = readLine()!!.split(" ").map{ it.toInt() }


import java.util.*

typealias IndexPair<Type> = Pair<Type, Int>
typealias IntIndexPair = IndexPair<Int>
typealias IntIntPair = Pair<Int, Int>

typealias IntMatrix = Array<IntArray>
typealias LongMatrix = Array<LongArray>

typealias ListArray<Type> = Array<MutableList<Type>>

typealias Graph = IntMatrix

typealias Edge = Pair<Int, Int>
typealias EdgeArray = Array<Edge>
typealias WeightedGraph = Array<EdgeArray>

typealias TotalEdge = Triple<Int, Int, Int>
typealias TotalEdgeArray = Array<TotalEdge>

fun main() {
    val n = readInt()
    val line = readInts()

    if (line.size < 6) {
        println(line.size)
        return
    }

    val lookup = sortedMapOf(
        4 to 0,
        8 to 0,
        15 to 0,
        16 to 0,
        23 to 0,
        42 to 0
    )

    var toRemove = 0

    line.forEach {
        if (it == 4) {
            lookup[it] = lookup[it]!! + 1
        } else {
            val prevEntryCount = lookup[lookup.headMap(it).lastKey()]!!

            if (prevEntryCount > lookup[it]!!) {
                lookup[it] = lookup[it]!! + 1
            } else {
                toRemove += 1
            }
        }
    }

    val complete = lookup[42]!!
    lookup[42] = 0

    lookup.values.forEach {
        if (it > complete) {
            toRemove += it - complete
        }
    }

    println(toRemove)
}

fun closestDivisible(n: Int, by: Int): Int {
    val q = n / by
    val n1 = by * q
    val n2 = if (n * by > 0) by * (q + 1) else by * (q - 1)
    return if (Math.abs(n - n1) < Math.abs(n - n2)) n1 else n2
}

tailrec fun gcd(a: Int, b: Int): Int =
    if (a == 0) b else gcd(b % a, a)

fun yesNo(yes: Boolean) {
    println(if (yes) "YES" else "NO")
}

fun readStrings(separator: String = " ", emptyWords: Boolean = false): Array<String> {
    val line = readLine()!!
    val list = ArrayList<String>()
    var builder = StringBuilder()

    for (i in 0..line.length) {
        if (i == line.length || separator.contains(line[i])) {
            if (emptyWords || builder.isNotEmpty()) {
                list.add(builder.toString())
                builder = StringBuilder()
            }
        } else {
            builder.append(line[i])
        }
    }

    return list.toTypedArray()
}

fun readString(separator: String = " ") =
    readStrings(separator).first()

fun readInts(separator: String = " ") =
    readStrings(separator).map(String::toInt).toIntArray()

fun readSortedInts(separator: String = " "): IntArray {
    val a = readInts(separator)

    val aInteger: Array<Int> = Array(a.size) { a[it] }
    Arrays.sort(aInteger)

    return aInteger.toIntArray()
}

fun readInt(separator: String = " ") =
    readInts(separator).first()

fun readLongs(separator: String = " ") =
    readStrings(separator).map(String::toLong).toLongArray()

fun readLong(separator: String = " ") =
    readLongs(separator).first()

fun readDoubles(separator: String = " ") =
    readStrings(separator).map(String::toDouble).toDoubleArray()

fun readDouble(separator: String = " ") =
    readDoubles(separator).first()

fun readTree(n: Int, indexing: Int = 1) =
    readGraph(n, n - 1, true, indexing)

fun readGraph(
    n: Int, m: Int,
    undirected: Boolean = true,
    indexing: Int = 1
): Graph {
    val builder = GraphBuilder()

    for (i in 1..m) {
        var (from, to) = readInts()

        from -= indexing
        to -= indexing

        if (undirected) builder.addEdge(from, to)
        else builder.addDirectedEdge(from, to)
    }

    return builder.build(n)
}

fun readWeightedGraph(
    n: Int, m: Int,
    undirected: Boolean = true,
    indexing: Int = 1
): WeightedGraph {
    val builder = GraphBuilder()

    for (i in 1..m) {
        var (from, to, weight) = readInts()

        from -= indexing
        to -= indexing

        if (undirected) builder.addEdge(from, to, weight)
        else builder.addDirectedEdge(from, to, weight)
    }

    return builder.buildWeighted(n)
}

fun readTotalEdges(m: Int, indexing: Int = 1) =
    TotalEdgeArray(m) {
        var (from, to, w) = readInts()

        from -= indexing
        to -= indexing

        Triple(from, to, w)
    }

class GraphBuilder {

    private val froms = ArrayList<Int>()
    private val tos = ArrayList<Int>()
    private val weights = ArrayList<Int>()

    fun addEdge(from: Int, to: Int, weight: Int = 1) {
        addDirectedEdge(from, to, weight)
        addDirectedEdge(to, from, weight)
    }

    fun addDirectedEdge(from: Int, to: Int, weight: Int = 1) {
        froms.add(from)
        tos.add(to)
        weights.add(weight)
    }

    private fun calculateFromSizes(n: Int): IntArray {
        val sizes = IntArray(n) { 0 }
        froms.forEach { ++sizes[it] }
        return sizes
    }

    fun build(n: Int): Graph {
        val sizes = calculateFromSizes(n)

        val graph = Graph(n) { IntArray(sizes[it]) { 0 } }

        for (i in 0 until n) {
            sizes[i] = 0
        }

        for (i in 0 until froms.size) {
            val from = froms[i]
            val to = tos[i]

            graph[from][sizes[from]++] = to
        }

        return graph
    }

    fun buildWeighted(n: Int): WeightedGraph {
        val sizes = calculateFromSizes(n)

        val graph = WeightedGraph(n) { EdgeArray(sizes[it]) { -1 to 0 } }

        for (i in 0 until n) {
            sizes[i] = 0
        }

        for (i in 0 until froms.size) {
            val from = froms[i]
            val to = tos[i]
            val weight = weights[i]

            graph[from][sizes[from]++] = to to weight
        }

        return graph
    }
}

fun checkIndex(index: Int, size: Int) =
    (index in 0..(size - 1))

fun checkCell(x: Int, n: Int, y: Int, m: Int) =
    checkIndex(x, n) && checkIndex(y, m)

fun toChar(index: Int, start: Char) =
    (index + start.toInt()).toChar()

class DSU {

    var sizes: IntArray
    var ranks: IntArray
    var parents: IntArray

    constructor(n: Int) : this(IntArray(n) { 1 })

    constructor(sizes: IntArray) {
        val size = sizes.size
        this.sizes = sizes
        this.ranks = IntArray(size) { 1 }
        this.parents = IntArray(size) { it }
    }

    operator fun get(v: Int): Int {
        val parent = parents[v]
        if (parent == v) return v
        parents[v] = get(parent)
        return parents[v]
    }

    fun union(aUniting: Int, bUniting: Int) {
        var a = get(aUniting)
        var b = get(bUniting)

        if (a == b) return

        if (ranks[a] < ranks[b]) {
            val tmp = a
            a = b
            b = tmp
        }

        parents[b] = a
        sizes[a] += sizes[b]
        if (ranks[a] == ranks[b]) ++ranks[a]
    }

    fun size(v: Int): Int = sizes[get(v)]
}

class FenwickTree(n: Int) {

    val size = n + 1
    val tree = LongArray(size) { 0L }

    fun update(index: Int, delta: Int) {
        var x = index + 1
        while (x < size) {
            tree[x] = tree[x] + delta
            x += x and -x
        }
    }

    fun get(start: Int, end: Int) =
        get(end) - get(start - 1)

    operator fun get(index: Int): Long {
        var result: Long = 0

        var x = index + 1
        println(x)
        while (x > 0) {
            result += tree[x]
            x -= x and -x
            println(x)
        }

        return result
    }
}


import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.max
import kotlin.math.min

fun readInt() = readLine()!!.toInt()

fun readLong() = readLine()!!.toLong()

fun readInts() = readLine()!!.split(' ').map(String::toInt).toIntArray()

fun readLongs() = readLine()!!.split(' ').map(String::toLong).toLongArray()

fun readInts(n: Int): IntArray {
    val a = IntArray(n)
    for (i in 0 until n) a[i] = readInt()
    return a
}

fun readLongs(n: Int): LongArray {
    val a = LongArray(n)
    for (i in 0 until n) a[i] = readLong()
    return a
}

fun readLines(n: Int): Array<String> {
    val s = Array(n) { "" }
    for (i in 0 until n) s[i] = readLine()!!
    return s
}

fun main() {
    val n = readInt()
    val a = readInts()
    val t = IntArray(43)
    t[4] = 0
    t[8] = 1
    t[15] = 2
    t[16] = 3
    t[23] = 4
    t[42] = 5
    val e = intArrayOf(4, 8, 15, 16, 23, 42)
    var res = 0
    val al = ArrayList<IntArray>()

    for (i in 0 until n) {
        if (a[i] == e[0]) {
            al.add(IntArray(6))
            al.get(al.size - 1)[0] = 1
        } else {
            for (ar in al) {
                if (ar[t[a[i]] - 1] == 1 && ar[t[a[i]]] == 0) {
                    ar[t[a[i]]] = 1
                    break
                }
//                else if (t[a[i]] >= 2 && ar[t[a[i]] - 2] == 0) ar[0] = -1
            }
        }
    }
    for (i in al) {
        if (i[5] == 1) res++
//        println(i.joinToString())
    }
    println(n - (res * 6))
}


import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.max
import kotlin.math.min

fun readInt() = readLine()!!.toInt()

fun readLong() = readLine()!!.toLong()

fun readInts() = readLine()!!.split(' ').map(String::toInt).toIntArray()

fun readLongs() = readLine()!!.split(' ').map(String::toLong).toLongArray()

fun readInts(n: Int): IntArray {
    val a = IntArray(n)
    for (i in 0 until n) a[i] = readInt()
    return a
}

fun readLongs(n: Int): LongArray {
    val a = LongArray(n)
    for (i in 0 until n) a[i] = readLong()
    return a
}

fun readLines(n: Int): Array<String> {
    val s = Array(n) { "" }
    for (i in 0 until n) s[i] = readLine()!!
    return s
}

fun main() {
    val n = readInt()
    val a = readInts()
    val t = IntArray(43)
    t[4] = 0
    t[8] = 1
    t[15] = 2
    t[16] = 3
    t[23] = 4
    t[42] = 5
    val e = intArrayOf(4, 8, 15, 16, 23, 42)
    var res = 0
    val al = ArrayList<IntArray>()

    for (i in 0 until n) {
        if (a[i] == e[0]) {
            al.add(IntArray(6))
            al.get(al.size - 1)[0] = 1
        } else {
            for (ar in al) {
                if (ar[t[a[i]] - 1] == 1) ar[t[a[i]]] = 1
            }
        }
    }
    for (i in al) {
        if (i[5] == 1) res++
    }
    println(n - (res * 6))
}


import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.max
import kotlin.math.min

fun readInt() = readLine()!!.toInt()

fun readLong() = readLine()!!.toLong()

fun readInts() = readLine()!!.split(' ').map(String::toInt).toIntArray()

fun readLongs() = readLine()!!.split(' ').map(String::toLong).toLongArray()

fun readInts(n: Int): IntArray {
    val a = IntArray(n)
    for (i in 0 until n) a[i] = readInt()
    return a
}

fun readLongs(n: Int): LongArray {
    val a = LongArray(n)
    for (i in 0 until n) a[i] = readLong()
    return a
}

fun readLines(n: Int): Array<String> {
    val s = Array(n) { "" }
    for (i in 0 until n) s[i] = readLine()!!
    return s
}

fun main() {
    val n = readInt()
    val a = readInts()
    val t = IntArray(43)
    val b = IntArray(43)
    t[4] = 0
    t[8] = 1
    t[15] = 2
    t[16] = 3
    t[23] = 4
    t[42] = 5
    val e = intArrayOf(4, 8, 15, 16, 23, 42)

    for (i in a) when {
        i == 4 -> {
            b[4]++
        }
        i == 8 && b[4] > 0 -> {
            b[4]--
            b[8]++
        }
        i == 15 && b[8] > 0 -> {
            b[8]--
            b[15]++
        }
        i == 16 && b[15] > 0 -> {
            b[15]--
            b[16]++
        }
        i == 23 && b[16] > 0 -> {
            b[16]--
            b[23]++
        }
        i == 42 && b[23] > 0 -> {
            b[23]--
            b[42]++
        }
    }
    println(n - b[42] * 6)
/*    var res = 0
    val al = ArrayList<IntArray>()
    val hm = HashMap<Int, Stack<Int>>()

    for (i in 0 until n) {
        if (a[i] == e[0]) {
            al.add(IntArray(6))
            al.get(al.size - 1)[0] = 1
            if (hm.containsKey(1)) {
                hm.get(1)!!.add(al.size - 1)
            }
        } else {
            val ar =
            for (ar in al) {
                if (ar[t[a[i]] - 1] == 1 && ar[t[a[i]]] == 0) {
                    ar[t[a[i]]] = 1
                    break
                }
            }
        }
    }
    for (i in al) {
        if (i[5] == 1) res++
    }*/
//    println(n - (res * 6))
}


fun main() {
    val n = readLine()!!.toInt()
    var a = readLine()!!.split(" ").map { it.toInt() }
    val idx = Array(50){0}
    idx[4] = 0
    idx[8] = 1
    idx[15] = 2
    idx[16] = 3
    idx[23] = 4
    idx[42] = 5
    var c = Array(6){0}
    var ans = n
    for (ai in a) {
        if (ai == 4) c[0]++
        else {
            if (c[idx[ai] - 1] > 0) {
                c[idx[ai] - 1]--
                c[idx[ai]]++
                if (ai == 42) ans -= 6
            }
        }
    }
    println(ans)
}


package Round565

// 4, 8, 15, 16, 23, 42
fun main() {
    val n = readLine()!!.toInt()
    var a = readLine()!!.split(" ").map { it.toInt() }
    val idx = Array(50){0}
    idx[4] = 0
    idx[8] = 1
    idx[15] = 2
    idx[16] = 3
    idx[23] = 4
    idx[42] = 5
    var c = Array(6){0}
    var ans = n
    for (ai in a) {
        if (ai == 4) c[0]++
        else {
            if (c[idx[ai] - 1] > 0) {
                c[idx[ai] - 1]--
                c[idx[ai]]++
                if (ai == 42) ans -= 6
            }
        }
    }
    println(ans)
}


fun main() {
    readLine()
    val a = readLine()!!.split(" ").map { it.toInt() }
    var sequences = 0
    val cursors = mutableMapOf(1 to 0, 2 to 0, 3 to 0, 4 to 0, 5 to 0)

    for (elem in a) {
        when (elem) {
            4 -> cursors[1] = cursors[1]!! + 1
            8 -> if (cursors[1]!! > 0) {
                cursors[1] = cursors[1]!! - 1
                cursors[2] = cursors[2]!! + 1
            }
            15 -> if (cursors[2]!! > 0) {
                cursors[2] = cursors[2]!! - 1
                cursors[3] = cursors[3]!! + 1
            }
            16 -> if (cursors[3]!! > 0) {
                cursors[3] = cursors[3]!! - 1
                cursors[4] = cursors[4]!! + 1
            }
            23 -> if (cursors[4]!! > 0) {
                cursors[4] = cursors[4]!! - 1
                cursors[5] = cursors[5]!! + 1
            }
            42 -> if (cursors[5]!! > 0) {
                cursors[5] = cursors[5]!! - 1
                sequences++
            }
        }
    }

    println(a.size - sequences * 6)
}


fun main() {

    var n = readLine()!!.toInt()
    var a = readLine()!!.split(" ").map { it.toInt() }

    var items = listOf(4, 8, 15, 16, 23, 42)
    var q = mutableListOf(0,0,0,0,0,0)

    var trash = 0
    for (i in a){
        val j = items.indexOf(i)

        if(j == 0 || q[j - 1] > q[j]){
            q[j]++
        }else{
            trash++
        }
    }

    for(i in q){
        trash += i - q.last()
    }

    println(trash)

}


@file:JvmName("programkt")

fun main() {
    val n = readInt()

    val array = Array(6) { 0 }
    var parasha = 0

    for (int in readInts()) {
        val num = map(int)

        if (num == 0) {
            array[0]++
        } else {
            if (array[num - 1] != 0) {
                array[num - 1]--
                array[num]++
            } else {
                parasha++
            }
        }
    }

    for (i in 0 until 5) {
        parasha += array[i] * (i + 1)
    }

    println(parasha)
}

fun map(int: Int) = when (int) {
    4 -> 0
    8 -> 1
    15 -> 2
    16 -> 3
    23 -> 4
    42 -> 5
    else -> TODO()
}

fun readInt() = readLine()!!.toInt()
fun readInts() = readLine()!!.split(" ").map { it.toInt() }