题目
题目描述
给出一个NN个顶点MM条边的无向无权图,顶点编号为1-N1−N。问从顶点11开始,到其他每个点的最短路有几条。
输入输出格式
输入格式:
第一行包含22个正整数N,MN,M,为图的顶点数与边数。
接下来MM行,每行22个正整数x,yx,y,表示有一条顶点xx连向顶点yy的边,请注意可能有自环与重边。
输出格式:
共NN行,每行一个非负整数,第ii行输出从顶点11到顶点ii有多少条不同的最短路,由于答案有可能会很大,你只需要输出 ans mod 100003后的结果即可。如果无法到达顶点ii则输出00。
输入输出样例
输入样例#1:
5 7
1 2
1 3
2 4
3 4
2 3
4 5
4 5
输出样例#1:
1
1
1
2
4
说明
11到55的最短路有44条,分别为22条1-2-4-51−2−4−5和22条1-3-4-51−3−4−5(由于4-54−5的边有22条)。
对于20%20%的数据,N ≤ 100N≤100;
对于60%60%的数据,N ≤ 1000N≤1000;
对于100%100%的数据,N<=1000000,M<=2000000N<=1000000,M<=2000000。
题解
在找最短路时增加判断即可
code
#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <list>
#include <map>
#include <iomanip>
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
#define R register
#define maxn 1001000
#define ull long long
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
return s * w;
}
struct Edge { int next, to, dis; } edge[maxn];
int n, num_edge = 0, m;
int head[maxn], dis[maxn], v[maxn], ans[maxn];
const int mod = 100003;
int vis[maxn];
inline void add(int from, int to, int dis) {
edge[++num_edge].to = to;
edge[num_edge].dis = dis;
edge[num_edge].next = head[from];
head[from] = num_edge;
}
void spfa(int k) {
queue<int> q;
memset(dis, 0x3f, sizeof(dis));
memset(vis, false, sizeof(vis));
q.push(k); vis[k] = 1; dis[k] = 0; ans[k] = 1;
while (!q.empty()) {
int u = q.front(); q.pop(); vis[u] = 0;
for (int i = head[u]; i; i = edge[i].next) {
int v = edge[i].to;
if (dis[v] > dis[u] + edge[i].dis) {
ans[v] = ans[u];
dis[v] = dis[u] + edge[i].dis;
if (!vis[v]) {
vis[v] = true;
q.push(v);
}
}
else {
if (dis[v] == dis[u] + edge[i].dis) {
ans[v] += ans[u];
ans[v] %= mod;
}
}
}
}
}
int main() {
n = read(), m = read();
for (int i = 1; i <= m; ++i) {
int a, b;
a = read(), b = read();
add(a, b, 1), add(b, a, 1);
}
spfa(1);
for (int i = 1; i <= n; ++i) printf("%d\n", ans[i]);
return 0;
}