light oj 1047 - Neighbor House 动态规划

举报
xindoo 发表于 2022/04/16 01:04:41 2022/04/16
【摘要】 题目链接 The people of Mohammadpur have decided to paint each of their houses red, green, or blue. They've also decided that no two neighboring houses will be painted the s...

题目链接

The people of Mohammadpur have decided to paint each of their houses red, green, or blue. They've also decided that no two neighboring houses will be painted the same color. The neighbors of house i are houses i-1 and i+1. The first and last houses are not neighbors.

You will be given the information of houses. Each house will contain three integers "R G B" (quotes for clarity only), where R, G and B are the costs of painting the corresponding house red, green, and blue, respectively. Return the minimal total cost required to perform the work.………………

题意:

      有n户人,打算把他们的房子图上颜色,有red、green、blue三种颜色,每家人涂不同的颜色要花不同的费用,而且相邻两户人家之间的颜色要不同,求最小的总花费费用。

思路:

     动态规划,这个和刘汝佳算法竞赛入门经典P158的数字三角形有些相似,不过是求最小的值,而且有些限制,每次走到点和上次走的点不在同一列。

代码:


  
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <algorithm>
  4. using namespace std;
  5. int dp[23][4];
  6. int a[23][4];
  7. int main()
  8. {
  9. int n, t;
  10. scanf("%d",&t);
  11. for(int k = 1; k <= t; k++)
  12. {
  13. scanf("%d",&n);
  14. memset(a, 0, sizeof(a));
  15. memset(dp, 0, sizeof(dp));
  16. for (int i = 1; i <= n; i++)
  17. {
  18. for (int j = 1; j <= 3; j++)
  19. scanf("%d",&a[i][j]);
  20. }
  21. for (int i = 1; i <= n; i++)
  22. {
  23. for (int j = 3; j < 6; j++)
  24. {
  25. dp[i][j%3+1] = a[i][j%3+1] + min(dp[i-1][(j-1)%3+1], dp[i-1][(j+1)%3+1]);
  26. //这里我用这种方法避免了分情况讨论,、减少了代码量
  27. }
  28. }
  29. printf("Case %d: %d\n", k, min(dp[n][1], min(dp[n][2], dp[n][3])));
  30. }
  31. return 0;
  32. }


文章来源: xindoo.blog.csdn.net,作者:xindoo,版权归原作者所有,如需转载,请联系作者。

原文链接:xindoo.blog.csdn.net/article/details/8832898

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。