【ybtoj 高效进阶 3.4】【强连通分量】 网络传输

【ybtoj 高效进阶 3.4】【强连通分量】 网络传输

题目

在这里插入图片描述
在这里插入图片描述


解题思路

缩点后构造新图
跑spfa求答案
加快读避免TLE
思路还好,就是码有点点长


代码

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
struct lzf {
    int to, q, nxt;
} f[2000100], f2[2000010];
double p[200010];
int x, y, q, n, m, t, tot, top, s[200100], d[200010], col[200010];
int head[200100], head2[200010], dfn[200010], low[200010];
int read() 
{
    int x=0;
    char c=getchar();
    while (c<'0'||c>'9')
	      c=getchar();
    while (c>='0'&&c<='9') 
    {
	      x=x*10+c-'0';
		  c=getchar();
	}
    return x;
}
void add(int x, int y, int q) {
    f[++t].q = q;
    f[t].to = y;
    f[t].nxt = head[x];
    head[x] = t;
}
void add2(int x, int y, int q) {
    f2[++t].q = q;
    f2[t].to = y;
    f2[t].nxt = head2[x];
    head2[x] = t;
}
void tarjan(int x) {
    dfn[x] = low[x] = ++tot;
    s[++top] = x;
    for (int i = head[x]; i; i = f[i].nxt)
        if (!dfn[f[i].to]) {
            tarjan(f[i].to);
            low[x] = min(low[x], low[f[i].to]);
        } else if (!col[f[i].to])
            low[x] = min(low[x], low[f[i].to]);
    if (dfn[x] == low[x]) {
        col[x] = ++y;
        while (s[top] != x) col[s[top--]] = y;
        top--;
    }
}
int main() {
    n=read(),m=read();
    for (int i = 1; i <= m; i++) {
        x=read(),y=read(),q=read(); 
        add(x, y, q);
    }
    y = 0;
    for (int i = 1; i <= n; i++)  
        if (!dfn[i])  //缩点
            tarjan(i);
    t = 0;
    for (int i = 1; i <= n; i++)  //建新图
        for (int j = head[i]; j; j = f[j].nxt)
            if (col[i] != col[f[j].to]) {
                add2(col[i], col[f[j].to], f[j].q);
            }
    if (col[1] == col[n]) {
        printf("0");
        return 0;
    }
    memset(d, 0x7f, sizeof(d));
    d[col[1]] = 0;
    s[1] = col[1];
    p[col[1]] = 0;
    int h = 0, ta = 1;  //spfa求传递信息代价最小值
    while (h < ta) {
        h++;
        for (int i = head2[s[h]]; i; i = f2[i].nxt)
            if (d[s[h]] + f2[i].q < d[f2[i].to]) {
                d[f2[i].to] = d[s[h]] + f2[i].q;
                if (!p[f2[i].to]) {
                    p[f2[i].to] = 1;
                    s[++ta] = f2[i].to;
                }
            }
        p[s[h]] = 0;
    }
    printf("%d", d[col[n]]);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值