HDU 3715 Go Deeper

时间:2023-03-09 23:50:37
HDU 3715 Go Deeper

二分答案 + 2-SAT判断

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std; const int maxn=+;
int M,N,T;
int ans;
int L,R,Mid;
int a[],b[],c[]; struct TwoSAT
{
int n;
vector<int> G[maxn*];
bool mark[maxn*];
int S[maxn*],c; bool dfs(int x)
{
if(mark[x^]) return false;
if(mark[x]) return true;
mark[x]=true;
S[c++]=x;
for(int i=;i<G[x].size();i++)
if(!dfs(G[x][i])) return false;
return true;
} void init(int n)
{
this->n=n;
for(int i=;i<n*;i++) G[i].clear();
memset(mark,,sizeof mark);
} void add_clause(int x,int y)
{
G[x].push_back(y^);
G[y].push_back(x^);
} bool solve()
{
for(int i=;i<*n;i+=)
if(!mark[i]&&!mark[i+])
{
c=;
if(!dfs(i))
{
while(c>) mark[S[--c]]=false;
if(!dfs(i+)) return false;
}
}
return true;
}
}; int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&N,&M);
for(int i=;i<M;i++)
scanf("%d%d%d",&a[i],&b[i],&c[i]);
L=,R=M; while(L<=R)
{
Mid=(L+R)/;
TwoSAT T; T.init(N);
for(int i=;i<Mid;i++)
{
if(c[i]==)
{
T.add_clause(*a[i]+,*b[i]+);
}
else if(c[i]==)
{
T.add_clause(*a[i]+,*b[i]);
T.add_clause(*a[i],*b[i]+);
}
else if(c[i]==)
{
T.add_clause(*a[i],*b[i]);
}
}
if(T.solve())
{
ans=Mid;
L=Mid+;
}
else R=Mid-;
}
printf("%d\n",ans);
}
return ;
}