豆豆与黄金剑, 一道典型DP题的C#解法

题目:

Description

有只企鹅叫豆豆,总是被别的企鹅欺负。豆豆在长期的隐忍之后,掌握了所有企鹅的高度和攻击力强度,还得到了一把黄金剑。在拥有了黄金剑以后,豆豆终于可以展开绝地大反击。但这把黄金剑的用法却很奇怪。

首先,豆豆第一次可以选择任何一只企鹅开始挑战。豆豆这一次必胜。

再次,当豆豆已经挑战过某一只企鹅后,再下一次的挑战对象只能是比上一名对手高,且比上一名对手攻击力强的企鹅。这样豆豆必胜。否则黄金剑会觉得打的没意思而故意发脾气输掉。豆豆还会被大家集体暴打。

面对着这把脾气很大的黄金剑,豆豆想请你帮助他计算一下,他最多可以连续击败多少只企鹅?

Input

第一行:一个数据n,代表企鹅群里除了豆豆一共有n(1 ≤ n ≤ 1000)只企鹅。
第2至第n+1行:每行2个数字。第i+1行的第一个数字为企鹅i的高度。第i+1行的第二个数字为企鹅i的攻击力。0 ≤ 高度,攻击力 ≤ 1,000,000。

Output

一个数。代表豆豆最多可以连续击败的企鹅数。

Sample Input

Sample Input #1Sample Input #2
3
1 3
3 2
2 4
5
10 1
9 2
7 3
6 4
5 5

Sample Output

Sample Output #1Sample Output #2
21

C#代码如下:

 

 1    public class QQ
 2    {
 3        public int Height getset; }
 4        public int ATK getset; }
 5    }

 6    class Program
 7    {
 8        static void Main(string[] args)
 9        {
10            int n, h, atk;
11            Console.WriteLine("input the population n(1<=n<= 1000):");
12            while ((n = int.Parse(Console.ReadLine())) > 1000 || n < 1) ;
13            List<QQ> population = new List<QQ>(n+1);
14
15            Console.WriteLine("input the Height and ATK properties,split by one space:");
16            for (int i = 0; i < n; i++)
17            {
18                string[] property = Console.ReadLine().Split(new Char[] ' ' });
19                if ((h = int.Parse(property[0])) < 1000000 && h > -1 &&
20                    (atk = int.Parse(property[1])) < 1000000 && atk > -1)
21                    population.Add(new QQ { Height=h,ATK=atk});
22            }

23
24            population.Sort((a, b) =>
25            {
26                if (a.Height != b.Height)
27                    return a.Height - b.Height;
28                else if (a.ATK != b.ATK)
29                    return a.ATK - b.ATK;
30                else
31                    return 0;
32            }
);
33
34            int[] tb = new int[n];
35            for (int i = 0; i < n; i++)
36            {
37                tb[i] = 1;
38            }

39
40            for (int i = 0; i < n; i++)
41            {
42                for (int j = 0; j < i; j++)
43                {
44                    if (population[i].Height > population[j].Height && 
45                        population[i].ATK > population[j].ATK && tb[i] < tb[j] + 1)
46                    {
47                        tb[i] = tb[j] + 1;
48                    }

49                }

50            }

51            Console.WriteLine("the answer is: "+tb.Max().ToString());
52        }

53    }

PS:还是可以更健壮更优化的,欢迎交流 ;-) 

posted on 2009-07-25 20:01  J.D Huang  阅读(899)  评论(0编辑  收藏  举报