当前位置:   article > 正文

3个A国人,3个B国人,3个C国人坐成一排。 要求不能使连续的3个人是同一个国籍._一个b一个3人个人换免费的

一个b一个3人个人换免费的

 这道题本来很容易的,就是一次全排列然后检查而已。

  1. public class Test3
  2. {
  3. static int kinds=0;
  4. static int b[]=new int[10];
  5. static boolean vis[]=new boolean[10];
  6. public static void main(String[] args)
  7. {
  8. int a[]=new int[]{0,1,1,1,2,2,2,3,3,3};
  9. dfs(1,a);
  10. System.out.println("kinds:"+kinds);
  11. }
  12. static void dfs(int start,int a[])
  13. {
  14. if(start==a.length)
  15. {
  16. kinds++;
  17. }
  18. else
  19. {
  20. for(int i=1;i<a.length;i++)
  21. {
  22. if(!vis[i])//未上坐
  23. {
  24. b[start]=a[i];
  25. if(start>2 && b[start-2]==b[start-1] && b[start-1]==b[start])
  26. continue;//边排边检查提高效率
  27. vis[i]=true;
  28. dfs(start+1,a);
  29. vis[i]=false;
  30. }
  31. }
  32. }
  33. }
  34. }
  35. //kinds:283824
  36.  

一不小心以为不可以重复,一个同学给我指出来了,来自同一个国家,但个体可以不同,所以序列是可以重复的。如果要求序列也不重复的话,问题就会复杂些了。

下面是代码。

  1. /**
  2. * 和上一篇的售票员卖车票很相似
  3. * 因为有3国人 所以结果必然是3的倍数。
  4. * 可以使第一个座位是A。这样程序就能快3倍了。
  5. * 采用回溯,边排边测试,提高效率。
  6. */
  7. import java.util.Arrays;
  8. public class Test4
  9. {
  10. static int kinds=0;
  11. static int a[]=new int[4];
  12. static int b[]=new int[4];
  13. static int c[]=new int[4];
  14. static int aim[]=new int[10];
  15. public static void main(String[] args)
  16. {
  17. // aim[1]=1;
  18. Arrays.fill(a,1);
  19. Arrays.fill(b,2);
  20. Arrays.fill(c,3);
  21. // dfs(2,2,3,3);
  22. dfs(1,3,3,3);
  23. System.out.println("kinds:"+kinds);
  24. }
  25. static void dfs(int start,int a,int b,int c)
  26. {
  27. if(start==10)
  28. {
  29. kinds++;
  30. // for(int i=1;i<start;i++)
  31. // {
  32. // System.out.printf("%c",(aim[i]+64));
  33. // }
  34. // System.out.println();
  35. }
  36. else if(start<3)//肯定不会出现三个座来自国家相同的,因为就两座位。
  37. {
  38. aim[start]=1;
  39. a--;
  40. dfs(start+1,a,b,c);
  41. a++;
  42. aim[start]=2;
  43. b--;
  44. dfs(start+1,a,b,c);
  45. b++;
  46. aim[start]=3;
  47. c--;
  48. dfs(start+1,a,b,c);
  49. c++;
  50. }
  51. else
  52. {
  53. aim[start]=1;
  54. if(!(aim[start-2]==aim[start-1] && aim[start-1]==aim[start]) && a>0)//不是3连号,且A国家还有人未上坐
  55. {
  56. a--;
  57. dfs(start+1,a,b,c);
  58. a++;
  59. }
  60. aim[start]=2;
  61. if(!(aim[start-2]==aim[start-1] && aim[start-1]==aim[start]) && b>0)//同理
  62. {
  63. b--;
  64. dfs(start+1,a,b,c);
  65. b++;
  66. }
  67. aim[start]=3;
  68. if(!(aim[start-2]==aim[start-1] && aim[start-1]==aim[start]) && c>0)//同理
  69. {
  70. c--;
  71. dfs(start+1,a,b,c);
  72. c++;
  73. }
  74. }
  75. }
  76. }
  77. //计算是1314.好巧的数字啊
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/887350
推荐阅读
相关标签
  

闽ICP备14008679号