P3387 【模板】缩点 40pts求调
  • 板块灌水区
  • 楼主PCCP
  • 当前回复7
  • 已保存回复7
  • 发布时间2022/11/13 11:50
  • 上次更新2023/10/27 03:08:03
查看原帖
P3387 【模板】缩点 40pts求调
310773
PCCP楼主2022/11/13 11:50

40pts,#2,6,8,9,10 TLE;#4 WA。蒟蒻太菜了,模板调了一上午都没有调出来,求大佬帮忙看看哪里有问题,我估计是拓扑有问题,但是没有找到(

#include<iostream>
#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
using namespace std;
const int N=1e4+10;
int n,m,w[N],ans=-1e9;
int he[N<<1],ne[N<<1],to[N<<1],tot=0;
void addedge(int x,int y){
	to[++tot]=y;
	ne[tot]=he[x];
	he[x]=tot;
}
int her[N<<1],ner[N<<1],tor[N<<1],wr[N];
void add(int x,int y){
	tor[++tot]=y;
	ner[tot]=her[x];
	her[x]=tot;
}
stack <int> q;
vector <int> scc[N];
int cnt,scccnt,dfo[N],low[N],rootid[N],root[N],in[N],dist[N];
bool st[N];
//tarjan后要新建一个图,表示缩点后的图 
void tarjan(int now){
	dfo[now]=low[now]=++cnt;
	q.push(now);
	st[now]=1;
	for(int i=he[now];i;i=ne[i]){
		int v=to[i];
		if(!dfo[v]){
			tarjan(v);
			low[now]=min(low[v],low[now]);
		}
		else if(dfo[v]&&st[v]==1){
			low[now]=min(low[now],dfo[v]);
		}
	}
	if(dfo[now]==low[now]){
		++scccnt;
		for(int i=1;i;i++){
			scc[scccnt].push_back(q.top());
			st[q.top()]=0;
			rootid[q.top()]=scccnt;
			wr[scccnt]+=w[q.top()];
			//新图内一个点的权值等于相对应的原图强连通分量的权值之和 
			q.pop();
			if(scc[scccnt].back()==now){
				root[scccnt]=now;
				break;
			}
		}
	}
}
int tpo[N],tpocnt;
void tuopu(){
	queue <int> heap;
	for(int i=1;i<=scccnt;i++){
		if(in[i]==0){
			heap.push(i);
			dist[i]=wr[i];
		}
	}
	while(heap.size()){
		int t=heap.front();
		heap.pop();
		tpo[++tpocnt]=t;
		for(int i=her[t];i;i=ner[i]){
			int v=tor[i];
			in[v]--;
			if(in[v]<=0){
				dist[v]=max(dist[v],dist[t]+wr[v]);
				//这里要用新图的权值,不要把wr写成w 
				heap.push(v);
				//这里的heap不能和q重了 
			}
		}
	}
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		scanf("%d",&w[i]);
	}
	int x,y;
	for(int i=1;i<=m;i++){
		scanf("%d%d",&x,&y);
		addedge(x,y);
	}
	for(int i=1;i<=n;i++){
		if(!dfo[i]){
			tarjan(i); 
		}
	}
	tot=0;
	for(int i=1;i<=n;i++){
		for(int j=he[i];j;j=ne[j]){
			//要注意,这里是j=ne[j] 
			if(rootid[i]!=rootid[to[j]]){
				add(rootid[i],rootid[to[j]]);
				++in[rootid[to[j]]];
			}
		}
	}
	tuopu();
	for(int i=1;i<=n;i++){
		ans=max(ans,dist[i]);
	}
	printf("%d\n",ans);
}
2022/11/13 11:50
加载中...