<commit_before>/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include <fb/fbjni/CoreClasses.h>

#include <fb/assert.h>
#include <fb/log.h>

#include <alloca.h>
#include <cstdlib>
#include <ios>
#include <stdexcept>
#include <stdio.h>
#include <string>
#include <system_error>

#include <jni.h>

namespace facebook {
namespace jni {

namespace {
class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;";

  static local_ref<JRuntimeException> create(const char* str) {
    return newInstance(make_jstring(str));
  }

  static local_ref<JRuntimeException> create() {
    return newInstance();
  }
};

class JIOException : public JavaClass<JIOException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/io/IOException;";

  static local_ref<JIOException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;";

  static local_ref<JOutOfMemoryError> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;";

  static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;";
<commit_msg>Lines authored by ritzau<commit_after>/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#include <fb/fbjni/CoreClasses.h>

#include <fb/assert.h>
#include <fb/log.h>

#include <alloca.h>
#include <cstdlib>
#include <ios>
#include <stdexcept>
#include <stdio.h>
#include <string>
#include <system_error>

#include <jni.h>

namespace facebook {
namespace jni {

namespace {
class JRuntimeException : public JavaClass<JRuntimeException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/RuntimeException;";

  static local_ref<JRuntimeException> create(const char* str) {
    return newInstance(make_jstring(str));
  }

  static local_ref<JRuntimeException> create() {
    return newInstance();
  }
};

class JIOException : public JavaClass<JIOException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/io/IOException;";

  static local_ref<JIOException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JOutOfMemoryError : public JavaClass<JOutOfMemoryError, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/OutOfMemoryError;";

  static local_ref<JOutOfMemoryError> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JArrayIndexOutOfBoundsException : public JavaClass<JArrayIndexOutOfBoundsException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Ljava/lang/ArrayIndexOutOfBoundsException;";

  static local_ref<JArrayIndexOutOfBoundsException> create(const char* str) {
    return newInstance(make_jstring(str));
  }
};

class JUnknownCppException : public JavaClass<JUnknownCppException, JThrowable> {
 public:
  static auto constexpr kJavaDescriptor = "Lcom/facebook/jni/UnknownCppException;";

<|endoftext|>


<commit_before>#include "components/TextEditComponent.h"
#include "Log.h"
#include "resources/Font.h"
#include "Window.h"
#include "Renderer.h"
#include "Util.h"

#define TEXT_PADDING_HORIZ 10
#define TEXT_PADDING_VERT 2

#define CURSOR_REPEAT_START_DELAY 500
#define CURSOR_REPEAT_SPEED 28 // lower is faster

TextEditComponent::TextEditComponent(Window* window) : GuiComponent(window),
	mBox(window, ":/textinput_ninepatch.png"), mFocused(false),
	mScrollOffset(0.0f, 0.0f), mCursor(0), mEditing(false), mFont(Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT)),
	mCursorRepeatDir(0)
{
	addChild(&mBox);

	onFocusLost();

	setSize(256, mFont->getHeight() + TEXT_PADDING_VERT);
}

void TextEditComponent::onFocusGained()
{
	mFocused = true;
	mBox.setImagePath(":/textinput_ninepatch_active.png");
}

void TextEditComponent::onFocusLost()
{
	mFocused = false;
	mBox.setImagePath(":/textinput_ninepatch.png");
}

void TextEditComponent::onSizeChanged()
{
	mBox.fitTo(mSize, Eigen::Vector3f::Zero(), Eigen::Vector2f(-34, -32 - TEXT_PADDING_VERT));
	onTextChanged(); // wrap point probably changed
}

void TextEditComponent::setValue(const std::string& val)
{
	mText = val;
	onTextChanged();
}

std::string TextEditComponent::getValue() const
{
	return mText;
}

void TextEditComponent::textInput(const char* text)
{
	if(mEditing)
	{
		mCursorRepeatDir = 0;
		if(text[0] == '\b')
		{
			if(mCursor > 0)
			{
				size_t newCursor = Font::getPrevCursor(mText, mCursor);
				mText.erase(mText.begin() + newCursor, mText.begin() + mCursor);
				mCursor = newCursor;
			}
		}else{
			mText.insert(mCursor, text);
			mCursor += strlen(text);
		}
	}

	onTextChanged();
	onCursorChanged();
}

void TextEditComponent::startEditing()
{
	SDL_StartTextInput();
	mEditing = true;
	updateHelpPrompts();
}

void TextEditComponent::stopEditing()
{
	SDL_StopTextInput();
	mEditing = false;
	updateHelpPrompts();
}

bool TextEditComponent::input(InputConfig* config, Input input)
{
	if(input.value == 0)
	{
		if(config->isMappedTo("left", input) || config->isMappedTo("right", input))
			mCursorRepeatDir = 0;

		return false;
	}

	if(config->isMappedTo("a", input) && mFocused && !mEditing)
	{
		startEditing();
		return true;
	}

	if(mEditing)
	{
		if(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RETURN)
		{
			if(isMultiline())
			{
				textInput("\n");
			}else{
				stopEditing();
			}

			return true;
		}

		if((config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_ESCAPE) || (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedTo("b", input)))
		{
			stopEditing();
			return true;
		}

		if(config->isMappedTo("up", input))
		{
			// TODO
		}else if(config->isMappedTo("down", input))
		{
			// TODO
		}else if(config->isMappedTo("left", input) || config->isMappedTo("right", input))
		{
			mCursorRepeatDir = config->isMappedTo("left", input) ? -1 : 1;
			mCursorRepeatTimer = -(CURSOR_REPEAT_START_DELAY - CURSOR_REPEAT_SPEED);
			moveCursor(mCursorRepeatDir);
		}

		//consume all input when editing text
		return true;
	}

	return false;
}

void TextEditComponent::update(int deltaTime)
{
	updateCursorRepeat(deltaTime);
	GuiComponent::update(deltaTime);
}

void TextEditComponent::updateCursorRepeat(int deltaTime)
{
	if(mCursorRepeatDir == 0)
		return;

	mCursorRepeatTimer += deltaTime;
	while(mCursorRepeatTimer >= CURSOR_REPEAT_SPEED)
	{
		moveCursor(mCursorRepeatDir);
		mCursorRepeatTimer -= CURSOR_REPEAT_SPEED;
	}
}

void TextEditComponent::moveCursor(int amt)
{
	mCursor = Font::moveCursor(mText, mCursor, amt);
	onCursorChanged();
}

void TextEditComponent::setCursor(size_t pos)
{
	if(pos == std::string::npos)
		mCursor = mText.length();
	else
		mCursor = (int)pos;

	moveCursor(0);
}

void TextEditComponent::onTextChanged()
{
	std::string wrappedText = (isMultiline() ? mFont->wrapText(mText, getTextAreaSize().x()) : mText);
	mTextCache = std::unique_ptr<TextCache>(mFont->buildTextCache(wrappedText, 0, 0, 0x77777700 | getOpacity()));

	if(mCursor > (int)mText.length())
		mCursor = mText.length();
}

void TextEditComponent::onCursorChanged()
{
	if(isMultiline())
	{
		Eigen::Vector2f textSize = mFont->getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor);

		if(mScrollOffset.y() + getTextAreaSize().y() < textSize.y() + mFont->getHeight()) //need to scroll down?
		{
			mScrollOffset[1] = textSize.y() - getTextAreaSize().y() + mFont->getHeight();
		}else if(mScrollOffset.y() > textSize.y()) //need to scroll up?
		{
			mScrollOffset[1] = textSize.y();
		}
	}else{
		Eigen::Vector2f cursorPos = mFont->sizeText(mText.substr(0, mCursor));

		if(mScrollOffset.x() + getTextAreaSize().x() < cursorPos.x())
		{
			mScrollOffset[0] = cursorPos.x() - getTextAreaSize().x();
		}else if(mScrollOffset.x() > cursorPos.x())
		{
			mScrollOffset[0] = cursorPos.x();
		}
	}
}

void TextEditComponent::render(const Eigen::Affine3f& parentTrans)
{
	Eigen::Affine3f trans = getTransform() * parentTrans;
	renderChildren(trans);

	// text + cursor rendering
	// offset into our "text area" (padding)
	trans.translation() += Eigen::Vector3f(getTextAreaPos().x(), getTextAreaPos().y(), 0);

	Eigen::Vector2i clipPos((int)trans.translation().x(), (int)trans.translation().y());
	Eigen::Vector3f dimScaled = trans * Eigen::Vector3f(getTextAreaSize().x(), getTextAreaSize().y(), 0); // use "text area" size for clipping
	Eigen::Vector2i clipDim((int)dimScaled.x() - trans.translation().x(), (int)dimScaled.y() - trans.translation().y());
	Renderer::pushClipRect(clipPos, clipDim);

	trans.translate(Eigen::Vector3f(-mScrollOffset.x(), -mScrollOffset.y(), 0));
	trans = roundMatrix(trans);

	Renderer::setMatrix(trans);

	if(mTextCache)
	{
		mFont->renderTextCache(mTextCache.get());
	}

	// pop the clip early to allow the cursor to be drawn outside of the "text area"
	Renderer::popClipRect();

	// draw cursor
	if(mEditing)
	{
		Eigen::Vector2f cursorPos;
		if(isMultiline())
		{
			cursorPos = mFont->getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor);
		}else{
			cursorPos = mFont->sizeText(mText.substr(0, mCursor));
			cursorPos[1] = 0;
		}

		float cursorHeight = mFont->getHeight() * 0.8f;
		Renderer::drawRect(cursorPos.x(), cursorPos.y() + (mFont->getHeight() - cursorHeight) / 2, 2.0f, cursorHeight, 0x000000FF);
	}
}

bool TextEditComponent::isMultiline()
{
	return (getSize().y() > mFont->getHeight() * 1.25f);
}

Eigen::Vector2f TextEditComponent::getTextAreaPos() const
{
	return Eigen::Vector2f(TEXT_PADDING_HORIZ / 2.0f, TEXT_PADDING_VERT / 2.0f);
}

Eigen::Vector2f TextEditComponent::getTextAreaSize() const
{
	return Eigen::Vector2f(mSize.x() - TEXT_PADDING_HORIZ, mSize.y() - TEXT_PADDING_VERT);
}

std::vector<HelpPrompt> TextEditComponent::getHelpPrompts()
{
	std::vector<HelpPrompt> prompts;
	if(mEditing)
	{
		prompts.push_back(HelpPrompt("up/down/left/right", "move cursor"));
		prompts.push_back(HelpPrompt("b", "stop editing"));
	}else{
		prompts.push_back(HelpPrompt("a", "edit"));
	}
	return prompts;
}
<commit_msg>Fix initial text positioning and improve keyboard handling in TextEditComponent<commit_after>#include "components/TextEditComponent.h"
#include "Log.h"
#include "resources/Font.h"
#include "Window.h"
#include "Renderer.h"
#include "Util.h"

#define TEXT_PADDING_HORIZ 10
#define TEXT_PADDING_VERT 2

#define CURSOR_REPEAT_START_DELAY 500
#define CURSOR_REPEAT_SPEED 28 // lower is faster

TextEditComponent::TextEditComponent(Window* window) : GuiComponent(window),
	mBox(window, ":/textinput_ninepatch.png"), mFocused(false),
	mScrollOffset(0.0f, 0.0f), mCursor(0), mEditing(false), mFont(Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT)),
	mCursorRepeatDir(0)
{
	addChild(&mBox);

	onFocusLost();

	setSize(4096, mFont->getHeight() + TEXT_PADDING_VERT);
}

void TextEditComponent::onFocusGained()
{
	mFocused = true;
	mBox.setImagePath(":/textinput_ninepatch_active.png");
}

void TextEditComponent::onFocusLost()
{
	mFocused = false;
	mBox.setImagePath(":/textinput_ninepatch.png");
}

void TextEditComponent::onSizeChanged()
{
	mBox.fitTo(mSize, Eigen::Vector3f::Zero(), Eigen::Vector2f(-34, -32 - TEXT_PADDING_VERT));
	onTextChanged(); // wrap point probably changed
}

void TextEditComponent::setValue(const std::string& val)
{
	mText = val;
	onTextChanged();
}

std::string TextEditComponent::getValue() const
{
	return mText;
}

void TextEditComponent::textInput(const char* text)
{
	if(mEditing)
	{
		mCursorRepeatDir = 0;
		if(text[0] == '\b')
		{
			if(mCursor > 0)
			{
				size_t newCursor = Font::getPrevCursor(mText, mCursor);
				mText.erase(mText.begin() + newCursor, mText.begin() + mCursor);
				mCursor = newCursor;
			}
		}else{
			mText.insert(mCursor, text);
			mCursor += strlen(text);
		}
	}

	onTextChanged();
	onCursorChanged();
}

void TextEditComponent::startEditing()
{
	SDL_StartTextInput();
	mEditing = true;
	updateHelpPrompts();
}

void TextEditComponent::stopEditing()
{
	SDL_StopTextInput();
	mEditing = false;
	updateHelpPrompts();
}

bool TextEditComponent::input(InputConfig* config, Input input)
{
	bool const cursor_left = (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedTo("left", input)) ||
		(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_LEFT);
	bool const cursor_right = (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedTo("right", input)) ||
		(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RIGHT);

	if(input.value == 0)
	{
		if(cursor_left || cursor_right)
			mCursorRepeatDir = 0;

		return false;
	}

	if((config->isMappedTo("a", input) || (config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RETURN)) && mFocused && !mEditing)
	{
		startEditing();
		return true;
	}

	if(mEditing)
	{
		if(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RETURN)
		{
			if(isMultiline())
			{
				textInput("\n");
			}else{
				stopEditing();
			}

			return true;
		}

		if((config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_ESCAPE) || (config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedTo("b", input)))
		{
			stopEditing();
			return true;
		}

		if(config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedTo("up", input))
		{
			// TODO
		}else if(config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedTo("down", input))
		{
			// TODO
		}else if(cursor_left || cursor_right)
		{
			mCursorRepeatDir = cursor_left ? -1 : 1;
			mCursorRepeatTimer = -(CURSOR_REPEAT_START_DELAY - CURSOR_REPEAT_SPEED);
			moveCursor(mCursorRepeatDir);
		} else if(config->getDeviceId() == DEVICE_KEYBOARD)
		{
			switch(input.id)
			{
				case SDLK_HOME:
					setCursor(0);
					break;

				case SDLK_END:
					setCursor(std::string::npos);
					break;

				case SDLK_DELETE:
					if(mCursor < mText.length())
					{
						// Fake as Backspace one char to the right
						moveCursor(1);
						textInput("\b");
					}
					break;
			}
		}

		//consume all input when editing text
		return true;
	}

	return false;
}

void TextEditComponent::update(int deltaTime)
{
	updateCursorRepeat(deltaTime);
	GuiComponent::update(deltaTime);
}

void TextEditComponent::updateCursorRepeat(int deltaTime)
{
	if(mCursorRepeatDir == 0)
		return;

	mCursorRepeatTimer += deltaTime;
	while(mCursorRepeatTimer >= CURSOR_REPEAT_SPEED)
	{
		moveCursor(mCursorRepeatDir);
		mCursorRepeatTimer -= CURSOR_REPEAT_SPEED;
	}
}

void TextEditComponent::moveCursor(int amt)
{
	mCursor = Font::moveCursor(mText, mCursor, amt);
	onCursorChanged();
}

void TextEditComponent::setCursor(size_t pos)
{
	if(pos == std::string::npos)
		mCursor = mText.length();
	else
		mCursor = (int)pos;

	moveCursor(0);
}

void TextEditComponent::onTextChanged()
{
	std::string wrappedText = (isMultiline() ? mFont->wrapText(mText, getTextAreaSize().x()) : mText);
	mTextCache = std::unique_ptr<TextCache>(mFont->buildTextCache(wrappedText, 0, 0, 0x77777700 | getOpacity()));

	if(mCursor > (int)mText.length())
		mCursor = mText.length();
}

void TextEditComponent::onCursorChanged()
{
	if(isMultiline())
	{
		Eigen::Vector2f textSize = mFont->getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor);

		if(mScrollOffset.y() + getTextAreaSize().y() < textSize.y() + mFont->getHeight()) //need to scroll down?
		{
			mScrollOffset[1] = textSize.y() - getTextAreaSize().y() + mFont->getHeight();
		}else if(mScrollOffset.y() > textSize.y()) //need to scroll up?
		{
			mScrollOffset[1] = textSize.y();
		}
	}else{
		Eigen::Vector2f cursorPos = mFont->sizeText(mText.substr(0, mCursor));

		if(mScrollOffset.x() + getTextAreaSize().x() < cursorPos.x())
		{
			mScrollOffset[0] = cursorPos.x() - getTextAreaSize().x();
		}else if(mScrollOffset.x() > cursorPos.x())
		{
			mScrollOffset[0] = cursorPos.x();
		}
	}
}

void TextEditComponent::render(const Eigen::Affine3f& parentTrans)
{
	Eigen::Affine3f trans = getTransform() * parentTrans;
	renderChildren(trans);

	// text + cursor rendering
	// offset into our "text area" (padding)
	trans.translation() += Eigen::Vector3f(getTextAreaPos().x(), getTextAreaPos().y(), 0);

	Eigen::Vector2i clipPos((int)trans.translation().x(), (int)trans.translation().y());
	Eigen::Vector3f dimScaled = trans * Eigen::Vector3f(getTextAreaSize().x(), getTextAreaSize().y(), 0); // use "text area" size for clipping
	Eigen::Vector2i clipDim((int)dimScaled.x() - trans.translation().x(), (int)dimScaled.y() - trans.translation().y());
	Renderer::pushClipRect(clipPos, clipDim);

	trans.translate(Eigen::Vector3f(-mScrollOffset.x(), -mScrollOffset.y(), 0));
	trans = roundMatrix(trans);

	Renderer::setMatrix(trans);

	if(mTextCache)
	{
		mFont->renderTextCache(mTextCache.get());
	}

	// pop the clip early to allow the cursor to be drawn outside of the "text area"
	Renderer::popClipRect();

	// draw cursor
	if(mEditing)
	{
		Eigen::Vector2f cursorPos;
		if(isMultiline())
		{
			cursorPos = mFont->getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor);
		}else{
			cursorPos = mFont->sizeText(mText.substr(0, mCursor));
			cursorPos[1] = 0;
		}

		float cursorHeight = mFont->getHeight() * 0.8f;
		Renderer::drawRect(cursorPos.x(), cursorPos.y() + (mFont->getHeight() - cursorHeight) / 2, 2.0f, cursorHeight, 0x000000FF);
	}
}

bool TextEditComponent::isMultiline()
{
	return (getSize().y() > mFont->getHeight() * 1.25f);
}

Eigen::Vector2f TextEditComponent::getTextAreaPos() const
{
	return Eigen::Vector2f(TEXT_PADDING_HORIZ / 2.0f, TEXT_PADDING_VERT / 2.0f);
}

Eigen::Vector2f TextEditComponent::getTextAreaSize() const
{
	return Eigen::Vector2f(mSize.x() - TEXT_PADDING_HORIZ, mSize.y() - TEXT_PADDING_VERT);
}

std::vector<HelpPrompt> TextEditComponent::getHelpPrompts()
{
	std::vector<HelpPrompt> prompts;
	if(mEditing)
	{
		prompts.push_back(HelpPrompt("up/down/left/right", "move cursor"));
		prompts.push_back(HelpPrompt("b", "stop editing"));
	}else{
		prompts.push_back(HelpPrompt("a", "edit"));
	}
	return prompts;
}
<|endoftext|>


<commit_before>#define DEBUG 1

/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-5-27 00:19:34
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, K;
int a[100];
int ans = 0;

int main()
{
  cin >> N >> K;
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
  }
  for (auto l = 0; l < K; l++)
  {
    for (auto r = 0; r < K - l; r++)
    {
      if (l + r > N)
      {
        continue;
      }
      int now = 0;
      int d = K - l - r;
      vector<int> V;
      for (auto i = 0; i < l; i++)
      {
        now += a[i];
        V.push_back(a[i]);
      }
      for (auto i = N - r; i < N; i++)
      {
        now += a[i];
        V.push_back(a[i]);
      }
      sort(V.begin(), V.end());
      for (auto i = 0; i < d; i++)
      {
        if (i >= (int)V.size())
        {
          break;
        }
        if (V[i] >= 0)
        {
          break;
        }
        now -= V[i];
      }
      ans = max(ans, now);
    }
  }
  cout << ans << endl;
}<commit_msg>submit D2.cpp to 'D - equeue' (abc128) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1

/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-5-27 00:19:34
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, K;
int a[100];
int ans = 0;

int main()
{
  cin >> N >> K;
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
  }
  for (auto l = 0; l <= K; l++)
  {
    for (auto r = 0; r <= K - l; r++)
    {
      if (l + r > N)
      {
        continue;
      }
      int now = 0;
      int d = K - l - r;
      vector<int> V;
      for (auto i = 0; i < l; i++)
      {
        now += a[i];
        V.push_back(a[i]);
      }
      for (auto i = N - r; i < N; i++)
      {
        now += a[i];
        V.push_back(a[i]);
      }
      sort(V.begin(), V.end());
      for (auto i = 0; i < d; i++)
      {
        if (i >= (int)V.size())
        {
          break;
        }
        if (V[i] >= 0)
        {
          break;
        }
        now -= V[i];
      }
      ans = max(ans, now);
    }
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <Context.h>
#include <i18n.h>
#include <CmdUndo.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdUndo::CmdUndo ()
{
  _keyword     = "undo";
  _usage       = "task          undo";
  _description = STRING_CMD_UNDO_USAGE;
  _read_only   = false;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdUndo::execute (std::string& output)
{
  // Detect attempts to modify the task.
  for (auto& a : context.cli._args)
    if (a.hasTag ("MODIFICATION"))
      throw std::string (STRING_CMD_UNDO_MODS);

  context.tdb2.revert ();
  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>CmdUndo: Converted from CLI to CLI2<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <Context.h>
#include <i18n.h>
#include <CmdUndo.h>

extern Context context;

////////////////////////////////////////////////////////////////////////////////
CmdUndo::CmdUndo ()
{
  _keyword     = "undo";
  _usage       = "task          undo";
  _description = STRING_CMD_UNDO_USAGE;
  _read_only   = false;
  _displays_id = false;
}

////////////////////////////////////////////////////////////////////////////////
int CmdUndo::execute (std::string& output)
{
  // Detect attempts to modify the task.
  if (context.cli2.getWords ().size ())
    throw std::string (STRING_CMD_UNDO_MODS);

  context.tdb2.revert ();
  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOBJReader.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkOBJReader.h"

#include "vtkCellArray.h"
#include "vtkFloatArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"

vtkCxxRevisionMacro(vtkOBJReader, "1.23");
vtkStandardNewMacro(vtkOBJReader);

// Description:
// Instantiate object with NULL filename.
vtkOBJReader::vtkOBJReader()
{
  this->FileName = NULL;
}

vtkOBJReader::~vtkOBJReader()
{
  if (this->FileName)
    {
    delete [] this->FileName;
    this->FileName = NULL;
    }
}

/*--------------------------------------------------------

This is only partial support for the OBJ format, which is
quite complicated. To find a full specification,
search the net for "OBJ format", eg.:

http://netghost.narod.ru/gff/graphics/summary/waveobj.htm

We support the following types:

v <x> <y> <z>              vertex

vn <x> <y> <z>             vertex normal

vt <x> <y>                 texture coordinate

f <v_a> <v_b> <v_c> ...

polygonal face linking vertices v_a, v_b, v_c, etc. which
are 1-based indices into the vertex list

f <v_a>/<t_a> <v_b>/<t_b> ...

polygonal face as above, but with texture coordinates for
each vertex. t_a etc. are 1-based indices into the texture
coordinates list (from the vt lines)

f <v_a>/<t_a>/<n_a> <v_b>/<t_b>/<n_b> ...

polygonal face as above, with a normal at each vertex, as a
1-based index into the normals list (from the vn lines)

f <v_a>//<n_a> <v_b>//<n_b> ...

polygonal face as above but without texture coordinates.

Per-face tcoords and normals are supported by duplicating
the vertices on each face as necessary.

---------------------------------------------------------*/

void vtkOBJReader::Execute()
{
  if (!this->FileName)
    {
    vtkErrorMacro(<< "A FileName must be specified.");
    return;
    }

  FILE *in = fopen(this->FileName,"r");

  if (in == NULL)
    {
    vtkErrorMacro(<< "File " << this->FileName << " not found");
    return;
    }

  vtkDebugMacro(<<"Reading file");

  // intialise some structures to store the file contents in
  vtkPoints *points = vtkPoints::New();
  vtkFloatArray *tcoords = vtkFloatArray::New();
  tcoords->SetNumberOfComponents(2);
  vtkFloatArray *normals = vtkFloatArray::New();
  normals->SetNumberOfComponents(3);
  vtkCellArray *polys = vtkCellArray::New();
  vtkCellArray *tcoord_polys = vtkCellArray::New();
  int hasTCoords=0; // (false)
  int tcoords_same_as_verts=1; // (true)
  vtkCellArray *normal_polys = vtkCellArray::New();
  int hasNormals=0; // (false)
  int normals_same_as_verts=1; // (true)

  int everything_ok = 1; // (true)   (use of this flag avoids early return and associated memory leak)

  // -- work through the file line by line, assigning into the above six structures as appropriate --

  { // (make a local scope section to emphasise that the variables below are only used here)

  const int MAX_LINE=1024;
  char line[MAX_LINE],*pChar;
  float xyz[3];
  int iVert,iTCoord,iNormal;
  while (everything_ok && fgets(line,MAX_LINE,in)!=NULL)
    {

    // in the OBJ format the first characters determine how to interpret the line:
    if (strncmp(line,"v ",2)==0)
      {
      // this is a vertex definition, expect three floats, separated by whitespace:
      if (sscanf(line, "v %f %f %f", xyz, xyz + 1, xyz + 2)==3)
        {
        points->InsertNextPoint(xyz);
        }
      else
        {
        vtkErrorMacro(<<"Error in reading file");
        everything_ok=0; // (false)
        }
      }
    else if (strncmp(line,"vt ",3)==0)
      {
      // this is a tcoord, expect two floats, separated by whitespace:
      if (sscanf(line, "vt %f %f", xyz, xyz + 1)==2)
        {
        tcoords->InsertNextTuple(xyz);
        }
      else
        {
        vtkErrorMacro(<<"Error in reading file");
        everything_ok=0; // (false)
        }
      }
    else if (strncmp(line,"vn ",3)==0)
      {
      // this is a normal, expect three floats, separated by whitespace:
      if (sscanf(line, "vn %f %f %f", xyz, xyz + 1, xyz + 2)==3)
        {
        normals->InsertNextTuple(xyz);
        }
      else
        {
        vtkErrorMacro(<<"Error in reading file");
        everything_ok=0; // (false)
        }
      }
    else if (strncmp(line,"f ",2)==0 || strncmp(line,"fo ",3)==0)   // not sure why "fo" here
      {
      // this is a face definition, consisting of 1-based indices separated by whitespace and /

      polys->InsertNextCell(0); // we don't yet know how many points are to come
      tcoord_polys->InsertNextCell(0);
      normal_polys->InsertNextCell(0);

      int nVerts=0,nTCoords=0,nNormals=0; // keep a count of how many of each there are

      pChar = line + 2;
      const char *pEnd = line + strlen(line);

      while (everything_ok && pChar<pEnd)
        {
        // find the first non-whitespace character
        while (isspace(*pChar) && pChar<pEnd) { pChar++; }

        if (pChar<pEnd)         // there is still data left on this line
          {
          if (sscanf(pChar,"%d/%d/%d",&iVert,&iTCoord,&iNormal)==3)
            {
            polys->InsertCellPoint(iVert-1); // convert to 0-based index
            nVerts++;
            tcoord_polys->InsertCellPoint(iTCoord-1);
            nTCoords++;
            if (iTCoord!=iVert && tcoords_same_as_verts)
              tcoords_same_as_verts = 0; // (false)
            normal_polys->InsertCellPoint(iNormal-1);
            nNormals++;
            if (iNormal!=iVert && normals_same_as_verts)
              normals_same_as_verts = 0; // (false)
            }
          else if (sscanf(pChar,"%d//%d",&iVert,&iNormal)==2)
            {
            polys->InsertCellPoint(iVert-1);
            nVerts++;
            normal_polys->InsertCellPoint(iNormal-1);
            nNormals++;
            if (iNormal!=iVert && normals_same_as_verts)
              normals_same_as_verts = 0; // (false)
            }
          else if (sscanf(pChar,"%d/%d",&iVert,&iTCoord)==2)
            {
            polys->InsertCellPoint(iVert-1);
            nVerts++;
            tcoord_polys->InsertCellPoint(iTCoord-1);
            nTCoords++;
            if (iTCoord!=iVert && tcoords_same_as_verts)
              tcoords_same_as_verts = 0; // (false)
            }
          else if (sscanf(pChar,"%d",&iVert)==1)
            {
            polys->InsertCellPoint(iVert-1);
            nVerts++;
            }
          else
            {
            vtkErrorMacro(<<"Error in reading file");
            everything_ok=0; // (false)
            }
          // skip over what we just read
          // (find the first whitespace character)
          while (!isspace(*pChar) && pChar<pEnd) { pChar++; }

          }

        }

      // count of tcoords and normals must be equal to number of vertices or zero
      if (nVerts==0 || (nTCoords>0 && nTCoords!=nVerts) || (nNormals>0 && nNormals!=nVerts))
        {
        vtkErrorMacro(<<"Error in reading file");
        everything_ok=0; // (false)
        }

      // now we know how many points there were in this cell
      polys->UpdateCellCount(nVerts);
      tcoord_polys->UpdateCellCount(nTCoords);
      normal_polys->UpdateCellCount(nNormals);

      // also make a note of whether any cells have tcoords, and whether any have normals
      if (nTCoords>0 && !hasTCoords) { hasTCoords=1; }
      if (nNormals>0 && !hasNormals) { hasNormals=1; }
      }
    else
      {
      //vtkDebugMacro(<<"Ignoring line: "<<line);
      }

    } // (end of while loop)

  } // (end of local scope section)

  // we have finished with the file
  fclose(in);

  if (everything_ok)   // (otherwise just release allocated memory and return)
    {
    // -- now turn this lot into a useable vtkPolyData --

    // if there are no tcoords or normals or they match exactly
    // then we can just copy the data into the output (easy!)
    if ((!hasTCoords||tcoords_same_as_verts) && (!hasNormals||normals_same_as_verts))
      {
      vtkDebugMacro(<<"Copying file data into the output directly");

      this->GetOutput()->SetPoints(points);
      this->GetOutput()->SetPolys(polys);

      // if there is an exact correspondence between tcoords and vertices then can simply
      // assign the tcoords points as point data
      if (hasTCoords && tcoords_same_as_verts)
        this->GetOutput()->GetPointData()->SetTCoords(tcoords);

      // if there is an exact correspondence between normals and vertices then can simply
      // assign the normals as point data
      if (hasNormals && normals_same_as_verts)
        this->GetOutput()->GetPointData()->SetNormals(normals);

      this->GetOutput()->Squeeze();
      }
    // otherwise we can duplicate the vertices as necessary (a bit slower)
    else
      {
      vtkDebugMacro(<<"Duplicating vertices so that tcoords and normals are correct");

      vtkPoints *new_points = vtkPoints::New();
      vtkFloatArray *new_tcoords = vtkFloatArray::New();
      new_tcoords->SetNumberOfComponents(2);
      vtkFloatArray *new_normals = vtkFloatArray::New();
      new_normals->SetNumberOfComponents(3);
      vtkCellArray *new_polys = vtkCellArray::New();

      // for each poly, copy its vertices into new_points (and point at them)
      // also copy its tcoords into new_tcoords
      // also copy its normals into new_normals
      polys->InitTraversal();
      tcoord_polys->InitTraversal();
      normal_polys->InitTraversal();
      int i,j;
      int dummy_warning_prevention_mechanism[1];
      int n_pts=-1,*pts=dummy_warning_prevention_mechanism;
      int n_tcoord_pts=-1,*tcoord_pts=dummy_warning_prevention_mechanism;
      int n_normal_pts=-1,*normal_pts=dummy_warning_prevention_mechanism;
      for (i=0;i<polys->GetNumberOfCells();i++)
        {
        polys->GetNextCell(n_pts,pts);
        tcoord_polys->GetNextCell(n_tcoord_pts,tcoord_pts);
        normal_polys->GetNextCell(n_normal_pts,normal_pts);

        // If some vertices have tcoords and not others (likewise normals)
        // then we must do something else VTK will complain. (crash on render attempt)
        // Easiest solution is to delete polys that don't have complete tcoords (if there
        // are any tcoords in the dataset) or normals (if there are any normals in the dataset).

        if ( (n_pts!=n_tcoord_pts && hasTCoords) || (n_pts!=n_normal_pts && hasNormals) )
          {
          // skip this poly
          vtkDebugMacro(<<"Skipping poly "<<i+1<<" (1-based index)");
          }
        else
          {
          // copy the corresponding points, tcoords and normals across
          for (j=0;j<n_pts;j++)
            {
            // copy the tcoord for this point across (if there is one)
            if (n_tcoord_pts>0)
              new_tcoords->InsertNextTuple(tcoords->GetTuple(tcoord_pts[j]));
            // copy the normal for this point across (if there is one)
            if (n_normal_pts>0)
              new_normals->InsertNextTuple(normals->GetTuple(normal_pts[j]));
            // copy the vertex into the new structure and update
            // the vertex index in the polys structure (pts is a pointer into it)
            pts[j] = new_points->InsertNextPoint(points->GetPoint(pts[j]));
            }
          // copy this poly (pointing at the new points) into the new polys list
          new_polys->InsertNextCell(n_pts,pts);
          }
        }

      // use the new structures for the output
      this->GetOutput()->SetPoints(new_points);
      this->GetOutput()->SetPolys(new_polys);
      if (hasTCoords)
        this->GetOutput()->GetPointData()->SetTCoords(new_tcoords);
      if (hasNormals)
        this->GetOutput()->GetPointData()->SetNormals(new_normals);
      this->GetOutput()->Squeeze();

      new_points->Delete();
      new_polys->Delete();
      new_tcoords->Delete();
      new_normals->Delete();
      }
    }

  points->Delete();
  tcoords->Delete();
  normals->Delete();
  polys->Delete();
  tcoord_polys->Delete();
  normal_polys->Delete();
}

void vtkOBJReader::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "File Name: "
     << (this->FileName ? this->FileName : "(none)") << "\n";

}

<commit_msg>FIX: Replaced isspace() to avoid build problems on some systems.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkOBJReader.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkOBJReader.h"

#include "vtkCellArray.h"
#include "vtkFloatArray.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"

vtkCxxRevisionMacro(vtkOBJReader, "1.24");
vtkStandardNewMacro(vtkOBJReader);

// Description:
// Instantiate object with NULL filename.
vtkOBJReader::vtkOBJReader()
{
  this->FileName = NULL;
}

vtkOBJReader::~vtkOBJReader()
{
  if (this->FileName)
    {
    delete [] this->FileName;
    this->FileName = NULL;
    }
}

/*--------------------------------------------------------

This is only partial support for the OBJ format, which is
quite complicated. To find a full specification,
search the net for "OBJ format", eg.:

http://netghost.narod.ru/gff/graphics/summary/waveobj.htm

We support the following types:

v <x> <y> <z>              vertex

vn <x> <y> <z>             vertex normal

vt <x> <y>                 texture coordinate

f <v_a> <v_b> <v_c> ...

polygonal face linking vertices v_a, v_b, v_c, etc. which
are 1-based indices into the vertex list

f <v_a>/<t_a> <v_b>/<t_b> ...

polygonal face as above, but with texture coordinates for
each vertex. t_a etc. are 1-based indices into the texture
coordinates list (from the vt lines)

f <v_a>/<t_a>/<n_a> <v_b>/<t_b>/<n_b> ...

polygonal face as above, with a normal at each vertex, as a
1-based index into the normals list (from the vn lines)

f <v_a>//<n_a> <v_b>//<n_b> ...

polygonal face as above but without texture coordinates.

Per-face tcoords and normals are supported by duplicating
the vertices on each face as necessary.

---------------------------------------------------------*/

// a replacement for isspace()
int is_whitespace(char c)
{
  if ( c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f')
    return 1;
  else
    return 0;
}

void vtkOBJReader::Execute()
{
  if (!this->FileName)
    {
    vtkErrorMacro(<< "A FileName must be specified.");
    return;
    }

  FILE *in = fopen(this->FileName,"r");

  if (in == NULL)
    {
    vtkErrorMacro(<< "File " << this->FileName << " not found");
    return;
    }

  vtkDebugMacro(<<"Reading file");

  // intialise some structures to store the file contents in
  vtkPoints *points = vtkPoints::New();
  vtkFloatArray *tcoords = vtkFloatArray::New();
  tcoords->SetNumberOfComponents(2);
  vtkFloatArray *normals = vtkFloatArray::New();
  normals->SetNumberOfComponents(3);
  vtkCellArray *polys = vtkCellArray::New();
  vtkCellArray *tcoord_polys = vtkCellArray::New();
  int hasTCoords=0; // (false)
  int tcoords_same_as_verts=1; // (true)
  vtkCellArray *normal_polys = vtkCellArray::New();
  int hasNormals=0; // (false)
  int normals_same_as_verts=1; // (true)

  int everything_ok = 1; // (true)   (use of this flag avoids early return and associated memory leak)

  // -- work through the file line by line, assigning into the above six structures as appropriate --

  { // (make a local scope section to emphasise that the variables below are only used here)

  const int MAX_LINE=1024;
  char line[MAX_LINE],*pChar;
  float xyz[3];
  int iVert,iTCoord,iNormal;
  while (everything_ok && fgets(line,MAX_LINE,in)!=NULL)
    {

    // in the OBJ format the first characters determine how to interpret the line:
    if (strncmp(line,"v ",2)==0)
      {
      // this is a vertex definition, expect three floats, separated by whitespace:
      if (sscanf(line, "v %f %f %f", xyz, xyz + 1, xyz + 2)==3)
        {
        points->InsertNextPoint(xyz);
        }
      else
        {
        vtkErrorMacro(<<"Error in reading file");
        everything_ok=0; // (false)
        }
      }
    else if (strncmp(line,"vt ",3)==0)
      {
      // this is a tcoord, expect two floats, separated by whitespace:
      if (sscanf(line, "vt %f %f", xyz, xyz + 1)==2)
        {
        tcoords->InsertNextTuple(xyz);
        }
      else
        {
        vtkErrorMacro(<<"Error in reading file");
        everything_ok=0; // (false)
        }
      }
    else if (strncmp(line,"vn ",3)==0)
      {
      // this is a normal, expect three floats, separated by whitespace:
      if (sscanf(line, "vn %f %f %f", xyz, xyz + 1, xyz + 2)==3)
        {
        normals->InsertNextTuple(xyz);
        }
      else
        {
        vtkErrorMacro(<<"Error in reading file");
        everything_ok=0; // (false)
        }
      }
    else if (strncmp(line,"f ",2)==0 || strncmp(line,"fo ",3)==0)   // not sure why "fo" here
      {
      // this is a face definition, consisting of 1-based indices separated by whitespace and /

      polys->InsertNextCell(0); // we don't yet know how many points are to come
      tcoord_polys->InsertNextCell(0);
      normal_polys->InsertNextCell(0);

      int nVerts=0,nTCoords=0,nNormals=0; // keep a count of how many of each there are

      pChar = line + 2;
      const char *pEnd = line + strlen(line);

      while (everything_ok && pChar<pEnd)
        {
        // find the first non-whitespace character
        while (is_whitespace(*pChar) && pChar<pEnd) { pChar++; }

        if (pChar<pEnd)         // there is still data left on this line
          {
          if (sscanf(pChar,"%d/%d/%d",&iVert,&iTCoord,&iNormal)==3)
            {
            polys->InsertCellPoint(iVert-1); // convert to 0-based index
            nVerts++;
            tcoord_polys->InsertCellPoint(iTCoord-1);
            nTCoords++;
            if (iTCoord!=iVert && tcoords_same_as_verts)
              tcoords_same_as_verts = 0; // (false)
            normal_polys->InsertCellPoint(iNormal-1);
            nNormals++;
            if (iNormal!=iVert && normals_same_as_verts)
              normals_same_as_verts = 0; // (false)
            }
          else if (sscanf(pChar,"%d//%d",&iVert,&iNormal)==2)
            {
            polys->InsertCellPoint(iVert-1);
            nVerts++;
            normal_polys->InsertCellPoint(iNormal-1);
            nNormals++;
            if (iNormal!=iVert && normals_same_as_verts)
              normals_same_as_verts = 0; // (false)
            }
          else if (sscanf(pChar,"%d/%d",&iVert,&iTCoord)==2)
            {
            polys->InsertCellPoint(iVert-1);
            nVerts++;
            tcoord_polys->InsertCellPoint(iTCoord-1);
            nTCoords++;
            if (iTCoord!=iVert && tcoords_same_as_verts)
              tcoords_same_as_verts = 0; // (false)
            }
          else if (sscanf(pChar,"%d",&iVert)==1)
            {
            polys->InsertCellPoint(iVert-1);
            nVerts++;
            }
          else
            {
            vtkErrorMacro(<<"Error in reading file");
            everything_ok=0; // (false)
            }
          // skip over what we just read
          // (find the first whitespace character)
          while (!is_whitespace(*pChar) && pChar<pEnd) { pChar++; }

          }

        }

      // count of tcoords and normals must be equal to number of vertices or zero
      if (nVerts==0 || (nTCoords>0 && nTCoords!=nVerts) || (nNormals>0 && nNormals!=nVerts))
        {
        vtkErrorMacro(<<"Error in reading file");
        everything_ok=0; // (false)
        }

      // now we know how many points there were in this cell
      polys->UpdateCellCount(nVerts);
      tcoord_polys->UpdateCellCount(nTCoords);
      normal_polys->UpdateCellCount(nNormals);

      // also make a note of whether any cells have tcoords, and whether any have normals
      if (nTCoords>0 && !hasTCoords) { hasTCoords=1; }
      if (nNormals>0 && !hasNormals) { hasNormals=1; }
      }
    else
      {
      //vtkDebugMacro(<<"Ignoring line: "<<line);
      }

    } // (end of while loop)

  } // (end of local scope section)

  // we have finished with the file
  fclose(in);

  if (everything_ok)   // (otherwise just release allocated memory and return)
    {
    // -- now turn this lot into a useable vtkPolyData --

    // if there are no tcoords or normals or they match exactly
    // then we can just copy the data into the output (easy!)
    if ((!hasTCoords||tcoords_same_as_verts) && (!hasNormals||normals_same_as_verts))
      {
      vtkDebugMacro(<<"Copying file data into the output directly");

      this->GetOutput()->SetPoints(points);
      this->GetOutput()->SetPolys(polys);

      // if there is an exact correspondence between tcoords and vertices then can simply
      // assign the tcoords points as point data
      if (hasTCoords && tcoords_same_as_verts)
        this->GetOutput()->GetPointData()->SetTCoords(tcoords);

      // if there is an exact correspondence between normals and vertices then can simply
      // assign the normals as point data
      if (hasNormals && normals_same_as_verts)
        this->GetOutput()->GetPointData()->SetNormals(normals);

      this->GetOutput()->Squeeze();
      }
    // otherwise we can duplicate the vertices as necessary (a bit slower)
    else
      {
      vtkDebugMacro(<<"Duplicating vertices so that tcoords and normals are correct");

      vtkPoints *new_points = vtkPoints::New();
      vtkFloatArray *new_tcoords = vtkFloatArray::New();
      new_tcoords->SetNumberOfComponents(2);
      vtkFloatArray *new_normals = vtkFloatArray::New();
      new_normals->SetNumberOfComponents(3);
      vtkCellArray *new_polys = vtkCellArray::New();

      // for each poly, copy its vertices into new_points (and point at them)
      // also copy its tcoords into new_tcoords
      // also copy its normals into new_normals
      polys->InitTraversal();
      tcoord_polys->InitTraversal();
      normal_polys->InitTraversal();
      int i,j;
      int dummy_warning_prevention_mechanism[1];
      int n_pts=-1,*pts=dummy_warning_prevention_mechanism;
      int n_tcoord_pts=-1,*tcoord_pts=dummy_warning_prevention_mechanism;
      int n_normal_pts=-1,*normal_pts=dummy_warning_prevention_mechanism;
      for (i=0;i<polys->GetNumberOfCells();i++)
        {
        polys->GetNextCell(n_pts,pts);
        tcoord_polys->GetNextCell(n_tcoord_pts,tcoord_pts);
        normal_polys->GetNextCell(n_normal_pts,normal_pts);

        // If some vertices have tcoords and not others (likewise normals)
        // then we must do something else VTK will complain. (crash on render attempt)
        // Easiest solution is to delete polys that don't have complete tcoords (if there
        // are any tcoords in the dataset) or normals (if there are any normals in the dataset).

        if ( (n_pts!=n_tcoord_pts && hasTCoords) || (n_pts!=n_normal_pts && hasNormals) )
          {
          // skip this poly
          vtkDebugMacro(<<"Skipping poly "<<i+1<<" (1-based index)");
          }
        else
          {
          // copy the corresponding points, tcoords and normals across
          for (j=0;j<n_pts;j++)
            {
            // copy the tcoord for this point across (if there is one)
            if (n_tcoord_pts>0)
              new_tcoords->InsertNextTuple(tcoords->GetTuple(tcoord_pts[j]));
            // copy the normal for this point across (if there is one)
            if (n_normal_pts>0)
              new_normals->InsertNextTuple(normals->GetTuple(normal_pts[j]));
            // copy the vertex into the new structure and update
            // the vertex index in the polys structure (pts is a pointer into it)
            pts[j] = new_points->InsertNextPoint(points->GetPoint(pts[j]));
            }
          // copy this poly (pointing at the new points) into the new polys list
          new_polys->InsertNextCell(n_pts,pts);
          }
        }

      // use the new structures for the output
      this->GetOutput()->SetPoints(new_points);
      this->GetOutput()->SetPolys(new_polys);
      if (hasTCoords)
        this->GetOutput()->GetPointData()->SetTCoords(new_tcoords);
      if (hasNormals)
        this->GetOutput()->GetPointData()->SetNormals(new_normals);
      this->GetOutput()->Squeeze();

      new_points->Delete();
      new_polys->Delete();
      new_tcoords->Delete();
      new_normals->Delete();
      }
    }

  points->Delete();
  tcoords->Delete();
  normals->Delete();
  polys->Delete();
  tcoord_polys->Delete();
  normal_polys->Delete();
}

void vtkOBJReader::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "File Name: "
     << (this->FileName ? this->FileName : "(none)") << "\n";

}

<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 6/23/2019, 5:37:29 AM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <memory>
#include <algorithm>

template <typename T, typename A = std::allocator<T>>
struct vector_base
{ // vector のためのメモリ構造
  A alloc;
  T *elem;  // 先頭
  T *space; // 拡張用領域の先頭
  T *last;  // 終端

  vector_base(const A &a, typename A::size_type n = 0, typename A::size_type m = 0)
      : alloc{a}, elem{alloc.allocate(n + m)}, space{elem + n}, last{elem + n + m} {}

  ~vector_base() { alloc.deallocate(elem, last - elem); }

  vector_base(const vector_base &) = delete;            // コピー演算は行えない
  vector_base &operator=(const vector_base &) = delete; // コピー代入演算子も無効化

  vector_base(vector_base &&);            // ムーブ演算を行う
  vector_base &operator=(vector_base &&); // ムーブ代入演算子
};

template <typename T, typename A = std::allocator<T>>
class vector
{
private:
  vector_base<T, A> vb;
  void destroy_elements();

public:
  using size_type = typename A::size_type; // vector 要素用の型
  explicit vector(size_type n = 0, const T &val = T(), const A &a = A());

  ~vector() { destroy_elements(); };

  vector(const vector &a);            // コピーコンストラクタ
  vector &operator=(const vector &a); // コピー代入演算子

  vector(vector &&a);            // ムーブコンストラクタ
  vector &operator=(vector &&a); // ムーブ代入演算子

  size_type size() const { return vb.space - vb.elem; }
  size_type capacity() const { return vb.last - vb.elem; }
  void reserve(size_type n);                // 容量を n まで増やす
  void resize(size_type n, const T & = {}); // 要素数を n に変更
  void clear() { resize(0); }
  void push_back(const T &);

  T *begin() { return vb.elem; }
  T *end() { return vb.space; }
  const T &operator[](const size_type t) const { return *(vb.elem + t); }
  T &operator[](const size_type t) { return *(vb.elem + t); }
};

template <typename T, typename A>
vector_base<T, A>::vector_base(vector_base &&a)
    : alloc{a.alloc}, elem{a.elem}, space{a.space}, last{a.last}
{
  a.elem = a.space = a.last = nullptr;
}

template <typename T, typename A>
vector_base<T, A> &vector_base<T, A>::operator=(vector_base &&a)
{
  std::swap(*this, a);
  return *this;
}

template <typename T, typename A>
void vector<T, A>::destroy_elements()
{
  for (T *p = vb.elem; p != vb.space; ++p)
  {
    p->~T();
  }
  vb.space = vb.elem;
}

template <typename T, typename A>
vector<T, A>::vector(size_type n, const T &val, const A &a) : vb{a, n}
{
  std::uninitialized_fill(vb.elem, vb.elem + n, val);
}

template <typename T, typename A>
vector<T, A>::vector(const vector &a) : vb{a.vb.alloc, a.size()}
{
  std::uninitialized_copy(a.begin(), a.end(), vb.elem);
}

template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(const vector &a)
{
  vector temp{a};
  std::swap(*this, temp);
  return *this;
}

template <typename T, typename A>
vector<T, A>::vector(vector &&a) : vb{std::move(a.vb)} {}

template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(vector &&a)
{
  std::swap(vb, a.vb);
  return *this;
}

/*
template <typename C>
using Value_type = typename C::value_type;

template <typename In, typename Out>
Out uninitialized_move(In b, In e, Out oo)
{
  using T = Value_type<Out>;
  for (; b != e; ++b, ++oo)
  {
    new (static_cast<void *>(&*oo)) T{std::move(*b)};
    b->~T();
  }
  return oo;
}
*/

template <typename T, typename A>
void vector<T, A>::reserve(size_type new_alloc)
{
  if (new_alloc <= capacity())
  {
    return;
  }
  vector_base<T, A> b{vb.alloc, new_alloc - size()};
  // uninitialized_move(vb.elem, vb.elem + size(), b.elem);
  T *begin = vb.elem;
  T *end = vb.elem + size();
  T *oo = b.elem;
  for (; begin != end; ++begin, ++oo)
  {
    new (static_cast<void *>(&*oo)) T{std::move(*begin)};
    begin->~T();
  }
  std::swap(vb, b);
}

/*
template <typename In>
void destroy(In b, In e)
{
  for (; b != e; ++b)
  {
    b->~Value_type<In>();
  }
}
*/

template <typename T, typename A>
void vector<T, A>::resize(size_type new_size, const T &val)
{
  reserve(new_size);
  if (size() < new_size)
  {
    std::uninitialized_fill(vb.elem + size(), vb.elem + new_size, val);
  }
  else
  {
    auto b = vb.elem + new_size;
    auto e = vb.elem + size();
    for (; b != e; ++b)
    {
      b->~T();
    }
  }
  vb.space = vb.elem + new_size;
}

template <typename T, typename A>
void vector<T, A>::push_back(const T &val)
{
  if (capacity() == size())
  {
    reserve(size() ? 2 * size() : 8);
#if DEBUG == 1
    std::cerr << "aaa" << std::endl;
#endif
  }
  vb.alloc.construct(&vb.elem[size()], val);
  ++vb.space;
}

typedef long long ll;

int N;
typedef std::pair<ll, ll> work;
vector<work> V;

int main()
{
  std::cin >> N;
  for (auto i = 0; i < N; i++)
  {
    ll a, b;
    std::cin >> a >> b;
    V.push_back(work(b, a));
  }
  std::sort(V.begin(), V.end());
  ll now = 0;
  for (auto i = 0; i < N; i++)
  {
    now += V[i].first;
    if (now > V[i].second)
    {
      std::cout << "No" << std::endl;
      return 0;
    }
  }
  std::cout << "Yes" << std::endl;
}<commit_msg>tried D2.cpp to 'D'<commit_after>#define DEBUG 1
/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 6/23/2019, 5:37:29 AM
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <memory>
#include <algorithm>

template <typename T, typename A = std::allocator<T>>
struct vector_base
{ // vector のためのメモリ構造
  A alloc;
  T *elem;  // 先頭
  T *space; // 拡張用領域の先頭
  T *last;  // 終端

  vector_base(const A &a, typename A::size_type n = 0, typename A::size_type m = 0)
      : alloc{a}, elem{alloc.allocate(n + m)}, space{elem + n}, last{elem + n + m} {}

  ~vector_base() { alloc.deallocate(elem, last - elem); }

  vector_base(const vector_base &) = delete;            // コピー演算は行えない
  vector_base &operator=(const vector_base &) = delete; // コピー代入演算子も無効化

  vector_base(vector_base &&);            // ムーブ演算を行う
  vector_base &operator=(vector_base &&); // ムーブ代入演算子
};

template <typename T, typename A = std::allocator<T>>
class vector
{
private:
  vector_base<T, A> vb;
  void destroy_elements();

public:
  using size_type = typename A::size_type; // vector 要素用の型
  explicit vector(size_type n = 0, const T &val = T(), const A &a = A());

  ~vector() { destroy_elements(); };

  vector(const vector &a);            // コピーコンストラクタ
  vector &operator=(const vector &a); // コピー代入演算子

  vector(vector &&a);            // ムーブコンストラクタ
  vector &operator=(vector &&a); // ムーブ代入演算子

  size_type size() const { return vb.space - vb.elem; }
  size_type capacity() const { return vb.last - vb.elem; }
  void reserve(size_type n);                // 容量を n まで増やす
  void resize(size_type n, const T & = {}); // 要素数を n に変更
  void clear() { resize(0); }
  void push_back(const T &);

  T *begin() { return vb.elem; }
  T *end() { return vb.space; }
  const T &operator[](const size_type t) const { return *(vb.elem + t); }
  T &operator[](const size_type t) { return *(vb.elem + t); }
};

template <typename T, typename A>
vector_base<T, A>::vector_base(vector_base &&a)
    : alloc{a.alloc}, elem{a.elem}, space{a.space}, last{a.last}
{
  a.elem = a.space = a.last = nullptr;
}

template <typename T, typename A>
vector_base<T, A> &vector_base<T, A>::operator=(vector_base &&a)
{
  std::swap(*this, a);
  return *this;
}

template <typename T, typename A>
void vector<T, A>::destroy_elements()
{
  for (T *p = vb.elem; p != vb.space; ++p)
  {
    p->~T();
  }
  vb.space = vb.elem;
}

template <typename T, typename A>
vector<T, A>::vector(size_type n, const T &val, const A &a) : vb{a, n}
{
  std::uninitialized_fill(vb.elem, vb.elem + n, val);
}

template <typename T, typename A>
vector<T, A>::vector(const vector &a) : vb{a.vb.alloc, a.size()}
{
  std::uninitialized_copy(a.begin(), a.end(), vb.elem);
}

template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(const vector &a)
{
  vector temp{a};
  std::swap(*this, temp);
  return *this;
}

template <typename T, typename A>
vector<T, A>::vector(vector &&a) : vb{std::move(a.vb)} {}

template <typename T, typename A>
vector<T, A> &vector<T, A>::operator=(vector &&a)
{
  std::swap(vb, a.vb);
  return *this;
}

/*
template <typename C>
using Value_type = typename C::value_type;

template <typename In, typename Out>
Out uninitialized_move(In b, In e, Out oo)
{
  using T = Value_type<Out>;
  for (; b != e; ++b, ++oo)
  {
    new (static_cast<void *>(&*oo)) T{std::move(*b)};
    b->~T();
  }
  return oo;
}
*/

template <typename T, typename A>
void vector<T, A>::reserve(size_type new_alloc)
{
  if (new_alloc <= capacity())
  {
    return;
  }
  vector_base<T, A> b{vb.alloc, new_alloc - size()};
  // uninitialized_move(vb.elem, vb.elem + size(), b.elem);
  T *begin = vb.elem;
  T *end = vb.elem + size();
  T *oo = b.elem;
  for (; begin != end; ++begin, ++oo)
  {
#if DEBUG == 1
    std::cerr << "aaa" << std::endl;
#endif
    new (static_cast<void *>(&*oo)) T{std::move(*begin)};
    begin->~T();
  }
  std::swap(vb, b);
}

/*
template <typename In>
void destroy(In b, In e)
{
  for (; b != e; ++b)
  {
    b->~Value_type<In>();
  }
}
*/

template <typename T, typename A>
void vector<T, A>::resize(size_type new_size, const T &val)
{
  reserve(new_size);
  if (size() < new_size)
  {
    std::uninitialized_fill(vb.elem + size(), vb.elem + new_size, val);
  }
  else
  {
    auto b = vb.elem + new_size;
    auto e = vb.elem + size();
    for (; b != e; ++b)
    {
      b->~T();
    }
  }
  vb.space = vb.elem + new_size;
}

template <typename T, typename A>
void vector<T, A>::push_back(const T &val)
{
  if (capacity() == size())
  {
    reserve(size() ? 2 * size() : 8);
  }
  vb.alloc.construct(&vb.elem[size()], val);
  ++vb.space;
}

typedef long long ll;

int N;
typedef std::pair<ll, ll> work;
vector<work> V;

int main()
{
  std::cin >> N;
  for (auto i = 0; i < N; i++)
  {
    ll a, b;
    std::cin >> a >> b;
    V.push_back(work(b, a));
  }
  std::sort(V.begin(), V.end());
  ll now = 0;
  for (auto i = 0; i < N; i++)
  {
    now += V[i].first;
    if (now > V[i].second)
    {
      std::cout << "No" << std::endl;
      return 0;
    }
  }
  std::cout << "Yes" << std::endl;
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 11/13/2019, 7:24:07 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <boost/rational.hpp>
using boost::rational;
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "0 1" << endl;
  exit(0);
}

using Info = tuple<ll, ll>;

int main()
{
  int N;
  cin >> N;
  vector<Info> V(N);
  ll A_sum{0LL};
  for (auto i = 0; i < N; i++)
  {
    ll A, B;
    cin >> A >> B;
    V[i] = Info(max(A, B), B);
    A_sum += A;
  }
  sort(V.rbegin(), V.rend());
  vector<ll> C_sum(N + 1);
  C_sum[0] = 0;
  for (auto i = 0; i < N; i++)
  {
    C_sum[i + 1] = C_sum[i] + get<0>(V[i]);
  }
  if (C_sum[N] == A_sum)
  {
    No();
  }
  rational<ll> ans{0, 1};
#if DEBUG == 1
  cerr << "A_sum = " << A_sum << endl;
#endif
  for (auto k = 0; k < N; k++)
  {
    ll B_k{get<1>(V[k])};
    ll ok{N}, ng{-1};
    ll tmp_sum{0};
    bool included{false};
    while (abs(ok - ng) > 1)
    {
      ll t{(ok + ng) / 2};
      ll tmp{C_sum[t]};
      if (k < t)
      {
        tmp -= B_k;
      }
      if (tmp + B_k >= A_sum)
      {
        ok = t;
        included = k < t;
        tmp_sum = tmp;
      }
      else
      {
        ng = t;
      }
    }
    rational<ll> r{A_sum - tmp_sum, B_k};
#if DEBUG == 1
    cerr << "k = " << k << ", B_k = " << B_k << ", tmp_sum = " << tmp_sum << ", r = " << r << endl;
#endif
    ll M{included ? ok - 1 : ok};
#if DEBUG == 1
    cerr << "ok = " << ok << ", included = " << included << ", M = " << M << ", r = " << r << endl;
#endif
    if (r < 0)
    {
      continue;
    }
    rational<ll> tmp_ans = (N - M - r) / N;
#if DEBUG == 1
    cerr << "tmp_ans = " << tmp_ans << endl;
#endif
    ch_max(ans, tmp_ans);
  }
  cout << ans.numerator() << " " << ans.denominator() << endl;
}
<commit_msg>tried D2.cpp to 'D'<commit_after>#define DEBUG 1
/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 11/13/2019, 7:24:07 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <boost/rational.hpp>
using boost::rational;
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "0 1" << endl;
  exit(0);
}

using Info = tuple<ll, ll>;

int main()
{
  int N;
  cin >> N;
  vector<Info> V(N);
  ll A_sum{0LL};
  for (auto i = 0; i < N; i++)
  {
    ll A, B;
    cin >> A >> B;
    V[i] = Info(max(A, B), B);
    A_sum += A;
  }
  sort(V.rbegin(), V.rend());
  vector<ll> C_sum(N + 1);
  C_sum[0] = 0;
  for (auto i = 0; i < N; i++)
  {
    C_sum[i + 1] = C_sum[i] + get<0>(V[i]);
  }
  if (C_sum[N] == A_sum)
  {
    No();
  }
  rational<ll> ans{0, 1};
#if DEBUG == 1
  cerr << "A_sum = " << A_sum << endl;
#endif
  for (auto k = 0; k < N; k++)
  {
    ll B_k{get<1>(V[k])};
    ll ok{N}, ng{-1};
    ll tmp_sum{0};
    bool included{false};
    while (abs(ok - ng) > 1)
    {
      ll t{(ok + ng) / 2};
      ll tmp{C_sum[t]};
      if (k < t)
      {
        tmp -= B_k;
      }
      if (tmp + B_k >= A_sum)
      {
        ok = t;
        included = k < t;
        tmp_sum = tmp;
      }
      else
      {
        ng = t;
      }
    }
    rational<ll> r{A_sum - tmp_sum, B_k};
#if DEBUG == 1
    cerr << "k = " << k << ", B_k = " << B_k << ", tmp_sum = " << tmp_sum << ", r = " << r << endl;
#endif
    ll M{included ? ok - 1 : ok};
#if DEBUG == 1
    cerr << "ok = " << ok << ", included = " << included << ", M = " << M << ", r = " << r << endl;
#endif
    rational<ll> tmp_ans = (N - M - r) / N;
#if DEBUG == 1
    cerr << "tmp_ans = " << tmp_ans << endl;
#endif
    if (r < 0)
    {
      continue;
    }
    ch_max(ans, tmp_ans);
  }
  cout << ans.numerator() << " " << ans.denominator() << endl;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "graph.hpp"

namespace gt = testing;

namespace pk
{
namespace testing
{

struct graph_tester : public gt::Test
{
    static const int VERTICES = 3;
    static const int MAX_VERTEX_DEGREE = 5;

    typedef graph<VERTICES, MAX_VERTEX_DEGREE> graph_type;

    // tested class:
    graph_type g;
};

TEST_F(graph_tester, tests_empty_graph)
{
    // given
    ASSERT_EQ(3, g.size());

    // when and then
    EXPECT_EQ(0, g.get_adjacency_list(0).size());
    EXPECT_EQ(0, g.get_adjacency_list(1).size());
    EXPECT_EQ(0, g.get_adjacency_list(2).size());
}

TEST_F(graph_tester, tests_full_graph)
{
    // given
    ASSERT_EQ(3, g.size());

    // when
    g.add_not_directed_edge(0, 1);
    g.add_not_directed_edge(0, 2);
    g.add_not_directed_edge(1, 2);

    // then
    const graph_type::adjacency_list& adj0 = g.get_adjacency_list(0);
    ASSERT_EQ(2, adj0.size());
    EXPECT_EQ(1, adj0[0]);
    EXPECT_EQ(2, adj0[1]);

    const graph_type::adjacency_list& adj1 = g.get_adjacency_list(1);
    ASSERT_EQ(2, adj1.size());
    EXPECT_EQ(0, adj1[0]);
    EXPECT_EQ(2, adj1[1]);

    const graph_type::adjacency_list& adj2 = g.get_adjacency_list(2);
    ASSERT_EQ(2, adj2.size());
    EXPECT_EQ(0, adj2[0]);
    EXPECT_EQ(1, adj2[1]);
}

TEST_F(graph_tester, test_adding_directed_edge)
{
    // given
    ASSERT_EQ(3, g.size());

    // when
    g.add_directed_edge(1, 2);

    // then
    const graph_type::adjacency_list& adj0 = g.get_adjacency_list(0);
    EXPECT_EQ(0, adj0.size());

    const graph_type::adjacency_list& adj1 = g.get_adjacency_list(1);
    ASSERT_EQ(1, adj1.size());
    EXPECT_EQ(2, adj1[0]);

    const graph_type::adjacency_list& adj2 = g.get_adjacency_list(2);
    EXPECT_EQ(0, adj2.size());
}

} // namespace testing
} // namespace pk
<commit_msg>Unit tests for graph::add_not_directed_edge() added<commit_after>#include <gtest/gtest.h>

#include "graph.hpp"

namespace gt = testing;

namespace pk
{
namespace testing
{

struct graph_tester : public gt::Test
{
    static const int VERTICES = 3;
    static const int MAX_VERTEX_DEGREE = 5;

    typedef graph<VERTICES, MAX_VERTEX_DEGREE> graph_type;

    // tested class:
    graph_type g;
};

TEST_F(graph_tester, tests_empty_graph)
{
    // given
    ASSERT_EQ(3, g.size());

    // when and then
    EXPECT_EQ(0, g.get_adjacency_list(0).size());
    EXPECT_EQ(0, g.get_adjacency_list(1).size());
    EXPECT_EQ(0, g.get_adjacency_list(2).size());
}

TEST_F(graph_tester, tests_full_graph)
{
    // given
    ASSERT_EQ(3, g.size());

    // when
    g.add_not_directed_edge(0, 1);
    g.add_not_directed_edge(0, 2);
    g.add_not_directed_edge(1, 2);

    // then
    const graph_type::adjacency_list& adj0 = g.get_adjacency_list(0);
    ASSERT_EQ(2, adj0.size());
    EXPECT_EQ(1, adj0[0]);
    EXPECT_EQ(2, adj0[1]);

    const graph_type::adjacency_list& adj1 = g.get_adjacency_list(1);
    ASSERT_EQ(2, adj1.size());
    EXPECT_EQ(0, adj1[0]);
    EXPECT_EQ(2, adj1[1]);

    const graph_type::adjacency_list& adj2 = g.get_adjacency_list(2);
    ASSERT_EQ(2, adj2.size());
    EXPECT_EQ(0, adj2[0]);
    EXPECT_EQ(1, adj2[1]);
}

TEST_F(graph_tester, test_adding_directed_edge)
{
    // given
    ASSERT_EQ(3, g.size());

    // when
    g.add_directed_edge(1, 2);

    // then
    const graph_type::adjacency_list& adj0 = g.get_adjacency_list(0);
    EXPECT_EQ(0, adj0.size());

    const graph_type::adjacency_list& adj1 = g.get_adjacency_list(1);
    ASSERT_EQ(1, adj1.size());
    EXPECT_EQ(2, adj1[0]);

    const graph_type::adjacency_list& adj2 = g.get_adjacency_list(2);
    EXPECT_EQ(0, adj2.size());
}

TEST_F(graph_tester, test_adding_not_directed_edge)
{
    // given
    ASSERT_EQ(3, g.size());

    // when
    g.add_not_directed_edge(1, 2);

    // then
    const graph_type::adjacency_list& adj0 = g.get_adjacency_list(0);
    EXPECT_EQ(0, adj0.size());

    const graph_type::adjacency_list& adj1 = g.get_adjacency_list(1);
    ASSERT_EQ(1, adj1.size());
    EXPECT_EQ(2, adj1[0]);

    const graph_type::adjacency_list& adj2 = g.get_adjacency_list(2);
    EXPECT_EQ(1, adj2.size());
    EXPECT_EQ(1, adj2[0]);
}

} // namespace testing
} // namespace pk
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 11/13/2019, 7:24:07 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <boost/rational.hpp>
using boost::rational;
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "0 1" << endl;
  exit(0);
}

using Info = tuple<ll, ll>;

int main()
{
  int N;
  cin >> N;
  vector<Info> V(N);
  ll A_sum{0LL};
  for (auto i = 0; i < N; i++)
  {
    ll A, B;
    cin >> A >> B;
    V[i] = Info(A + B, B);
    A_sum += A;
  }
  sort(V.rbegin(), V.rend());
  vector<ll> C_sum(N + 1);
  C_sum[0] = 0;
  for (auto i = 0; i < N; i++)
  {
    C_sum[i + 1] = C_sum[i] + get<0>(V[i]);
  }
  if (C_sum[N] == A_sum)
  {
    No();
  }
  rational<ll> ans{0, 1};
  for (auto k = 0; k < N; k++)
  {
    ll B_k{get<1>(V[k])};
    ll ok{N}, ng{-1};
    ll tmp_sum{0};
    while (abs(ok - ng) > 1)
    {
      ll t{(ok + ng) / 2};
      ll tmp{C_sum[t]};
      if (k < t)
      {
        tmp -= C_sum[t];
      }
      if (tmp + B_k >= A_sum)
      {
        ok = t;
        tmp_sum = tmp;
      }
      else
      {
        ng = t;
      }
    }
    rational<ll> r{A_sum - tmp_sum, B_k};
    assert(0 <= r && r <= 1);
    rational<ll> tmp_ans = (N - ok - r) / N;
    ch_max(ans, tmp_ans);
  }
  cout << ans.numerator() << " " << ans.denominator() << endl;
}
<commit_msg>tried D2.cpp to 'D'<commit_after>#define DEBUG 1
/**
 * File    : D2.cpp
 * Author  : Kazune Takahashi
 * Created : 11/13/2019, 7:24:07 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <boost/rational.hpp>
using boost::rational;
using namespace std;
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
using ll = long long;
constexpr ll MOD{1000000007LL};
constexpr ll MAX_SIZE{3000010LL};
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// for C++14
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "0 1" << endl;
  exit(0);
}

using Info = tuple<ll, ll>;

int main()
{
  int N;
  cin >> N;
  vector<Info> V(N);
  ll A_sum{0LL};
  for (auto i = 0; i < N; i++)
  {
    ll A, B;
    cin >> A >> B;
    V[i] = Info(A + B, B);
    A_sum += A;
  }
  sort(V.rbegin(), V.rend());
  vector<ll> C_sum(N + 1);
  C_sum[0] = 0;
  for (auto i = 0; i < N; i++)
  {
    C_sum[i + 1] = C_sum[i] + get<0>(V[i]);
  }
  if (C_sum[N] == A_sum)
  {
    No();
  }
  rational<ll> ans{0, 1};
  for (auto k = 0; k < N; k++)
  {
    ll B_k{get<1>(V[k])};
    ll ok{N}, ng{-1};
    ll tmp_sum{0};
    while (abs(ok - ng) > 1)
    {
      ll t{(ok + ng) / 2};
      ll tmp{C_sum[t]};
      if (k < t)
      {
        tmp -= C_sum[t];
      }
      if (tmp + B_k >= A_sum)
      {
        ok = t;
        tmp_sum = tmp;
      }
      else
      {
        ng = t;
      }
    }
#if DEBUG == 1
    cerr << "ok = " << ok << endl;
#endif
    rational<ll> r{A_sum - tmp_sum, B_k};
    assert(0 <= r && r <= 1);
    rational<ll> tmp_ans = (N - ok - r) / N;
    ch_max(ans, tmp_ans);
  }
  cout << ans.numerator() << " " << ans.denominator() << endl;
}
<|endoftext|>