洛谷3387 模板 缩点

题目:缩点

 

思路:tarjan缩点+最长路。

 

注意:

1、用dijkstra求最长路时,优先队列中的<运算符要反过来。

2、需要把所有入度为0的点为起点跑一遍最长路。

3、每次求最长路时,dist数组不要重新初始化。

4、缩点后的点权为缩点前的所有点权之和。

5、最开始初始化dist[s]的值不为0,为点权。

 

代码:

#include<bits/stdc++.h>
using namespace std;

#define maxn 10000
#define maxm 100000

struct Pair {
	int x;
	int y;
	Pair(int xx=0,int yy=0) {
		x=xx,y=yy;
	}
	bool operator < (const Pair& oth) const {
		return x<oth.x||(x==oth.x&&y<oth.y);
	}
};

int n,m;
int w[maxn+5];
vector<int> a[maxn+5];

int pre[maxn+5]= {0},low[maxn+5],clk=0;
stack<int> s;
int cnt=0,isin[maxn+5];

vector<int> g[maxn+5];
int goin[maxn+5]= {0};
int dist[maxn+5]= {0};
int val[maxn+5]={0};

void readin() {
	scanf("%d%d",&n,&m);
	for(int i=1; i<=n; i++) {
		scanf("%d",&w[i]);
	}
	for(int i=1; i<=m; i++) {
		int x,y;
		scanf("%d%d",&x,&y);
		a[x].push_back(y);
	}
}

void tarjan(int x) {
	pre[x]=low[x]=++clk;
	s.push(x);
	for(int i=0; i<a[x].size(); i++) {
		int y=a[x][i];
		if(!pre[y]) {
			tarjan(y);
			low[x]=min(low[x],low[y]);
		} else if(!isin[y]) {
			low[x]=min(low[x],pre[y]);
		}
	}
	if(pre[x]==low[x]) {
		cnt++;
		int u;
		do {
			u=s.top();
			s.pop();
			isin[u]=cnt;
			val[cnt]+=w[u];
		} while(u!=x);
	}
}

void make_g() {
	for(int i=1;i<=n;i++){
		for(int j=0;j<a[i].size();j++){
			if(isin[i]!=isin[a[i][j]]) {
				g[isin[i]].push_back(isin[a[i][j]]);
				goin[isin[a[i][j]]]++;
			}
		}
	}
}

void dijkstra(int st) {
	dist[st]=val[st];
	priority_queue<Pair> p;
	p.push(Pair(dist[st],st));
	bool c[maxn+5]= {0};
	while(!p.empty()) {
		Pair x=p.top();
		p.pop();
		if(c[x.y]) continue;
		c[x.y]=true;
		for(int i=0; i<g[x.y].size(); i++) {
			if(dist[g[x.y][i]]<x.x+val[g[x.y][i]]) {
				dist[g[x.y][i]]=x.x+val[g[x.y][i]];
				p.push(Pair(dist[g[x.y][i]],g[x.y][i]));
			}
		}
	}
}

int main() {
	readin();
	for(int i=1; i<=n; i++) if(!pre[i]) tarjan(i);
	make_g();
	for(int i=1; i<=cnt; i++) {
		if(!goin[i]) dijkstra(i);
	}
	int ans=0;
	for(int i=1;i<=cnt;i++){
		ans=max(dist[i],ans);
	}
	printf("%d",ans);
	return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值