您的位置:首页 > 编程语言 > C#

pat1002

2016-04-11 14:46 435 查看
This time, you are supposed to find A+B where A and B are two polynomials.

Input

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 ... NK aNK,
where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.

Output

For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
Sample Input
2 1 2.4 0 3.2
2 2 1.5 1 0.5

Sample Output
3 2 1.5 1 2.9 0 3.2

输入两行数,把指数相同的相加起来,最后输出在一行。最后指数为0.0的不能输出,也不记在总数里

用C#处理这种多输入真的头疼,使用Dictionary<int,double>存数据,用了linq的排序方法= =感觉好复杂

输出格式为{0} {1:.0}

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int n1, n2;
            Dictionary<int, double> d = new Dictionary<int, double>();
            string[] str1 = Console.ReadLine().Split();
            string[] str2 = Console.ReadLine().Split();
            n1 = Convert.ToInt32(str1[0]);
            n2 = Convert.ToInt32(str2[0]);
            int i, j;
            for (i = 1, j = 2; i <= str1.Length - 1 && j <= str1.Length - 1; i += 2, j += 2)
            {
                d.Add(Convert.ToInt32(str1[i]), Convert.ToDouble(str1[j]));
            }
            for (i = 1, j = 2; i <= str2.Length - 1 && j <= str2.Length - 1; i += 2, j += 2)
            {
                if (d.ContainsKey(Convert.ToInt32(str2[i])))
                {
                    d[Convert.ToInt32(str2[i])] += Convert.ToDouble(str2[j]);
                }
                else
                {
                    d.Add(Convert.ToInt32(str2[i]), Convert.ToDouble(str2[j]));
                }
            }

            int co = 0;
            int nums = d.Count;
            d = d.OrderByDescending(r => r.Key).ToDictionary(r => r.Key, r => r.Value);
            foreach (KeyValuePair<int, double> ke in d)
            {
                if (ke.Value == 0) nums--;
            }
            Console.Write(nums);
            if (nums != 0) Console.Write(" ");
            foreach (KeyValuePair<int, double> ke in d)
            {
                if (ke.Value == 0)
                {
                    continue;
                }
                co++;
                Console.Write("{0} {1:.0}", ke.Key, ke.Value);
                if (co != nums) Console.Write(" ");
            }   
            Console.WriteLine();
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# PAT