#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <cstring>
#include <map>
#include <utility>
#include <set>
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <functional>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <array>
#include <cassert>
#include <bitset>
using namespace std;
using LL = long long;

int N, M, K;
vector<int>par;
void init() {
	par.clear();
	for (int i = 0; i < N + M; ++i) {
		par.push_back(i);
	}
}
int getpar(int x) {
	if (x == par[x])return x;
	return par[x] = getpar(par[x]);
}
bool unite(int a, int b) {
	a = getpar(a);
	b = getpar(b);
	if (a == b)return true;
	if (a >= N && b >= N)return false;
	if (a >= N) {
		par[b] = a;
	}
	else {
		par[a] = b;
	}
	return true;
}
bool unite2(int c, int x) {
	c = getpar(c);
	x = getpar(x);
	if (c == x)return true;
	if (c >= N)return false;
	par[c] = x;
	return true;
}

int main(void)
{
	cin >> N >> M >> K;
	init();
	for (int i = 0; i < K; ++i) {
		int t, v1, v2;
		cin >> t >> v1 >> v2;
		--v1; --v2;
		if (t == 1) {
			if (!unite(v1, v2)) {
				cout << i + 1 << endl;
				return 0;
			}
		}
		else {
			if (!unite2(v1, v2 + N)) {
				cout << i + 1 << endl;
				return 0;
			}
		}
	}
	cout << 0 << endl;
	return 0;
}


