您的位置:首页 > 其它

洛谷3387 模板 缩点

2018-03-25 20:20 232 查看
题目:缩点

思路: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息