[spfa] Jzoj P5869 绿洲
题解
- 每次以绿洲为起点,跑spfa,然后取max
代码
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 struct edge{int to,from;}e[100010*2]; 7 int n,m,k,cnt,d[110],dis[100010],visit[100010],head[100010],ans[100010]; 8 queue<int> Q; 9 void insert(int x,int y) 10 { 11 e[++cnt].to=y; e[cnt].from=head[x]; head[x]=cnt; 12 e[++cnt].to=x; e[cnt].from=head[y]; head[y]=cnt; 13 } 14 void spfa(int s) 15 { 16 memset(dis,-1,sizeof(dis)); 17 dis[s]=0,visit[s]=1; Q.push(s); 18 while (!Q.empty()) 19 { 20 int u=Q.front(); Q.pop(); 21 visit[u]=0; 22 for (int i=head[u];i;i=e[i].from) 23 if (dis[e[i].to]==-1||dis[e[i].to]>dis[u]+1) 24 { 25 dis[e[i].to]=dis[u]+1; 26 if (!visit[e[i].to]) visit[e[i].to]=1,Q.push(e[i].to); 27 } 28 } 29 } 30 int main() 31 { 32 freopen("oasis.in","r",stdin); 33 freopen("oasis.out","w",stdout); 34 scanf("%d%d%d",&n,&m,&k); 35 for (int i=1;i<=k;i++) scanf("%d",&d[i]); 36 for (int i=1;i<=m;i++) 37 { 38 int u,v; 39 scanf("%d%d",&u,&v); 40 insert(u,v); 41 } 42 for (int i=1;i<=k;i++) 43 { 44 spfa(d[i]); 45 for (int j=1;j<=n;j++) if (dis[j]!=-1) ans[j]=max(ans[j],dis[j]); 46 } 47 for (int i=1;i<=n;i++) printf("%d ",ans[i]); 48 return 0; 49 }