1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| #include <bits/stdc++.h> using namespace std; const int LEN = 1e5 + 50; int n, m, cnt, fa[LEN], val[LEN], discrete[LEN];
struct node { int x_, y_, w_; } arr[LEN];
int find(int x) { if (fa[x] == x) return x; int anc = fa[x]; fa[x] = find(fa[x]); val[x] ^= val[anc]; return fa[x]; }
void join(int x, int y, int w) { int a = find(x), b = find(y); val[a] = w ^ val[y] ^ val[x]; fa[a] = b; }
void init() { sort(discrete + 1, discrete + 1 + cnt); cnt = unique(discrete + 1, discrete + 1 + cnt) - (discrete + 1); for (int i = 1; i <= m; ++i) { arr[i].x_ = lower_bound(discrete + 1, discrete + 1 + cnt, arr[i].x_) - discrete; arr[i].y_ = lower_bound(discrete + 1, discrete + 1 + cnt, arr[i].y_) - discrete; } for (int i = 0; i <= cnt; ++i) fa[i] = i; }
void work() { int x, y, w; for (int i = 1; i <= m; ++i) { x = arr[i].x_, y = arr[i].y_, w = arr[i].w_; --x; if (find(x) != find(y)) { join(x, y, w); } else { if (val[x] ^ val[y] != w) { cout << i - 1 << endl; return; } } } cout << m << endl; }
int main() { string str; cin >> n >> m; for (int i = 1; i <= m; ++i) { cin >> arr[i].x_ >> arr[i].y_ >> str; arr[i].w_ = str[0] == 'e' ? 0 : 1; discrete[++cnt] = arr[i].x_, discrete[++cnt] = arr[i].y_; } init(), work(); return 0; }
|