求助,悬关
查看原帖
求助,悬关
931707
017_007楼主2023/7/20 21:08

个人认为这种做法很合理,但是就是错了,希望路过的dalao稍微指点。

#include<bits/stdc++.h>
#include<stack>

#define reg register

using namespace std;

inline int read() {
	int x=0,f=1;char s=getchar();
	while (s>'9'||s<'0') {
		if (s=='-') f=-f;
		s=getchar();
	}
	while (s>='0'&&s<='9') {
		x=(x<<3)+(x<<1)+(s-'0');
		s=getchar();
	}
	return x*f;
}

const int N = 2010;

int n,first[N],cnt,dfn[N],low[N],now,tot,belong[N];
bool instack[N];
stack<int>s;
int New[N],num[N],Nfirst[N],Ncnt,in[N];
struct edge{
	int to,nxt;
}edges[N*N],Nedges[N*N];
char k;

void add(int u,int v) {
	edges[++cnt].to=v;
	edges[cnt].nxt=first[u];
	first[u]=cnt;
}

void dfs(int root) {
	dfn[root]=low[root]=++now;
	s.push(root);instack[root]=true;
	for (reg int t=first[root];t;t=edges[t].nxt) {
		int h=edges[t].to;
		if (!dfn[h]) dfs(h),low[root]=min(low[root],low[h]);
		else if (instack[h]) low[root]=min(low[root],low[h]);
	}
	if (dfn[root]==low[root]) {
		tot++;
		while (1) {
			int h=s.top();s.pop();
			//printf("%d ",h);
			belong[h]=tot;instack[h]=false;
			if (h==root) break;
		}
		//printf("\n");
	}
	return ;
}

void Nadd(int u,int v) {
	Nedges[++Ncnt].to=v;
	Nedges[Ncnt].nxt=Nfirst[u];
	Nfirst[u]=Ncnt;
}

void pope() {
	queue<int>sx;
	for (reg int i=1;i<=tot;++i) if (!in[i]) sx.push(i);
	while (!sx.empty()) {
		int root=sx.front();sx.pop();
		for (int t=Nfirst[root];t;t=Nedges[t].nxt) {
			int h=Nedges[t].to;
			in[h]--;New[h]+=New[root];
			if (!in[h]) sx.push(h);
		}
	}
}

int main(){
	n=read();
	for (reg int i=1;i<=n;++i) {
		for (reg int j=1;j<=n;++j) {
			cin>>k;
			if (k=='1') add(i,j);
		}
	}
	for (reg int i=1;i<=n;++i) if (!dfn[i]) dfs(i);
	for (reg int i=1;i<=n;++i) New[belong[i]]++,num[belong[i]]++;
	//for (reg int i=1;i<=tot;++i) printf("New[%d]=%d\n",i,New[i]);
	for (reg int i=1;i<=n;++i) {
		for (reg int t=first[i];t;t=edges[t].nxt) {
			int h=edges[t].to;
			if (belong[i]==belong[h]) continue;
			in[belong[i]]++;Nadd(belong[h],belong[i]);
		}
	}
	pope();
	int ans=0;
	for (reg int i=1;i<=tot;++i) ans+=New[i]*num[i];
	printf("%d\n",ans);	
	return 0;
}

2023/7/20 21:08
加载中...