#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef long double ld;
#define PATH "D:\\QtProjects\\olymp\\"
const int N = 10001;
const int M = 100000;
int head[N], thead[N];
int linke[M];
int cap[M];
int dest[M];
int sz;
int used[N];
int curused;
inline void init(){
memset(linke, -1, sizeof(linke));
memset(head, -1, sizeof(head));
memset(used, -1, sizeof(used));
//fill(linke, linke + M, -1);
//fill(head, head + N, -1);
//fill(used, used + N, -1);
curused = 0;
sz = 0;
}
inline void addarc(const int frm, const int to, const int capacity){
dest[sz] = to;
linke[sz] = head[frm];
head[frm] = sz;
cap[sz] = capacity;
++sz;
}
inline void addedge(const int frm, const int to, const int capacity){
addarc(frm, to, capacity);
addarc(to, frm, 0);
}
int S, T;
int lvl[N];
inline int dfs(int v, int f){
if (v == T) return f;
int ans = 0;
for (int& arc = thead[v]; arc != -1 && f > 0; arc = linke[arc]){
int u = dest[arc];
if (cap[arc] && lvl[u] == lvl[v] + 1){
int curf = dfs(u, min(f, cap[arc]));
if (curf){
cap[arc] -= curf;
cap[arc ^ 1] += curf;
//return curf;
f -= curf;
ans += curf;
}
}
}
return ans;
}
const int INF = 2e9;
int q[N + 5];
inline bool bfs(const int mCap = 1){
int l = 0;
int r = 1;
memset(lvl, -1, sizeof(lvl));
lvl[S] = 0;
//from[S] = -1;
q[0] = S;
while (l != r){
int v = q[l++];
//int v = q.front(); q.pop();
for (int arc = head[v]; arc != -1; arc = linke[arc]){
int u = dest[arc];
if (cap[arc] >= mCap && lvl[u] == -1){
//from[u] = arc;
lvl[u] = lvl[v] + 1;
q[r++] = u;
}
}
}
return lvl[T] != -1;
}
int main(){
freopen(PATH"input.txt", "r", stdin);
//freopen("partition.in", "r", stdin);
//freopen("partition.out", "w", stdout);
//ios_base::sync_with_stdio(false);
init();
int n; scanf("%d\n", &n);
S = 0; T = n - 1;
for (int i = 0, t1, t2; i < n; ++i) scanf("%d%d", &t1, &t2);
int m; scanf("%d", &m);
for (int i = 0; i < m; ++i){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
//cin >> a >> b >> c;
--a; --b;
addarc(a, b, c);
addarc(b, a, c);
}
int sum = 0;
while (bfs()){
memcpy(thead, head, sizeof(head));
for (int t = dfs(S, INF); t != 0; t = dfs(S, INF)){
//++curused;
sum += t;
}
}
printf("%d\n", sum);
for (int arc = 0; arc < sz; arc += 2){
if (cap[arc] < cap[arc ^ 1]){
int to = dest[arc] + 1;
int fr = dest[arc ^ 1] + 1;
int f = (cap[arc ^ 1] - cap[arc]) / 2;
printf("%d %d %d\n", fr, to, f);
//cout << fr << ' ' << to << ' ' << f << '\n';
}
else
{
int to = dest[arc ^ 1] + 1;
int fr = dest[arc] + 1;
int f = (cap[arc] - cap[arc ^ 1]) / 2;
printf("%d %d %d\n", fr, to, f);
//cout << fr << ' ' << to << ' ' << f << '\n';
}
}
//cout.flush();
return 0;
}