#include <iostream>
#define INF 1000000000
using namespace std;
int dis[5010][5010];
int gedi(int x,int y){
	if(x>y) return dis[y][x];
	else return dis[x][y];
}

void sedi(int x,int y,int v){
	if(x>y) dis[y][x]=v;
	else dis[x][y]=v;
}
int N;
void wf(){
	for(int k=0;k<N;k++){
		for(int i=0;i<N;i++){
			for(int j=i;j<N;j++){
				sedi(i,j,min(gedi(i,j),gedi(i,k)+gedi(k,j)));
			}
		}
	}
}

int main(){
	int K,hog,bak,aho,kso;
	while(1){
		cin>>N>>K;
		if(N==0&&K==0) break;
		for(int i=0;i<N;i++){
			for(int j=0;j<N;j++){
				dis[i][j]=INF;
			}
		}
		for(int i=0;i<K;i++){
			////
			//for(int i=0;i<N;i++){
			//	for(int j=0;j<N;j++){
			//		cout<<"dis["<<i<<"]["<<j<<"]="<<gedi(i,j)<<" ";
			//	}
			//	cout<<endl;
			//}
			////
			cin>>hog;
			if(hog==0){
				cin>>bak>>aho;
				bak--;aho--;
				if(gedi(bak,aho)!=INF){
					cout<<gedi(bak,aho)<<endl;
				}
				else{
					cout<<-1<<endl;
				}
			}
			else{
				cin>>bak>>aho>>kso;
				bak--;aho--;
				if(gedi(bak,aho)>kso){
					sedi(bak,aho,kso);
					wf();
				}
			}
		}
	}
	return 0;
}