【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;
}