编程介的小学生 2019-12-07 21:53 采纳率: 0.4%
浏览 77

Greed is good 怎么写的

Problem Description
As we all know Uncle CTW is a very greedy uncle,he likes collecting jewels.One day he gets a necklace with beautiful gems,he has a strange habit,that he only collects the contiguous gems with with same color.That means if he pick a red gem at first,and he will continue to pick only if the next gem is red,or he will stop.(That's why people call him "Uncle.Strange").
As it is a necklace,he must find somewhere to cut the necklace at the very begining,then select an end to pick until meet a different color gem,and do the same for the other end (which might not be of the same color as the gems collected before this).
There are only three kinds of gems,red('r'),pink('p'),and white('w'),and NOTICE that,because the white one could be painted,so it can be seen as either color.(See the sample for detail.)
Now he just want to know the maximum number of gems he can collect,could you tell him?

Input
The first line contain an integer T,then T lines,each line with a string only contain r,p or w ,with length no more than 400.

Output
One integer per line indicating the maximum nunber.

Sample Input
1
wwwpprwrprprrprprwrwwrpwrwrrp

Sample Output
11

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-07-28 23:39
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    # 读取数据
    data <- readLines()
    
    # 定义函数计算连续相同颜色的宝石数量
    greedy_collected <- function(data) {
      # 初始化结果数组
      result <- c()
      
      # 遍历每一行
      for (line in data) {
        # 将字符串转换为字符数组
        chars <- strsplit(line, "")[[1]]
        
        # 创建一个字典来存储每个连续的颜色集合
        colors <- table(chars)
        
        # 计算连续相同颜色的宝石数量
        count <- sum(colors == 2)
        
        # 如果是红色或粉色,则将计数添加到结果数组中
        if ("r" %in% colors || "p" %in% colors) {
          result <- c(result, count + 1)
        }
      }
      
      # 返回结果数组
      return(result)
    }
    
    # 主程序
    t <- readline(prompt = "Enter number of test cases: ")
    cases <- grep("^.*$", t, value = TRUE)
    
    for (i in seq_along(cases)) {
      print(greedy_collected(readLines()[[cases[i]]]))
    }
    

    这个代码使用了readLines()函数从输入文件中读取数据,并定义了一个名为greedy_collected的函数,它接受一个字符串列表作为参数。在这个函数中,我们遍历每行,将其转换为字符数组并创建一个字典来存储每个连续的颜色集合。然后,我们计算这些集合的数量,如果它们包含两种不同的颜色,则将计数加一。最后,我们将结果数组返回。

    在主程序部分,我们读取测试用例的数量,并对每个测试用例调用greedy_collected函数并将结果打印出来。

    评论

报告相同问题?