3 2 1 0 1 0 2 1 0 0 0 2 2 0 1 0 1 1 2
1 1 2
#include <iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<vector> #include<queue> #include<stack> using namespace std; typedef long long ll; const int inf=0x3f3f3f3f; const int M=10022; const int N=422; int a[10022],b[10022],c[10022]; vector<int> g[N*2]; #define pb push_back int cnt,curr,f[N*2],dfn[N],low[N]; bool instack[N*2]; stack<int> s; int n,m; void dfs(int u) { dfn[u]=low[u]=++curr; s.push(u); instack[u]=1; for(int i=0;i<g[u].size();i++) { int v=g[u][i]; if(!dfn[v]) { dfs(v); low[u]=min(low[u],low[v]); }else{ if(instack[v]) low[u]=min(low[u],dfn[v]); } } if(low[u]==dfn[u]) { ++cnt; int v; do{ v=s.top(); s.pop(); instack[v]=0; f[v]=cnt; }while(v!=u); } } bool sat(int ans) { int i,j,k; cnt=curr=0; while(!s.empty())s.pop(); memset(dfn,0,sizeof dfn); memset(low,0,sizeof low); memset(instack,0,sizeof instack); memset(f,0,sizeof f); for(i=0;i<2*n;i++)g[i].clear(); for(i=0;i<ans;i++) { if(c[i]==0) { g[a[i]].pb(b[i]+n); g[b[i]].pb(a[i]+n); } if(c[i]==1) { g[a[i]].pb(b[i]); g[b[i]].pb(a[i]); g[a[i]+n].pb(b[i]+n); g[b[i]+n].pb(a[i]+n); } if(c[i]==2) { g[a[i]+n].pb(b[i]); g[b[i]+n].pb(a[i]); } } for(i=0;i<2*n;i++) if(!dfn[i])dfs(i); for(i=0;i<n;i++) if(f[i]==f[i+n])return 0; return 1; } int main() { int T;cin>>T; while(T--) { cin>>n>>m; for(int i=0;i<m;i++)cin>>a[i]>>b[i]>>c[i]; int l=0,r=m,mid; while(l<r) { mid=(l+r+1)/2; if(sat(mid))l=mid; else r=mid-1; } cout<<l<<endl; } }