| #include<iostream> #include<cstdio> #include<algorithm> using namespace std; #define LL long long LL n,m,tot,t,w,now,x,y,z,ans; LL head[100030],q[100030],vis[100030],cir[100030],dis[100030]; struct edge{ 	LL u,v,dis,last; } e[400030]; void add(LL x,LL y,LL z){ 	tot++; 	e[tot].u=x; 	e[tot].v=y; 	e[tot].dis=z; 	e[tot].last=head[x]; 	head[x]=tot; } bool spfa(){ 	q[1]=0; 	vis[0]=1; 	cir[0]=1; 	t=0; 	w=1; 	while (t!=w){ 		t=t%(n+10)+1; 		now=q[t]; 		for (int i=head[now];i;i=e[i].last) 			if (dis[e[i].v]<dis[now]+e[i].dis){ 				dis[e[i].v]=dis[now]+e[i].dis; 				if (++cir[e[i].v]>n) return 0; 				if (!vis[e[i].v]){ 					vis[e[i].v]=1; 					w=w%(n+10)+1; 					q[w]=e[i].v; 				} 			} 		vis[now]=0; 	} 	return 1; } int main(){ 	scanf("%lld%lld",&n,&m); 	 	for (int i=n;i>0;i--) add(0,i,1); 	 	for (int i=1;i<=m;i++){ 		scanf("%lld%lld%lld",&x,&y,&z); 		if (x==1){ add(y,z,0); add(z,y,0); } 		if (x==2){ 			if (y==z){ printf("-1\n"); return 0; } 			add(y,z,1); 		} 		if (x==3) add(z,y,0); 		if (x==4){ 			if (y==z){ printf("-1\n"); return 0; } 			add(z,y,1); 		} 		if (x==5) add(y,z,0); 	} 	 	if (!spfa()){ 		printf("-1\n"); 		return 0; 	} 	for (int i=1;i<=n;i++) ans+=dis[i]; 	printf("%lld\n",ans); 	 	return 0; }
 |