• [CareerCup][Google Interview] 找最大序列


    A circus is designing a tower routine consisting of people standing atop one another’s
    shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the heights and weights of each person in the circus, write a method to compute the largest possible number of people
    in such a tower.
    EXAMPLE:
    Input (ht, wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)
    Output: The longest tower is length 6 and includes from top to bottom: (56, 90) (60,95) (65,100) (68,110) (70,150) (75,190)

    http://www.careercup.com/question?id=9339758

    先把数组按height或者weight排个序,然后就变为找最长上升子序列问题了。

     1 #include <iostream>
     2 #include <vector>
     3 #include <algorithm>
     4 using namespace std;
     5 
     6 struct Node
     7 {
     8     int height;
     9     int weight;
    10 
    11     Node(){}
    12     Node(int h, int w):height(h), weight(w){}
    13 };
    14 
    15 bool comp(const Node &lhs, const Node &rhs)
    16 {
    17     return lhs.height < rhs.height;
    18 }
    19 
    20 int solve(vector<Node> &a)
    21 {
    22     sort(a.begin(), a.end(), comp);
    23 
    24     vector<int> f(a.size());
    25 
    26     f[0] = 1;
    27 
    28     for(int i = 1; i < a.size(); i++)
    29     {
    30         f[i] = 1;
    31         for(int j = 0; j < i; j++)
    32             if (a[i].height > a[j].height && a[i].weight > a[j].weight)
    33                 f[i] = max(f[i], f[j] + 1);
    34     }
    35 
    36     int maxF = 0;
    37     for(int i = 0; i < f.size(); i++)
    38         maxF = max(maxF, f[i]);
    39 
    40     return maxF;
    41 }
    42 
    43 int main()
    44 {
    45     vector<Node> a;
    46     a.push_back(Node(65, 100));
    47     a.push_back(Node(70, 150));
    48     a.push_back(Node(56, 90));
    49     a.push_back(Node(75, 190));
    50     a.push_back(Node(60, 95));
    51     a.push_back(Node(68, 110));
    52 
    53     cout << solve(a) << endl;
    54 
    55     vector<Node> b;
    56     b.push_back(Node(1, 2));
    57     b.push_back(Node(1, 3));
    58 
    59     cout << solve(b) << endl;
    60 }
  • 相关阅读:
    yaf将错误输出打印在页面上
    yaf设置命名空间
    yaf学习资料
    在 Github 上找「好东西」的方法
    在linux命令行下执行php 程序
    linux shell脚本查找重复行/查找非重复行/去除重复行/重复行统计
    php数组函数分析--array_column
    php 去掉字符串的最后一个字符
    设置arc 的默认编辑器
    需要学习的技术
  • 原文地址:https://www.cnblogs.com/chkkch/p/2744557.html
Copyright © 2020-2023  润新知