金5-backjun 2467溶液


標準2467溶液
https://www.acmicpc.net/problem/2467
方法
この問題は,2種類の溶液を選択して一緒にすると,0に最も近い組合せを求めるという問題である.その結果,絶対値が近いと0に近づくことができ,両溶液が負または正の値であれば,絶対値が小さいと0に最も近い数を求めることができると考えられた.
従って、絶対値を小さい順に並べ替えるために、順次取り出し、優先順位キューを用いて並べ替え、両溶液に添加した結果、0に最も近い値が格納される.
に答える
優先キューにペアで入れ、1つ目は絶対値、2つ目は元の溶液の値です.絶対値が小さいほど、昇順で上部に並べられます.
Qの優先順位を求める前に、溶液を取り出して値を加算し、その値の絶対値を既存の値Minと比較して、より小さな値を記憶する.Minの値が更新されるたびにsaveは2つの溶液を保存し,繰り返し文が終了するとsaveに格納された値は昇順に出力される.
コード#コード#
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

pair<int, int> save;
int Min = -1;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int N;
	cin >> N;

	for (int i = 0; i < N; i++)
	{
		pair<int, int> temp;
		cin >> temp.first;

		temp.second = temp.first;
		if (temp.first < 0)
			temp.first *= -1;

		pq.push(temp);
	}

	pair<int, int> before = pq.top();
	pq.pop();

	while (!pq.empty())
	{
		pair<int, int> cur = pq.top();
		pq.pop();

		int comb = before.second + cur.second;
		if (comb < 0)
			comb *= -1;

		if (Min == -1 || comb < Min)
		{
			Min = comb;
			save.first = before.second;
			save.second = cur.second;
		}

		before = cur;
	}

	cout << min(save.first, save.second) << ' ' << max(save.first, save.second) << endl;
	return 0;
}