#include <cmath>
#include <queue>
#include <cstdio>
#include <map>
#include <vector>
#include <iostream>
#include <stack>
#include <climits>
#include <set>
#include <queue>
#include <algorithm>
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef long double ld;
typedef set<int>::iterator sit;
typedef map<int,int>::iterator mit;
typedef vector<int>::iterator vit;
const int N = 100001;
const int MOD = 1e9 + 7;
bool pairCompare(const std::pair<int,pair<int,int>>& firstElem, const std::pair<int,pair<int,int>>& secondElem) {
return firstElem.first < secondElem.first;
}
void initialize(int size[], int Arr[ ], int N)
{
for(int i = 0;i<N;i++)
{
Arr[ i ] = i ;
size[ i ] = 1;
}
}
int root (int Arr[ ] ,int i)
{
while(Arr[ i ] != i)
{
Arr[ i ] = Arr[ Arr[ i ] ] ;
i = Arr[ i ];
}
return i;
}
/*modified union function where we connect the elements by changing the root of one of the element */
/*
void unio(int Arr[ ] ,int A ,int B)
{
int root_A = root(Arr, A);
int root_B = root(Arr, B);
Arr[ root_A ] = root_B ; //setting parent of root(A) as root(B).
}
*/
void weightedunio(int Arr[ ],int size[ ],int A,int B)
{
int root_A = root(Arr, A);
int root_B = root(Arr, B);
if(size[root_A] < size[root_B ])
{
Arr[ root_A ] = Arr[root_B];
size[root_B] += size[root_A];
}
else
{
Arr[ root_B ] = Arr[root_A];
size[root_A] += size[root_B];
}
}
bool find(int Arr[], int A,int B)
{
if( root(Arr, A)==root(Arr, B) ) //if A and B have same root,means they are connected.
return true;
else
return false;
}
int main(int argc, const char * argv[]) {
int n, m;
cin>>n>>m;
vector<pair<int,pair<int,int>>> adj;
for(int i = 0; i < m; i++){
int a,b,c;
cin>>a>>b>>c; a--; b--;
adj.push_back(mp(c,mp(a,b)));
}
int q;
cin>>q;
for(int i = 0; i < q; i++){
int s,t;
cin>>s>>t;s--;t--;
adj.push_back(mp(0,mp(s,t)));
sort(adj.begin(), adj.end(), pairCompare);
int ans = 0;
int size[n], arr[n];
initialize(size, arr, n);
for(int i = 0; i <= m; i++){
if(!find(arr, adj[i].second.first, adj[i].second.second)){
ans += adj[i].first;
weightedunio(arr,size,adj[i].second.first, adj[i].second.second);
}
}
cout<<ans<<endl;
}
/*
4 3
1 2 3
2 3 4
3 4 5
1
2 3*/
return 0;
}