
class abc_157:
    
    def __init__(self):
        pass
    
    def A(self):
       N=int(input())
       print(int(N/2)+(N%2))
    
    def B(self):
        A=[list(map(int,input().split())) for i in range(3)]
        N=int(input())
        
        B=[]
        for i in range(N):B.append(int(input()))
        
        
            
    def C(self):
        NM=list(map(int,input().split()))
        sc=[list(map(int,input().split())) for i in range(NM[1])]
        farst,second,third,full=[],[],[],[]
        division_list=[10**i for i in range(3)]
        ans=0
        
        for i in sc:
            if i[0]==1:farst.append(i)
            elif i[0]==2:second.append(i)
            else :third.append(i)
        
        sort_func=lambda val:val[1]
        farst.sort(key=sort_func)
        second.sort(key=sort_func)
        third.sort(key=sort_func)
        
        if farst:ans+=(10**(3-farst[0][0]))*farst[0][1]
        if second:ans+=(10**(3-second[0][0]))*second[0][1]
        if third:ans+=(10**(3-third[0][0]))*third[0][1]
        
        if int(ans/division_list[NM[0]-1])!=0:print(ans)
        else:print("-1")
            
    def D(self):
        S=input()
        Q=int(input())
        Q_list=[list(input().split()) for i in range(Q)]
        
        d=deque()
        top=True
        end=False
        count_revers=0
        
        d.append(S)
        for i in Q_list:
            #Ti==1
            if int(i[0])==1:
                count_revers+=1
                if top==True:
                    top=False
                    end=True
                else:
                    top=True
                    end=False
            #Ti==2
            else:
                #Fi==1
                if int(i[1])==1 :
                    if top==True:d.appendleft(i[2])
                    else:d.append(i[2])
                #Fi==2
                else :
                    if top==True:d.append(i[2])
                    else:d.appendleft(i[2])
                
                
        ans = "".join(list(d)) if count_revers%2==0 else  "".join(list(d))[::-1]
        print(ans)
        
    def E(self):
        pass
    
    def F(self):
        pass
    
    
if __name__=='__main__':
    obj=abc_157()
    obj.C()