标签:code mem www. 无向图 using 代码 cstring include href
给你一个\(n\)个点的无向图和\(m\)条边的有向图,然后我们需要求出从\(1\)号点到达图中每个点的最短路径有多少条。
( \(n \le 1000000,m \le 2000000\))
首先我们先用Bfs求出1号点到达每个点的最短路(因为题目中说了每条边权值为1)用一个\(min_dis\)数组来存储从1号点到达每个点的最小值。然后我们再次进行bfs,然后我们设\(f[i]\)为从\(1\)到达结点\(i\)的最短路数量。那么我们在第二次bfs的过程中,对于当前结点\(x\),我们判断所有与之相连的点\(v\)是否满足\(min_dis[x] = min_dis[v] - 1\)。如果满足就说明这条边一定在从\(1\)到\(v\)的最短路上那么说明\(f[v]\)的值可以从\(f[x]\)转移过来,然后我们将\(f[v]\)加上\(f[x]\)即可。注意初始化\(f[1]\)为\(1\)。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 1e6 + 5;
const int M = 4e6 + 5;
const int MOD = 100003;
int n, m;
int u, v;
int cnt = 0;
int head[N];
int f[N];
int min_dis[N];
bool vis[N];
struct EDGE {
int s;
int e;
int nxt;
} Edge[M];
inline int Min(int x, int y) {
return x <= y ? x : y;
}
int read() { //快速读入函数
int s = 0, w = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
s = s * 10 + ch - '0';
ch = getchar();
}
return s * w;
}
void write(int x) { //快速输出函数
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
void add(int u, int v) {
++cnt;
Edge[cnt].s = u;
Edge[cnt].e = v;
Edge[cnt].nxt = head[u];
head[u] = cnt;
}
void bfs(int x) { //第一次宽搜的函数
queue <int> q;
q.push(x);
vis[x] = true;
while (!q.empty()) {
int now = q.front(); q.pop();
for (register int i = head[now]; i; i = Edge[i].nxt) {
if (vis[Edge[i].e]) continue;
vis[Edge[i].e] = true;
min_dis[Edge[i].e] = min_dis[now] + 1; //求最短路径
q.push(Edge[i].e);
}
}
}
void bfs1(int x) { //第二次宽搜的函数
queue <int> q;
q.push(x);
vis[x] = true;
while (!q.empty()) {
int now = q.front(); q.pop();
for (register int i = head[now]; i; i = Edge[i].nxt) {
if (vis[Edge[i].e]) continue;
vis[Edge[i].e] = true;
q.push(Edge[i].e);
}
for (register int i = head[now]; i; i = Edge[i].nxt) {
if (min_dis[now] == min_dis[Edge[i].e] - 1) {
f[Edge[i].e] = (f[now] % MOD + f[Edge[i].e] % MOD) % MOD; //递推求出答案
}
}
}
}
int main(int argc, char const *argv[]) {
n = read(), m = read();
for (register int i = 1; i <= m; ++i) {
u = read(), v = read();
add(u, v);
add(v, u); //建立双向边
}
bfs(1);
memset(vis, 0, sizeof(vis)); //初始化vis数组
f[1] = 1;
bfs1(1);
for (register int i = 1; i <= n; ++i)
write(f[i]), putchar('\n');
return 0;
}
标签:code mem www. 无向图 using 代码 cstring include href
原文地址:https://www.cnblogs.com/lixiao189/p/9858399.html