大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.6 KiB

2 weeks ago
  1. /*
  2. A正在玩游戏n个不同星球m条双向航道A的任务是摧毁这些星球A将按照星球的编号从小到大依次摧毁各个星球A想知道在每个星球被摧毁时还剩下多少个联盟n个点m条边的无向图
  3. n,mm行2u,v1<n,m<5e4
  4. n个正整数
  5. 5 6
  6. 1 2
  7. 2 3
  8. 3 1
  9. 4 5
  10. 5 1
  11. 2 4
  12. 1 2 1 1 0
  13. */
  14. #include <stdio.h>
  15. #define MAXNUM 1000
  16. int Group[MAXNUM]; //记录图中节点是否被访问过
  17. int dist[MAXNUM][MAXNUM]; //通过邻接矩阵保存图
  18. void DFS(int i, int n);
  19. int main()
  20. {
  21. int n, m, p, q, k = 0;
  22. for (int i = 0; i < MAXNUM; i++)
  23. {
  24. for (int j = 0; j < MAXNUM; j++)
  25. dist[i][j] = 0; //初始化邻接矩阵,初始值为0
  26. Group[i] = 0; //同上
  27. }
  28. scanf("%d%d", &n, &m); //获取图的节点数n,和边数m
  29. for (int i = 0; i < m; i++)
  30. {
  31. scanf("%d%d", &p, &q);
  32. dist[p-1][q-1] = 1; //如果节点1和节3相连 则另dist[1][3]和dist[3][1]的值为1
  33. dist[q-1][p-1] = 1;
  34. }
  35. for(int zz = 1; zz <= n; zz++){
  36. for(int j = 1; j <= n; j++){ // 删除节点zz相连的边
  37. p = zz;
  38. q = j;
  39. dist[p-1][q-1] = 0;
  40. dist[q-1][p-1] = 0;
  41. }
  42. for (int i = 0; i < MAXNUM; i++) // 清零
  43. {
  44. Group[i] = 0;
  45. }
  46. for (int i = 0; i < n; i++)
  47. {
  48. if (Group[i] != 1)
  49. {
  50. DFS(i, n);
  51. k++; //执行一次DFS就是k的值自增1,
  52. }
  53. }
  54. printf("%d", k - zz); // k为删除边但没有删除节点的连通数 zz表示每次删除一个节点
  55. k = 0;
  56. }
  57. return 0;
  58. }
  59. void DFS(int i,int n)
  60. {
  61. Group[i] = 1;
  62. for (int j = 0; j < n; j++)
  63. {
  64. if (dist[i][j] == 1)
  65. if (Group[j] != 1)
  66. DFS(j, n);
  67. }
  68. }