#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int bin[20];
int n,m,K,lastans=1,cnt;
int fa[200005][18],mx[200005][18],deep[200005];
int f[200005],last[200005],father[200005],q[200005];
bool vis[200005];
struct edge{int to,next,v;}e[400005];
struct data{int x,y,w;}a[300005];
inline bool operator<(data a,data b)
{
return a.w<b.w;
}
inline void ins(int u,int v,int w)
{
e[++cnt].to=v;e[cnt].next=last[u];last[u]=cnt;e[cnt].v=w;
}
inline void insert(int u,int v,int w)
{
ins(u,v,w);ins(v,u,w);
}
int find(int x)
{
return x==father[x]?x:father[x]=find(father[x]);
}
void pre()
{
int head=0,tail=1;
q[0]=1;vis[1]=1;
while(head!=tail)
{
int now=q[head];head++;
for(int i=1;i<=17;i++)
if(deep[now]>=bin[i])
{
fa[now][i]=fa[fa[now][i-1]][i-1];
mx[now][i]=max(mx[now][i-1],mx[fa[now][i-1]][i-1]);
}
else break;
for(int i=last[now];i;i=e[i].next)
{
if(vis[e[i].to])continue;
vis[e[i].to]=1;
deep[e[i].to]=deep[now]+1;
fa[e[i].to][0]=now;
mx[e[i].to][0]=e[i].v;
q[tail++]=e[i].to;
}
}
}
int query(int x,int y)
{
int tmp=0;
if(deep[x]<deep[y])swap(x,y);
int t=deep[x]-deep[y];
for(int i=0;i<=17;i++)
if(bin[i]&t)
{
tmp=max(tmp,mx[x][i]);
x=fa[x][i];
}
for(int i=17;i>=0;i--)
if(fa[x][i]!=fa[y][i])
{
tmp=max(tmp,mx[x][i]);
tmp=max(tmp,mx[y][i]);
x=fa[x][i];y=fa[y][i];
}
if(x!=y)
{
tmp=max(tmp,mx[x][0]);
tmp=max(tmp,mx[y][0]);
}
return tmp;
}
int main()
{
bin[0]=1;for(int i=1;i<20;i++)bin[i]=(bin[i-1]<<1);
n=read();m=read();
for(int i=1;i<=n;i++)father[i]=i;
for(int i=1;i<=m;i++)
a[i].x=read(),a[i].y=read(),a[i].w=read();
sort(a+1,a+m+1);
int tot=0;
for(int i=1;;i++)
{
int p=find(a[i].x),q=find(a[i].y);
if(p!=q)
{
insert(a[i].x,a[i].y,a[i].w);
father[p]=q;
tot++;
if(tot==n-1)break;
}
}
pre();
K=read();
for(int i=1;i<=K;i++)
{
int p1=read(),p2=read(),q1=read(),q2=read();
int x=(ll)(lastans+p1)*p2%n+1;
int y=(ll)(lastans+q1)*q2%n+1;
lastans=query(x,y);
printf("%d\n",lastans);
}
return 0;
}