1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111。
#include <bits/stdc++.h>
#define pb push_back
#define LL long long
using namespace std;
const int N = 5e5 + 5, inf = 1e9;
int n, Q, f[N][20], lg[N], ct, ct2, dep[N], maxd = -1, fqi[N];
LL qz[N], ans[N];
struct Node{
int to, w;
};
struct jb{
int cz, x, y, w;
} a[N];
struct cx{
int cz, x, y;
} b[N];
vector <Node> ed[N];
void dfs(int x, int fa){
dep[x] = dep[fa] + 1, f[x][0] = fa;
if(dep[x] > maxd) maxd = dep[x];
for(auto i : ed[x]){
int tod = i.to;
if(tod != fa){
qz[tod] = qz[x] + i.w;
dfs(tod, x);
}
}
}
int lca(int u, int v){
if(dep[u] < dep[v]) swap(u, v);
while(dep[u] > dep[v]){
u = f[u][lg[dep[u] - dep[v]]];
}
if(u == v) return u;
for(int i = lg[dep[u]];i >= 0;i--){
if(f[u][i] != f[v][i]){
u = f[u][i], v = f[v][i];
}
}
return f[u][0];
}
int fin(int x){
if(fqi[x] == x) return x;
fqi[x] = fin(fqi[x]);
return fqi[x];
}
void he(int x, int y){
int z1 = fin(x), z2 = fin(y);
if(z1 != z2) fqi[z1] = z2;
}
int main(){
scanf("%d%d", &n, &Q);
for(int i = 1;i <= n;i++) fqi[i] = i;
for(int i = 2;i <= n;i++) lg[i] = lg[i / 2] + 1;
for(int i = 1;i <= Q;i++){
int x, y;
scanf("%d%d", &x, &y);
char ch = getchar();
if(ch == ' '){
int w;
scanf("%d", &w);
a[++ct] = (jb) {i, x, y, w};
he(x, y);
} else{
b[++ct2] = (cx) {i, x, y};
if(fin(x) != fin(y)) ans[ct2] = -1;
}
}
for(int i = 1;i <= ct;i++){
int x = a[i].x, y = a[i].y, w = a[i].w;
ed[x].pb((Node) {y, w}), ed[y].pb((Node) {x, w});
}
dfs(1, 0);
for(int j = 1;j <= lg[maxd];j++){
for(int i = 1;i <= n;i++){
f[i][j] = f[f[i][j - 1]][j - 1];
}
}
for(int i = 1;i <= ct2;i++){
int x = b[i].x, y = b[i].y;
int lc = lca(x, y);
if(ans[i] != -1){
ans[i] = qz[x] + qz[y] - 2 * qz[lc];
}
}
for(int i = 1;i <= ct2;i++){
printf("%lld\n", ans[i]);
}
return 0;
}
/*
4 7
1 3
1 3 100
2 3 200
1 3
1 2
2 3
1 4
*/