tarjan+topo+dp90tle
查看原帖
tarjan+topo+dp90tle
752257
Miangoa楼主2024/6/28 17:24
#include<bits/stdc++.h>
#define fi first
#define se second
#define int long long
#define inf 0x3f3f3f3f3f3f3f3f

using namespace std;

int n,k;
int h[100010],e[200010][3],cnt;
int c[100010],ans;
int dfn[100010],low[100010],mtn;
bool vis[100010];
int ns,bel[100010];
int nh[100010],ne[200010][3],ncnt;
int rd[100010];
stack<int> sta;

inline int read() {
	int f=1,x=0;
	char ch=getchar();
	while(ch<'0'||ch>'9')	f=(ch=='-'?-1:f),ch=getchar();
	while(ch>='0'&&ch<='9')	x=x*10+ch-'0',ch=getchar();
	return f*x;
}

void add(int a,int b,int c) {
	e[++cnt][0]=b;
	e[cnt][1]=h[a];
	e[cnt][2]=c;
	h[a]=cnt;
}

void nadd(int a,int b,int c) {
	ne[++ncnt][0]=b;
	ne[ncnt][1]=nh[a];
	ne[ncnt][2]=c;
	nh[a]=ncnt;
	rd[b]++;
}

void dfs(int p) {
	sta.push(p);
	dfn[p]=low[p]=++mtn;
	vis[p]=true;
	for(int i=h[p]; i; i=e[i][1]) {
		if(!vis[e[i][0]])	dfs(e[i][0]);
		low[p]=min(low[p],low[e[i][0]]);
	}
	if(low[p]!=dfn[p])	return;
	++ns;
	while(!sta.empty()) {
		int th=sta.top();
		sta.pop();
		bel[th]=ns;
		vis[th]=false;
		if(th==p)	break;
	}
}

bool rebuild() {
	for(int i=1; i<=n; i++)
		for(int j=h[i]; j; j=e[j][1])
			if(bel[i]!=bel[e[j][0]])
				nadd(bel[i],bel[e[j][0]],e[j][2]);
			else if(bel[i]==bel[e[j][0]]&&e[j][2]==1)
				return false;
	return true;
}

bool tarjan() {
	for(int i=1; i<=n; i++)
		if(!dfn[i])
			dfs(i);
	return rebuild();
}

int topo() {
	queue<int> que;
	for(int i=1; i<=ns; i++)
		if(!rd[i]) {
			c[i]=1;
			que.push(i);
		}
	while(!que.empty()) {
		int th=que.front();
		que.pop();
		for(int i=nh[th]; i; i=ne[i][1]) {
			rd[ne[i][0]]--,c[ne[i][0]]=max(c[ne[i][0]],c[th]+ne[i][2]);
			if(!rd[ne[i][0]])	que.push(ne[i][0]);
		}
	}
	for(int i=1; i<=n; i++)	ans+=c[bel[i]];
	return ans;
}

signed main() {
	n=read(),k=read();
	while(k--) {
		int x=read(),a=read(),b=read();
		if(x==1)	add(a,b,0),add(b,a,0);
		else if(x==2)	add(a,b,1);
		else if(x==3)	add(b,a,0);
		else if(x==4)	add(b,a,1);
		else if(x==5)	add(a,b,0);
	}
	if(tarjan())	printf("%lld",topo());
	else	printf("-1");
}
2024/6/28 17:24
加载中...