이동식이 2024. 6. 19. 14:14
728x90

문제

https://www.acmicpc.net/problem/2467

고민

두 용액을 합쳐서 X가 나오게 하라 ⇒ 투포인터

심지어 오름차순으로 제공된다? => 투포인터로 풀어라

코드

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TwoPointers
{
    internal class 용액
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] solution = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            
            int left = 0;
            int right = n - 1;

            long min = long.MaxValue;
            int minLeft = 0; 
            int minRight = 0;

            while(left < right)
            {
                long sum = solution[left] + solution[right];

                if(min > Math.Abs(sum))
                {
                    minLeft = left;
                    minRight = right;
                    min = Math.Abs(sum);
                }
                
                if(sum < 0)
                {
                    left++;
                }
                else
                {
                    right--;
                }
            }

            Console.WriteLine($"{solution[minLeft]} {solution[minRight]}");
        }
    }
}

처음에 자꾸 틀려서 대체 뭐가 문제인지 몰랐다. 다른 사람들 코드와 로직을 비교해도 아무리 투포인터 이론을 살펴봐도 나처럼 구현했는데 왜 나만 틀리지??

 

이유는 Long.MaxValue;였다. ㅋㅋㅋ내가 수동으로 100000000을 입력했다. 다음부턴 MaxValue 도움을 받자^!^