[关闭]
@Livingston 2021-05-10T12:20:15.000000Z 字数 755 阅读 456

[JZOJ3155]「提高A组模拟」『BFS』最短路

题解 BFS

题目

个结点、 个含 个结点的完全子图构成一个奇怪的图,问从结点走到结点最少需要经过多少个结点。

题解

考虑缩点,将完全子图看成一个点,然后连上完全子图内的点。可以减少边的数量,从而来跑BFS,注意最后的答案是

Code

  1. #include<cstdio>
  2. #include<cstring>
  3. using namespace std;
  4. struct node
  5. {
  6. int to,next;
  7. }a[2000005];
  8. int n,k,m,x,tot,h,t;
  9. int b[200005],d[101005][3],head[101005];
  10. void add(int x,int y)
  11. {
  12. a[++tot].to=y;
  13. a[tot].next=head[x];
  14. head[x]=tot;
  15. }
  16. int main()
  17. {
  18. scanf("%d%d%d",&n,&k,&m);
  19. for (int i=1;i<=m;++i)
  20. {
  21. for (int j=1;j<=k;++j)
  22. scanf("%d",&x),add(x,n+i),add(n+i,x);
  23. }
  24. h=0;t=1;
  25. d[1][1]=1;d[1][2]=1;
  26. b[1]=true;
  27. while (h<t)
  28. {
  29. int u=d[++h][1];
  30. for (int i=head[u];i;i=a[i].next)
  31. {
  32. int v=a[i].to;
  33. if (!b[v])
  34. {
  35. b[v]=true;
  36. d[++t][1]=v;
  37. d[t][2]=d[h][2]+1;
  38. if (v==n)
  39. {
  40. printf("%d\n",d[t][2]/2+1);
  41. return 0;
  42. }
  43. }
  44. }
  45. }
  46. printf("-1\n");
  47. return 0;
  48. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注