problem_id
stringlengths 2
6
| contest
stringlengths 1
4
| problem
stringlengths 1
3
| lang
stringclasses 2
values | problem_title
stringlengths 0
63
| problem_statement
stringlengths 0
13.7k
| page
stringlengths 11.2k
95.4k
| long_tags
stringlengths 2
1.79k
| short_tags
stringlengths 2
657
| tutorial_link
stringlengths 0
87
| tutorial_page
stringlengths 0
1.22M
|
---|---|---|---|---|---|---|---|---|---|---|
1392A | 1392 | A | ru | A. Омкар и пароль | <div class="problem-statement"><div class="header"><div class="title">A. Омкар и пароль</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Лорд Омкар разрешил тебе войти в Храм Омкара! Чтобы проверить, достоин ли ты, Омкар дает тебе пароль, который ты должен понять!</p><p>Пароль представляет собой массив $$$a$$$ из $$$n$$$ положительных целых чисел. Вы можете применить к массиву следующую операцию: выбрать любые два соседних числа, которые не равны друг другу, и заменить их на их сумму. Формально, вы должны выбрать индекс $$$i$$$ такой, что $$$1 \leq i < n$$$ и $$$a_{i} \neq a_{i+1}$$$, удалить $$$a_i$$$ и $$$a_{i+1}$$$ с массива, и на их место вставить $$$a_{i}+a_{i+1}$$$. </p><p>Например, для массива $$$[7, 4, 3, 7]$$$ можно выбрать $$$i = 2$$$ и массив станет равным $$$[7, 4+3, 7] = [7, 7, 7]$$$. Обратите внимание, что в этом массиве уже не получится применить данную операцию.</p><p>Обратите внимание, что одна операция уменьшает длину пароля на $$$1$$$. Какую наименьшую длину пароля можно получить после некоторого количества (возможно $$$0$$$) операций?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — длину пароля.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — начальное содержимое вашего пароля.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого пароля выведите одно целое число — наименьшую возможную длину пароля после некоторого количества операций.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
4
2 1 3 1
2
420 420
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы можете сделать следующее для достижения длины в $$$1$$$:</p><p>Выберите $$$i=2$$$, чтобы получить $$$[2, 4, 1]$$$.</p><p>Выберите $$$i=1$$$, чтобы получить $$$[6, 1]$$$.</p><p>Выберите $$$i=1$$$, чтобы получить $$$[7]$$$.</p><p>Во втором наборе входных данных вы не можете выполнить ни одной операции, потому что нет $$$i$$$, которые удовлетворяли бы вышеперечисленным требованиям.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="e5fef1c039892790cf7a7b67408f0cbc"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='e5fef1c039892790cf7a7b67408f0cbc'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='e5fef1c039892790cf7a7b67408f0cbc'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='e5fef1c039892790cf7a7b67408f0cbc'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e5fef1c039892790cf7a7b67408f0cbc'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700617"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e5fef1c039892790cf7a7b67408f0cbc'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700617"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_8c6022de058d07032a31c22b0d40fec4ddd61054">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Омкар и пароль</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Лорд Омкар разрешил тебе войти в Храм Омкара! Чтобы проверить, достоин ли ты, Омкар дает тебе пароль, который ты должен понять!</p><p>Пароль представляет собой массив $$$a$$$ из $$$n$$$ положительных целых чисел. Вы можете применить к массиву следующую операцию: выбрать любые два соседних числа, которые не равны друг другу, и заменить их на их сумму. Формально, вы должны выбрать индекс $$$i$$$ такой, что $$$1 \leq i < n$$$ и $$$a_{i} \neq a_{i+1}$$$, удалить $$$a_i$$$ и $$$a_{i+1}$$$ с массива, и на их место вставить $$$a_{i}+a_{i+1}$$$. </p><p>Например, для массива $$$[7, 4, 3, 7]$$$ можно выбрать $$$i = 2$$$ и массив станет равным $$$[7, 4+3, 7] = [7, 7, 7]$$$. Обратите внимание, что в этом массиве уже не получится применить данную операцию.</p><p>Обратите внимание, что одна операция уменьшает длину пароля на $$$1$$$. Какую наименьшую длину пароля можно получить после некоторого количества (возможно $$$0$$$) операций?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — длину пароля.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 10^9$$$) — начальное содержимое вашего пароля.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого пароля выведите одно целое число — наименьшую возможную длину пароля после некоторого количества операций.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
4
2 1 3 1
2
420 420
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных вы можете сделать следующее для достижения длины в $$$1$$$:</p><p>Выберите $$$i=2$$$, чтобы получить $$$[2, 4, 1]$$$.</p><p>Выберите $$$i=1$$$, чтобы получить $$$[6, 1]$$$.</p><p>Выберите $$$i=1$$$, чтобы получить $$$[7]$$$.</p><p>Во втором наборе входных данных вы не можете выполнить ни одной операции, потому что нет $$$i$$$, которые удовлетворяли бы вышеперечисленным требованиям.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:38</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8445e383374',t:'MTY5NjY2NjExOC4xMTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"] | ||
1392B | 1392 | B | ru | B. Омкар и Часы Бесконечности | <div class="problem-statement"><div class="header"><div class="title">B. Омкар и Часы Бесконечности</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Когда Рэй застрял дома, ему стало очень скучно. Чтобы скоротать время, он просит лорда Омкара использовать силу, сгибающую время: Часы Бесконечности! Однако, Лорд Омкар будет слушать только смертных, которые могут решить следующую задачу:</p><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел. Вам также дается целое $$$k$$$. Лорд Омкар хочет, чтобы вы сделали с этим массивом $$$k$$$ операций.</p><p>Определим одну операцию следующим образом: </p><ol> <li> Пусть $$$d$$$ равно максимальному значению вашего массива. </li><li> Для каждого $$$i$$$ от $$$1$$$ до $$$n$$$ замените $$$a_{i}$$$ на $$$d-a_{i}$$$. </li></ol><p>Цель — предсказать содержимое массива после $$$k$$$ операций. Пожалуйста, помогите Рэю определить, как будет выглядеть окончательный массив!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}$$$) — длину вашего массива и количество операций, которые необходимо выполнить.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_{1},a_{2},...,a_{n}$$$ $$$(-10^9 \leq a_{i} \leq 10^9)$$$ — начальное содержимое массива.</p><p>Гарантируется, что сумма $$$n$$$ по наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого случая выведите финальную версию массива $$$a$$$ после описанных выше $$$k$$$ операций.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
2 1
-199 192
5 19
5 -1 4 2 0
1 2
69
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
391 0
0 6 1 3 5
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных массив изменяется следующим образом:</p><ul><li><p>Изначально массив равен $$$[-199, 192]$$$. $$$d = 192$$$.</p></li><li><p>После операции массив становится равным $$$[d-(-199), d-192] = [391, 0]$$$.</p></li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="a7be71cdd8c0d9e3a761f96059ea9b04"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='a7be71cdd8c0d9e3a761f96059ea9b04'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='a7be71cdd8c0d9e3a761f96059ea9b04'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='a7be71cdd8c0d9e3a761f96059ea9b04'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a7be71cdd8c0d9e3a761f96059ea9b04'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700618"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a7be71cdd8c0d9e3a761f96059ea9b04'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700618"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_b3967588116ec66da741bdcad9293a77750e95ed">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Омкар и Часы Бесконечности</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Когда Рэй застрял дома, ему стало очень скучно. Чтобы скоротать время, он просит лорда Омкара использовать силу, сгибающую время: Часы Бесконечности! Однако, Лорд Омкар будет слушать только смертных, которые могут решить следующую задачу:</p><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел. Вам также дается целое $$$k$$$. Лорд Омкар хочет, чтобы вы сделали с этим массивом $$$k$$$ операций.</p><p>Определим одну операцию следующим образом: </p><ol> <li> Пусть $$$d$$$ равно максимальному значению вашего массива. </li><li> Для каждого $$$i$$$ от $$$1$$$ до $$$n$$$ замените $$$a_{i}$$$ на $$$d-a_{i}$$$. </li></ol><p>Цель — предсказать содержимое массива после $$$k$$$ операций. Пожалуйста, помогите Рэю определить, как будет выглядеть окончательный массив!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}$$$) — длину вашего массива и количество операций, которые необходимо выполнить.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_{1},a_{2},...,a_{n}$$$ $$$(-10^9 \leq a_{i} \leq 10^9)$$$ — начальное содержимое массива.</p><p>Гарантируется, что сумма $$$n$$$ по наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого случая выведите финальную версию массива $$$a$$$ после описанных выше $$$k$$$ операций.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
2 1
-199 192
5 19
5 -1 4 2 0
1 2
69
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
391 0
0 6 1 3 5
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных массив изменяется следующим образом:</p><ul><li><p>Изначально массив равен $$$[-199, 192]$$$. $$$d = 192$$$.</p></li><li><p>После операции массив становится равным $$$[d-(-199), d-192] = [391, 0]$$$.</p></li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:39</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a84de9cc3374',t:'MTY5NjY2NjExOS40NjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"] | ||
1392C | 1392 | C | ru | C. Омкар и водная горка | <div class="problem-statement"><div class="header"><div class="title">C. Омкар и водная горка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Омкар строит водную горку в своем аквапарке, и ему нужна ваша помощь, чтобы сделать это как можно эффективнее.</p><p>В настоящее время у Омкара есть $$$n$$$ опор, выстроенных в линию, $$$i$$$-я из которых имеет высоту $$$a_i$$$. Омкар хочет построить свою водную горку справа налево, поэтому его опоры должны быть неспадающими по высоте, чтобы выдержать водную горку. За $$$1$$$ операцию Омкар может сделать следующее: взять любой <span class="tex-font-style-bf">последовательный подотрезок</span> опор, <span class="tex-font-style-bf">неспадающий по высотам</span>, и добавить $$$1$$$ к высоте каждой из них. </p><p>Помогите Омкару найти минимальное количество операций, которые ему нужно сделать, чтобы его опоры смогли выдержать его водную горку!</p><p>Последовательность $$$b$$$ является подотрезком $$$c$$$, если $$$b$$$ может быть получена из $$$c$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p><p>Массив $$$b_1, b_2, \dots, b_n$$$ называется неспадающим, если $$$b_i\le b_{i+1}$$$ для каждого $$$i$$$ от $$$1$$$ до $$$n-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \leq t \leq 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — количество опор Омкара.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \leq a_{i} \leq 10^9)$$$ — высоты опор.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превысит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество операций, которое необходимо выполнить Омкару, чтобы его опоры могли выдерживать его водную горку.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
4
5 3 2 5
5
1 2 3 5 3
3
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
2
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Подмассив, с которым Омкар выполняет операцию, выделен жирным шрифтом.</p><p>В первом наборе входных данных:</p><ul><li><p>Первая операция:</p><p>$$$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$$$</p></li><li><p>Вторая операция:</p><p>$$$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$$$</p></li><li><p>Третья операция:</p><p>$$$[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$$$</p></li></ul><p>В третьем наборе входных данных массив уже является неспадающим, поэтому Омкар выполняет $$$0$$$ операций.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="f66f730b934e25faefb7b11309ffc087"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='f66f730b934e25faefb7b11309ffc087'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='f66f730b934e25faefb7b11309ffc087'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='f66f730b934e25faefb7b11309ffc087'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f66f730b934e25faefb7b11309ffc087'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700619"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f66f730b934e25faefb7b11309ffc087'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700619"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_7a1da287354ed21161519202f9693de54b02c573">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Омкар и водная горка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Омкар строит водную горку в своем аквапарке, и ему нужна ваша помощь, чтобы сделать это как можно эффективнее.</p><p>В настоящее время у Омкара есть $$$n$$$ опор, выстроенных в линию, $$$i$$$-я из которых имеет высоту $$$a_i$$$. Омкар хочет построить свою водную горку справа налево, поэтому его опоры должны быть неспадающими по высоте, чтобы выдержать водную горку. За $$$1$$$ операцию Омкар может сделать следующее: взять любой <span class="tex-font-style-bf">последовательный подотрезок</span> опор, <span class="tex-font-style-bf">неспадающий по высотам</span>, и добавить $$$1$$$ к высоте каждой из них. </p><p>Помогите Омкару найти минимальное количество операций, которые ему нужно сделать, чтобы его опоры смогли выдержать его водную горку!</p><p>Последовательность $$$b$$$ является подотрезком $$$c$$$, если $$$b$$$ может быть получена из $$$c$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p><p>Массив $$$b_1, b_2, \dots, b_n$$$ называется неспадающим, если $$$b_i\le b_{i+1}$$$ для каждого $$$i$$$ от $$$1$$$ до $$$n-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \leq t \leq 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — количество опор Омкара.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_{1},a_{2},...,a_{n}$$$ $$$(0 \leq a_{i} \leq 10^9)$$$ — высоты опор.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превысит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество операций, которое необходимо выполнить Омкару, чтобы его опоры могли выдерживать его водную горку.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
4
5 3 2 5
5
1 2 3 5 3
3
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
2
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Подмассив, с которым Омкар выполняет операцию, выделен жирным шрифтом.</p><p>В первом наборе входных данных:</p><ul><li><p>Первая операция:</p><p>$$$[5, 3, \textbf{2}, 5] \to [5, 3, \textbf{3}, 5]$$$</p></li><li><p>Вторая операция:</p><p>$$$[5, \textbf{3}, \textbf{3}, 5] \to [5, \textbf{4}, \textbf{4}, 5]$$$</p></li><li><p>Третья операция:</p><p>$$$[5, \textbf{4}, \textbf{4}, 5] \to [5, \textbf{5}, \textbf{5}, 5]$$$</p></li></ul><p>В третьем наборе входных данных массив уже является неспадающим, поэтому Омкар выполняет $$$0$$$ операций.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:40</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8566e899d9e',t:'MTY5NjY2NjEyMC44MjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1200"] | ||
1392D | 1392 | D | ru | D. Омкар и Война кроватей | <div class="problem-statement"><div class="header"><div class="title">D. Омкар и Война кроватей</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Омкар играет в свою любимую видеоигру Война кроватей! В Войне кроватей $$$n$$$ игроков располагаются по кругу, так что для всех $$$j$$$ таких, что $$$2 \leq j \leq n$$$, игрок $$$j - 1$$$ находится слева от игрока $$$j$$$, а игрок $$$j$$$ — справа от игрока $$$j - 1$$$. Кроме того, слева от игрока $$$1$$$ находится игрок $$$n$$$, а справа от игрока $$$n$$$ — игрок $$$1$$$.</p><p>В настоящее время каждый игрок атакует либо левого, либо правого игрока. Это означает, что каждого игрока в настоящее время атакует либо $$$0$$$, $$$1$$$ либо $$$2$$$ других игроков. Ключевым элементом стратегии Войны кроватей является то, что если на игрока нападает ровно $$$1$$$ другой игрок, то в ответ он, логически, должен атаковать этого игрока. Если же на игрока нападают либо $$$0$$$ либо $$$2$$$ других игроков, то стратегия Войны кроватей гласит, что игрок может атаковать любого из соседних игроков.</p><p>К сожалению, может случиться так, что некоторые игроки в этой игре не следуют правильной стратегии Войны кроватей нужным образом. Омкар знает, на кого в настоящее время нападает каждый игрок, и он может поговорить с любым количеством из $$$n$$$ игроков в игре, чтобы заставить их вместо этого атаковать другого игрока — то есть, если игрок в настоящее время атаковал игрока слева от него, Омкар может убедить его вместо этого атаковать игрока справа от него; если он в настоящее время атаковал игрока справа от него, Омкар может убедить его вместо этого атаковать игрока слева от него. </p><p>Омкар хотел бы, чтобы все игроки действовали логично. Найдите минимальное количество игроков, с которыми Омкар должен поговорить, чтобы после того, как все игроки, с которыми он поговорил (если таковые имеются), изменили игрока, которого они атакуют, все игроки действовали логически в соответствии со стратегией Войны кроватей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Ниже приведены описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — количество игроков (а значит и кроватей) в этой игре Bed Wars.</p><p>Вторая строка каждого набора входных данных содержит строку $$$s$$$ длиной $$$n$$$. $$$j$$$-й символ $$$s$$$ равен <span class="tex-font-style-tt">L</span>, если $$$j$$$-й игрок атакует игрока слева от него, и <span class="tex-font-style-tt">R</span>, если $$$j$$$-й игрок атакует игрока справа от него.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число: минимальное количество игроков, с которыми Омкар должен поговорить, чтобы сделать так, чтобы все игроки действовали логично в соответствии со стратегией Войны кроватей.</p><p>Можно доказать, что Омкар всегда может достичь этого при заданных ограничениях.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
4
RLRL
6
LRRRRL
8
RLLRRRLL
12
LLLLRRLRRRLL
5
RRRRR
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
1
3
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных игроки $$$1$$$ и $$$2$$$ атакуют друг друга, а игроки $$$3$$$ и $$$4$$$ — друг друга. Каждый игрок атакует ровно $$$1$$$ другого игрока, и каждый игрок атакует игрока, который атакует их, так что все игроки уже действуют логично в соответствии со стратегией Войны кроватей, и Омкару не нужно разговаривать ни с одним из них, следовательно, ответ $$$0$$$.</p><p>Во втором наборе входных данных, не каждый игрок действует логически: например, игрока $$$3$$$ атакует только игрок $$$2$$$, но он не атакует его в ответ. Омкару достаточно поговорить с игроком $$$3$$$ для изменения схемы атаки на <span class="tex-font-style-tt">LR<span class="tex-font-style-bf">L</span>RRL</span>, в которой все игроки действуют логично в соответствии со стратегией Войны кроватей, делая ответ $$$1$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="99739812a141958b74f24195a65e20cc"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='99739812a141958b74f24195a65e20cc'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='99739812a141958b74f24195a65e20cc'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='99739812a141958b74f24195a65e20cc'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1700
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='99739812a141958b74f24195a65e20cc'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700620"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='99739812a141958b74f24195a65e20cc'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700620"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_93f28f97dff14d025ae217f46517c6eb5a36c375">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Омкар и Война кроватей</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Омкар играет в свою любимую видеоигру Война кроватей! В Войне кроватей $$$n$$$ игроков располагаются по кругу, так что для всех $$$j$$$ таких, что $$$2 \leq j \leq n$$$, игрок $$$j - 1$$$ находится слева от игрока $$$j$$$, а игрок $$$j$$$ — справа от игрока $$$j - 1$$$. Кроме того, слева от игрока $$$1$$$ находится игрок $$$n$$$, а справа от игрока $$$n$$$ — игрок $$$1$$$.</p><p>В настоящее время каждый игрок атакует либо левого, либо правого игрока. Это означает, что каждого игрока в настоящее время атакует либо $$$0$$$, $$$1$$$ либо $$$2$$$ других игроков. Ключевым элементом стратегии Войны кроватей является то, что если на игрока нападает ровно $$$1$$$ другой игрок, то в ответ он, логически, должен атаковать этого игрока. Если же на игрока нападают либо $$$0$$$ либо $$$2$$$ других игроков, то стратегия Войны кроватей гласит, что игрок может атаковать любого из соседних игроков.</p><p>К сожалению, может случиться так, что некоторые игроки в этой игре не следуют правильной стратегии Войны кроватей нужным образом. Омкар знает, на кого в настоящее время нападает каждый игрок, и он может поговорить с любым количеством из $$$n$$$ игроков в игре, чтобы заставить их вместо этого атаковать другого игрока — то есть, если игрок в настоящее время атаковал игрока слева от него, Омкар может убедить его вместо этого атаковать игрока справа от него; если он в настоящее время атаковал игрока справа от него, Омкар может убедить его вместо этого атаковать игрока слева от него. </p><p>Омкар хотел бы, чтобы все игроки действовали логично. Найдите минимальное количество игроков, с которыми Омкар должен поговорить, чтобы после того, как все игроки, с которыми он поговорил (если таковые имеются), изменили игрока, которого они атакуют, все игроки действовали логически в соответствии со стратегией Войны кроватей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Ниже приведены описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$) — количество игроков (а значит и кроватей) в этой игре Bed Wars.</p><p>Вторая строка каждого набора входных данных содержит строку $$$s$$$ длиной $$$n$$$. $$$j$$$-й символ $$$s$$$ равен <span class="tex-font-style-tt">L</span>, если $$$j$$$-й игрок атакует игрока слева от него, и <span class="tex-font-style-tt">R</span>, если $$$j$$$-й игрок атакует игрока справа от него.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число: минимальное количество игроков, с которыми Омкар должен поговорить, чтобы сделать так, чтобы все игроки действовали логично в соответствии со стратегией Войны кроватей.</p><p>Можно доказать, что Омкар всегда может достичь этого при заданных ограничениях.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
4
RLRL
6
LRRRRL
8
RLLRRRLL
12
LLLLRRLRRRLL
5
RRRRR
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
1
3
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных игроки $$$1$$$ и $$$2$$$ атакуют друг друга, а игроки $$$3$$$ и $$$4$$$ — друг друга. Каждый игрок атакует ровно $$$1$$$ другого игрока, и каждый игрок атакует игрока, который атакует их, так что все игроки уже действуют логично в соответствии со стратегией Войны кроватей, и Омкару не нужно разговаривать ни с одним из них, следовательно, ответ $$$0$$$.</p><p>Во втором наборе входных данных, не каждый игрок действует логически: например, игрока $$$3$$$ атакует только игрок $$$2$$$, но он не атакует его в ответ. Омкару достаточно поговорить с игроком $$$3$$$ для изменения схемы атаки на <span class="tex-font-style-tt">LR<span class="tex-font-style-bf">L</span>RRL</span>, в которой все игроки действуют логично в соответствии со стратегией Войны кроватей, делая ответ $$$1$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:42</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a85ec8121687',t:'MTY5NjY2NjEyMi45NjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*1700"] | ||
1392E | 1392 | E | ru | E. Омкар и утка | <div class="problem-statement"><div class="header"><div class="title">E. Омкар и утка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача</span></p><p>Омкар только что наткнулся на утку! Утка ходит по сетке с $$$n$$$ строками и $$$n$$$ столбцами ($$$2 \leq n \leq 25$$$), так что сетка содержит в общей сложности $$$n^2$$$ ячеек. Обозначим как $$$(x, y)$$$ ячейку в $$$x$$$-й строке сверху и $$$y$$$-м столбце слева. Прямо сейчас утка находится в ячейке $$$(1, 1)$$$ (ячейка в левом верхнем углу) и хочет дойти до ячейки $$$(n, n)$$$ (ячейка в правом нижнем углу), перемещаясь каждую секунду либо вниз на $$$1$$$ ячейку, либо вправо на $$$1$$$ ячейку.</p><p>Так как Омкар считает, что утки это весело, он хочет поиграть с вами в игру, основанную на движении утки. Сначала для каждой ячейки $$$(x, y)$$$ в сетке вы скажете Омкару целое неотрицательное $$$a_{x,y}$$$, не превышающее $$$10^{16}$$$, а затем Омкар положит $$$a_{x,y}$$$ неинтересных задач в ячейку $$$(x, y)$$$. После этого утка начнет свое путешествие с $$$(1, 1)$$$ до $$$(n, n)$$$. Для каждой ячейки $$$(x, y)$$$, которую утка посещает во время своего путешествия (включая ячейки $$$(1, 1)$$$ и $$$(n, n)$$$), утка съест $$$a_{x,y}$$$ неинтересных задач в этой ячейке. После того как утка завершит свое путешествие, Омкар измерит ее массу, чтобы определить общее количество $$$k$$$ неинтересных задач, которые утка съела во время своего путешествия, а затем скажет вам $$$k$$$.</p><p>Ваша задача, зная $$$k$$$, состоит в том, чтобы точно воспроизвести утиный путь, т.е. точно сказать Омкару, какие клетки утка посетила во время своего путешествия. Чтобы быть уверенным в вашем мастерстве в этой игре, Омкар заставит утку выполнить $$$q$$$ различных путешествий ($$$1 \leq q \leq 10^3$$$). Обратите внимание, что все путешествия независимы: в начале каждого путешествия ячейка $$$(x, y)$$$ все так же будет содержать $$$a_{x,y}$$$ неинтересных задач.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начнется со строки, содержащей одно целое $$$n$$$ ($$$2 \leq n \leq 25$$$) — количество строк и столбцов в сетке. Считайте его.</p><p>Затем ваша программа должна вывести $$$n$$$ строк. $$$x$$$-я строка должна содержать $$$n$$$ целых чисел $$$a_{x,1}, a_{x,2}, \dotsc, a_{x,n}$$$, удовлетворяющих $$$0 \leq a_{x,y} \leq 10^{16}$$$, где $$$a_{x,y}$$$ — это количество неинтересных задач, которые Омкар должен поместить в ячейку $$$(x, y)$$$.</p><p>После этого вы получите одно целое $$$q$$$, количество путешествий, которые совершит утка. Затем последуют $$$q$$$ запросов; каждый запрос будет состоять из одной строки, содержащей целое число $$$k$$$ — количество неинтересных задач, которые утка съела в этой поездке. После каждого запроса, когда вы определили, что утка посетила ячейки $$$(x_1, y_1), (x_2, y_2), \dotsc, (x_{2n - 1}, y_{2n - 1})$$$ в таком порядке (всегда должно выполняться $$$(x_1, y_1) = (1, 1)$$$ и $$$(x_{2n - 1}, y_{2n - 1}) = (n, n)$$$), нужно вывести $$$2n - 1$$$ строк, в $$$j$$$-й из которых должно быть два целых числа $$$x_j, y_j$$$.</p><p><span class="tex-font-style-bf">Обратите внимание, что если сумма на вашем пути равна $$$k$$$, но ваш путь отличается от загаданного, то ваше решение все еще неверное!</span></p><p>После вывода очередной строки не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p><span class="tex-font-style-bf">Формат взломов</span></p><p>Для взлома сначала выведите строку, содержащую $$$n$$$, а затем другую строку, содержащую $$$q$$$. Должно выполняться $$$2 \leq n \leq 25$$$ и $$$1 \leq q \leq 1000$$$. Затем выведите $$$q$$$ путешествий, сделанных уткой в том же формате, как описано выше: для каждого путешествия, если утка посещала ячейки $$$(x_1, y_1), (x_2, y_2), \dotsc, (x_{2n - 1}, y_{2n - 1})$$$ в таком порядке, нужно вывести $$$2n - 1$$$ строк, в $$$j$$$-й строке должны быть два целых числа $$$x_j, y_j$$$. Должно выполняться $$$(x_1, y_1) = (1, 1)$$$ и $$$(x_{2n - 1}, y_{2n - 1}) = (n, n)$$$. Кроме того, для каждого $$$j$$$ такого, что $$$2 \leq j \leq 2n - 1$$$, должно быть верно, что $$$1 \leq x_j, y_j \leq n$$$ и либо $$$(x_j, y_j) = (x_{j - 1} + 1, y_{j - 1})$$$ либо $$$(x_j, y_j) = (x_{j - 1}, y_{j - 1} + 1)$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
3
23
26
27
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 2 3 6
4 6 2 10
9 0 7 3
2 8 8 2
1 1
1 2
1 3
2 3
2 4
3 4
4 4
1 1
2 1
3 1
3 2
3 3
3 4
4 4
1 1
1 2
1 3
1 4
2 4
3 4
4 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже проиллюстрированы три путешествия утки.</p><p>$$$1 + 2 + 3 + 2 + 10 + 3 + 2 = 23$$$ </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0787e498b86a4c1b16de231754044d2a45609704.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>$$$1 + 4 + 9 + 0 + 7 + 3 + 2 = 26$$$ </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c6533144095359f021b373978ae4ca373c9acec8.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>$$$1 + 2 + 3 + 6 + 10 + 3 + 2 = 27$$$ </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0a3f1bc73354d60850356d8d5cb52cc8bb98d8d9.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="1b20d50d9e0b7315182dca877a24998b"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='1b20d50d9e0b7315182dca877a24998b'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='1b20d50d9e0b7315182dca877a24998b'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='1b20d50d9e0b7315182dca877a24998b'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Битовые маски">
битмаски
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2100
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1b20d50d9e0b7315182dca877a24998b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700621"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1b20d50d9e0b7315182dca877a24998b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700621"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_ac8264fa284b9400dec67d013b458491f71f16ae">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Омкар и утка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача</span></p><p>Омкар только что наткнулся на утку! Утка ходит по сетке с $$$n$$$ строками и $$$n$$$ столбцами ($$$2 \leq n \leq 25$$$), так что сетка содержит в общей сложности $$$n^2$$$ ячеек. Обозначим как $$$(x, y)$$$ ячейку в $$$x$$$-й строке сверху и $$$y$$$-м столбце слева. Прямо сейчас утка находится в ячейке $$$(1, 1)$$$ (ячейка в левом верхнем углу) и хочет дойти до ячейки $$$(n, n)$$$ (ячейка в правом нижнем углу), перемещаясь каждую секунду либо вниз на $$$1$$$ ячейку, либо вправо на $$$1$$$ ячейку.</p><p>Так как Омкар считает, что утки это весело, он хочет поиграть с вами в игру, основанную на движении утки. Сначала для каждой ячейки $$$(x, y)$$$ в сетке вы скажете Омкару целое неотрицательное $$$a_{x,y}$$$, не превышающее $$$10^{16}$$$, а затем Омкар положит $$$a_{x,y}$$$ неинтересных задач в ячейку $$$(x, y)$$$. После этого утка начнет свое путешествие с $$$(1, 1)$$$ до $$$(n, n)$$$. Для каждой ячейки $$$(x, y)$$$, которую утка посещает во время своего путешествия (включая ячейки $$$(1, 1)$$$ и $$$(n, n)$$$), утка съест $$$a_{x,y}$$$ неинтересных задач в этой ячейке. После того как утка завершит свое путешествие, Омкар измерит ее массу, чтобы определить общее количество $$$k$$$ неинтересных задач, которые утка съела во время своего путешествия, а затем скажет вам $$$k$$$.</p><p>Ваша задача, зная $$$k$$$, состоит в том, чтобы точно воспроизвести утиный путь, т.е. точно сказать Омкару, какие клетки утка посетила во время своего путешествия. Чтобы быть уверенным в вашем мастерстве в этой игре, Омкар заставит утку выполнить $$$q$$$ различных путешествий ($$$1 \leq q \leq 10^3$$$). Обратите внимание, что все путешествия независимы: в начале каждого путешествия ячейка $$$(x, y)$$$ все так же будет содержать $$$a_{x,y}$$$ неинтересных задач.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начнется со строки, содержащей одно целое $$$n$$$ ($$$2 \leq n \leq 25$$$) — количество строк и столбцов в сетке. Считайте его.</p><p>Затем ваша программа должна вывести $$$n$$$ строк. $$$x$$$-я строка должна содержать $$$n$$$ целых чисел $$$a_{x,1}, a_{x,2}, \dotsc, a_{x,n}$$$, удовлетворяющих $$$0 \leq a_{x,y} \leq 10^{16}$$$, где $$$a_{x,y}$$$ — это количество неинтересных задач, которые Омкар должен поместить в ячейку $$$(x, y)$$$.</p><p>После этого вы получите одно целое $$$q$$$, количество путешествий, которые совершит утка. Затем последуют $$$q$$$ запросов; каждый запрос будет состоять из одной строки, содержащей целое число $$$k$$$ — количество неинтересных задач, которые утка съела в этой поездке. После каждого запроса, когда вы определили, что утка посетила ячейки $$$(x_1, y_1), (x_2, y_2), \dotsc, (x_{2n - 1}, y_{2n - 1})$$$ в таком порядке (всегда должно выполняться $$$(x_1, y_1) = (1, 1)$$$ и $$$(x_{2n - 1}, y_{2n - 1}) = (n, n)$$$), нужно вывести $$$2n - 1$$$ строк, в $$$j$$$-й из которых должно быть два целых числа $$$x_j, y_j$$$.</p><p><span class="tex-font-style-bf">Обратите внимание, что если сумма на вашем пути равна $$$k$$$, но ваш путь отличается от загаданного, то ваше решение все еще неверное!</span></p><p>После вывода очередной строки не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p><span class="tex-font-style-bf">Формат взломов</span></p><p>Для взлома сначала выведите строку, содержащую $$$n$$$, а затем другую строку, содержащую $$$q$$$. Должно выполняться $$$2 \leq n \leq 25$$$ и $$$1 \leq q \leq 1000$$$. Затем выведите $$$q$$$ путешествий, сделанных уткой в том же формате, как описано выше: для каждого путешествия, если утка посещала ячейки $$$(x_1, y_1), (x_2, y_2), \dotsc, (x_{2n - 1}, y_{2n - 1})$$$ в таком порядке, нужно вывести $$$2n - 1$$$ строк, в $$$j$$$-й строке должны быть два целых числа $$$x_j, y_j$$$. Должно выполняться $$$(x_1, y_1) = (1, 1)$$$ и $$$(x_{2n - 1}, y_{2n - 1}) = (n, n)$$$. Кроме того, для каждого $$$j$$$ такого, что $$$2 \leq j \leq 2n - 1$$$, должно быть верно, что $$$1 \leq x_j, y_j \leq n$$$ и либо $$$(x_j, y_j) = (x_{j - 1} + 1, y_{j - 1})$$$ либо $$$(x_j, y_j) = (x_{j - 1}, y_{j - 1} + 1)$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
3
23
26
27
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 2 3 6
4 6 2 10
9 0 7 3
2 8 8 2
1 1
1 2
1 3
2 3
2 4
3 4
4 4
1 1
2 1
3 1
3 2
3 3
3 4
4 4
1 1
1 2
1 3
1 4
2 4
3 4
4 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже проиллюстрированы три путешествия утки.</p><p>$$$1 + 2 + 3 + 2 + 10 + 3 + 2 = 23$$$ </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0787e498b86a4c1b16de231754044d2a45609704.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>$$$1 + 4 + 9 + 0 + 7 + 3 + 2 = 26$$$ </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c6533144095359f021b373978ae4ca373c9acec8.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>$$$1 + 2 + 3 + 6 + 10 + 3 + 2 = 27$$$ </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0a3f1bc73354d60850356d8d5cb52cc8bb98d8d9.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:44</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a86c3b380c4e',t:'MTY5NjY2NjEyNC40MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2100"] | ||
1392F | 1392 | F | ru | F. Омкар и оползень | <div class="problem-statement"><div class="header"><div class="title">F. Омкар и оползень</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Омкар стоит у подножия горы Селеста. Вершина находится в $$$n$$$ метрах от него, и он может видеть всю гору до вершины, поэтому для каждого $$$1 \leq j \leq n$$$ он знает, что высота горы в точке в $$$j$$$ метрах от него равна $$$h_j$$$. Известно, что для всех $$$j$$$ удовлетворяющих $$$1 \leq j \leq n - 1$$$, $$$h_j < h_{j + 1}$$$ (то есть высоты строго возрастают).</p><p>Внезапно происходит оползень! Пока происходит оползень, происходит следующее: каждую минуту, если $$$h_j + 2 \leq h_{j + 1}$$$, то один квадратный метр грязи будет скользить с позиции $$$j + 1$$$ в позицию $$$j$$$, так что $$$h_{j + 1}$$$ уменьшается на $$$1$$$, а $$$h_j$$$ увеличивается на $$$1$$$. Эти изменения происходят одновременно, так, например, если $$$h_j + 2 \leq h_{j + 1}$$$ и $$$h_{j + 1} + 2 \leq h_{j + 2}$$$ для какого-то $$$j$$$, то $$$h_j$$$ будет увеличено на $$$1$$$, $$$h_{j + 2}$$$ будет уменьшено на $$$1$$$, а $$$h_{j + 1}$$$ будет увеличено и уменьшено на $$$1$$$, что означает, что на самом деле $$$h_{j + 1}$$$ в течение этой минуты не изменится.</p><p>Оползень заканчивается, когда не будет такого $$$j$$$, что $$$h_j + 2 \leq h_{j + 1}$$$. Помогите Омкару выяснить, каковы будут значения $$$h_1, \dots, h_n$$$ после окончания оползня. Можно доказать, что при заданных ограничениях оползень всегда заканчивается через некоторое число минут.</p><p>Обратите внимание, что из-за большого количества входных данных, рекомендуется, чтобы ваш код использовал быстрый ввод.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^6$$$). </p><p>Вторая строка содержит $$$n$$$ целых чисел $$$h_1, h_2, \dots, h_n$$$ удовлетворяющих $$$0 \leq h_1 < h_2 < \dots < h_n \leq 10^{12}$$$ — высоты.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, где $$$j$$$-е число — это значение $$$h_j$$$ после остановки оползня.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
2 6 7 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5 5 6 7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первоначально гора имеет высоты $$$2, 6, 7, 8$$$.</p><p>В первую минуту у нас есть $$$2 + 2 \leq 6$$$, таким образом $$$2$$$ увеличивается до $$$3$$$, а $$$6$$$ уменьшается до $$$5$$$, оставляя $$$3, 5, 7, 8$$$.</p><p>Во вторую минуту у нас есть $$$3 + 2 \leq 5$$$ и $$$5 + 2 \leq 7$$$, таким образом $$$3$$$ увеличивается до $$$4$$$, $$$5$$$ остается без изменений, а $$$7$$$ уменьшается до $$$6$$$, оставляя $$$4, 5, 6, 8$$$.</p><p>На третьей минуте у нас есть $$$6 + 2 \leq 8$$$, так что $$$6$$$ увеличивается до $$$7$$$, а $$$8$$$ уменьшается до $$$7$$$, оставляя $$$4, 5, 7, 7$$$.</p><p>На четвертой минуте у нас есть $$$5 + 2 \leq 7$$$, таким образом $$$5$$$ увеличивается до $$$6$$$, а $$$7$$$ уменьшается до $$$6$$$, оставляя $$$4, 6, 6, 7$$$.</p><p>На пятой минуте у нас есть $$$4 + 2 \leq 6$$$, поэтому $$$4$$$ увеличивается до $$$5$$$, а $$$6$$$ уменьшается до $$$5$$$, оставляя $$$5, 5, 6, 7$$$.</p><p>На шестой минуте ничего больше не может измениться, поэтому оползень останавливается, и наш ответ — $$$5, 5, 6, 7$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="8d622c094ff60774ee6e12580c4b7f5d"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - F - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='8d622c094ff60774ee6e12580c4b7f5d'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FF%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='8d622c094ff60774ee6e12580c4b7f5d'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='8d622c094ff60774ee6e12580c4b7f5d'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8d622c094ff60774ee6e12580c4b7f5d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700622"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8d622c094ff60774ee6e12580c4b7f5d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700622"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="F" data-uuid="ps_fdc5d746156e77fe32062c19985ee263ef395e90">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Омкар и оползень</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Омкар стоит у подножия горы Селеста. Вершина находится в $$$n$$$ метрах от него, и он может видеть всю гору до вершины, поэтому для каждого $$$1 \leq j \leq n$$$ он знает, что высота горы в точке в $$$j$$$ метрах от него равна $$$h_j$$$. Известно, что для всех $$$j$$$ удовлетворяющих $$$1 \leq j \leq n - 1$$$, $$$h_j < h_{j + 1}$$$ (то есть высоты строго возрастают).</p><p>Внезапно происходит оползень! Пока происходит оползень, происходит следующее: каждую минуту, если $$$h_j + 2 \leq h_{j + 1}$$$, то один квадратный метр грязи будет скользить с позиции $$$j + 1$$$ в позицию $$$j$$$, так что $$$h_{j + 1}$$$ уменьшается на $$$1$$$, а $$$h_j$$$ увеличивается на $$$1$$$. Эти изменения происходят одновременно, так, например, если $$$h_j + 2 \leq h_{j + 1}$$$ и $$$h_{j + 1} + 2 \leq h_{j + 2}$$$ для какого-то $$$j$$$, то $$$h_j$$$ будет увеличено на $$$1$$$, $$$h_{j + 2}$$$ будет уменьшено на $$$1$$$, а $$$h_{j + 1}$$$ будет увеличено и уменьшено на $$$1$$$, что означает, что на самом деле $$$h_{j + 1}$$$ в течение этой минуты не изменится.</p><p>Оползень заканчивается, когда не будет такого $$$j$$$, что $$$h_j + 2 \leq h_{j + 1}$$$. Помогите Омкару выяснить, каковы будут значения $$$h_1, \dots, h_n$$$ после окончания оползня. Можно доказать, что при заданных ограничениях оползень всегда заканчивается через некоторое число минут.</p><p>Обратите внимание, что из-за большого количества входных данных, рекомендуется, чтобы ваш код использовал быстрый ввод.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^6$$$). </p><p>Вторая строка содержит $$$n$$$ целых чисел $$$h_1, h_2, \dots, h_n$$$ удовлетворяющих $$$0 \leq h_1 < h_2 < \dots < h_n \leq 10^{12}$$$ — высоты.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел, где $$$j$$$-е число — это значение $$$h_j$$$ после остановки оползня.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
2 6 7 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5 5 6 7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первоначально гора имеет высоты $$$2, 6, 7, 8$$$.</p><p>В первую минуту у нас есть $$$2 + 2 \leq 6$$$, таким образом $$$2$$$ увеличивается до $$$3$$$, а $$$6$$$ уменьшается до $$$5$$$, оставляя $$$3, 5, 7, 8$$$.</p><p>Во вторую минуту у нас есть $$$3 + 2 \leq 5$$$ и $$$5 + 2 \leq 7$$$, таким образом $$$3$$$ увеличивается до $$$4$$$, $$$5$$$ остается без изменений, а $$$7$$$ уменьшается до $$$6$$$, оставляя $$$4, 5, 6, 8$$$.</p><p>На третьей минуте у нас есть $$$6 + 2 \leq 8$$$, так что $$$6$$$ увеличивается до $$$7$$$, а $$$8$$$ уменьшается до $$$7$$$, оставляя $$$4, 5, 7, 7$$$.</p><p>На четвертой минуте у нас есть $$$5 + 2 \leq 7$$$, таким образом $$$5$$$ увеличивается до $$$6$$$, а $$$7$$$ уменьшается до $$$6$$$, оставляя $$$4, 6, 6, 7$$$.</p><p>На пятой минуте у нас есть $$$4 + 2 \leq 6$$$, поэтому $$$4$$$ увеличивается до $$$5$$$, а $$$6$$$ уменьшается до $$$5$$$, оставляя $$$5, 5, 6, 7$$$.</p><p>На шестой минуте ничего больше не может измениться, поэтому оползень останавливается, и наш ответ — $$$5, 5, 6, 7$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:45</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8756b9c75a7',t:'MTY5NjY2NjEyNS43NTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"] | ||
1392G | 1392 | G | ru | G. Омкар и пироги | <div class="problem-statement"><div class="header"><div class="title">G. Омкар и пироги</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Омкара есть поднос для пирогов с $$$k$$$ местами ($$$2 \leq k \leq 20$$$). Каждое место на подносе содержит либо шоколадный пирог, либо тыквенный пирог. Омкару не нравится, как пироги расположены в настоящее время, и у него есть другое идеальное расположение, которое он предпочел бы этому.</p><p>Чтобы помочь Омкару, $$$n$$$ эльфов построились в очередь на замену пирогов на подносе. $$$j$$$-й слева эльф способен поменять пироги на позициях $$$a_j$$$ и $$$b_j$$$ местами.</p><p>Чтобы максимально приблизиться к своему идеальному расположению, Omkar может выбрать последовательный подотрезок эльфов и затем пропустить свой поднос через этот подотрезок, начиная слева. Однако, поскольку эльфы приложили столько усилий, чтобы собраться в строку, они просят, чтобы выбранный Омкаром подотрезок содержал как минимум $$$m$$$ ($$$1 \leq m \leq n$$$) эльфов.</p><p>Формально, Omkar может выбрать два целых числа $$$l$$$ и $$$r$$$, удовлетворяющих $$$1 \leq l \leq r \leq n$$$ и $$$r - l + 1 \geq m$$$, после чего сначала будут поменяны пироги в позициях $$$a_l$$$ и $$$b_l$$$, затем пироги в позициях $$$a_{l + 1}$$$ и $$$b_{l + 1}$$$ и т.д. пока, наконец, не будут поменяны местами пироги $$$a_r$$$ и $$$b_r$$$.</p><p>Помогите Омкару выбрать подотрезок эльфов таким образом, чтобы количество позиций в итоговой расстановке Омкара, содержащих тот же тип пирога, что и в его идеальной расстановке, было максимально возможным. <span class="tex-font-style-bf">Обратите внимание, что поскольку Омкар обладает большим воображением, может случиться так, что количество пирогов каждого типа в его первоначальном расположении и в его идеальном расположении не совпадают</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \leq m \leq n \leq 10^6$$$ и $$$2 \leq k \leq 20$$$) — число эльфов, минимальную длину подотрезка и число мест в подносе Омкара соответственно.</p><p>Вторая и третья строки содержат по строке длиной $$$k$$$, состоящей из $$$0$$$ и $$$1$$$, которые представляют собой начальное расположение пирогов и идеальное расположение пирогов; $$$j$$$-й символ в каждой строке равен $$$0$$$, если $$$j$$$-е место в расположении содержит шоколадный пирог, и равен $$$1$$$, если $$$j$$$-е место в расположении содержит тыквенный пирог. Не гарантируется, что две строки имеют одинаковое количество $$$0$$$ или одинаковое количество $$$1$$$.</p><p>Ниже следуют $$$n$$$ строк. $$$j$$$-я из этих строк содержит два целых числа $$$a_j$$$ и $$$b_j$$$, ($$$1 \leq a_j, b_j \leq k$$$, $$$a_j \neq b_j$$$), которые указывают на то, что $$$j$$$-й эльф слева может поменять местами пироги в подносе на позициях $$$a_j$$$ и $$$b_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выводите две строки. </p><p>Первая строка должна содержать одно целое $$$s$$$ ($$$0 \leq s \leq k$$$), равное количеству позиций, которые содержат один и тот же тип пирога в окончательном расположении Омкара и в идеальном расположении Омкара; $$$s$$$ должно быть максимально возможным. </p><p>Вторая строка должна содержать два целых числа $$$l$$$ и $$$r$$$, удовлетворяющих $$$1 \leq l \leq r \leq n$$$ и $$$r - l + 1 \geq m$$$, обозначающих, что Омкар должен пропустить свой поднос через подотрезок $$$l, l + 1, \dots, r$$$, чтобы добиться конечного расположения в котором есть $$$s$$$ позиций, в которых тот же тип пирога, что и в идеальном расположении.</p><p>Если ответов несколько, то можно вывести любой из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2 5
11000
00011
1 3
3 5
4 2
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
1 3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 3 5
11000
00011
1 3
1 5
2 4
1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
1 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, изменения будут проходить вот так: </p><ul> <li> Поменяйте $$$1$$$ и $$$3$$$: <span class="tex-font-style-tt">11000</span> становится <span class="tex-font-style-tt">01100</span> </li><li> Поменяйте $$$3$$$ и $$$5$$$: <span class="tex-font-style-tt">01100</span> становится <span class="tex-font-style-tt">01001</span> </li><li> Поменяйте $$$4$$$ и $$$2$$$: <span class="tex-font-style-tt">01001</span> становится <span class="tex-font-style-tt">00011</span> </li></ul> Окончательная расстановка такая же, как и у идеального пирога <span class="tex-font-style-tt">00011</span>, поэтому есть $$$5$$$ позиций с тем же типом пирога, что и в оптимальной.<p>Во втором примере, изменения будут идти вот так: </p><ul> <li> Поменяйте $$$1$$$ и $$$3$$$: <span class="tex-font-style-tt">11000</span> становится <span class="tex-font-style-tt">01100</span> </li><li> Поменяйте $$$1$$$ и $$$5$$$: <span class="tex-font-style-tt">01100</span> становится <span class="tex-font-style-tt">01100</span> </li><li> Поменяйте $$$4$$$ и $$$2$$$: <span class="tex-font-style-tt">01100</span> становится <span class="tex-font-style-tt">00110</span> </li><li> Поменяйте $$$1$$$ и $$$5$$$: <span class="tex-font-style-tt">00110</span> становится <span class="tex-font-style-tt">00110</span> </li></ul> Окончательная расстановка имеет $$$3$$$ позиции с тем же типом пирога, что и идеальная расстановка <span class="tex-font-style-tt">00011</span>, это позиции $$$1$$$, $$$2$$$ и $$$4$$$. В этом случае подотрезок эльфов $$$(l, r) = (2, 3)$$$ более оптимален, но этот подотрезок имеет только длину $$$2$$$ и поэтому не удовлетворяет ограничению, заключающемуся в том, что подотрезок должен иметь длину не менее $$$m = 3$$$.</div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="bb321d3999da23b89d3a63f12cb1f191"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - G - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - G - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='bb321d3999da23b89d3a63f12cb1f191'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FG%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='bb321d3999da23b89d3a63f12cb1f191'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='bb321d3999da23b89d3a63f12cb1f191'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Битовые маски">
битмаски
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах">
кратчайшие пути
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2900
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bb321d3999da23b89d3a63f12cb1f191'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700623"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bb321d3999da23b89d3a63f12cb1f191'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700623"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="G" data-uuid="ps_85f44ca59b45da4059b157620c8028c2d73a2e9d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Омкар и пироги</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Омкара есть поднос для пирогов с $$$k$$$ местами ($$$2 \leq k \leq 20$$$). Каждое место на подносе содержит либо шоколадный пирог, либо тыквенный пирог. Омкару не нравится, как пироги расположены в настоящее время, и у него есть другое идеальное расположение, которое он предпочел бы этому.</p><p>Чтобы помочь Омкару, $$$n$$$ эльфов построились в очередь на замену пирогов на подносе. $$$j$$$-й слева эльф способен поменять пироги на позициях $$$a_j$$$ и $$$b_j$$$ местами.</p><p>Чтобы максимально приблизиться к своему идеальному расположению, Omkar может выбрать последовательный подотрезок эльфов и затем пропустить свой поднос через этот подотрезок, начиная слева. Однако, поскольку эльфы приложили столько усилий, чтобы собраться в строку, они просят, чтобы выбранный Омкаром подотрезок содержал как минимум $$$m$$$ ($$$1 \leq m \leq n$$$) эльфов.</p><p>Формально, Omkar может выбрать два целых числа $$$l$$$ и $$$r$$$, удовлетворяющих $$$1 \leq l \leq r \leq n$$$ и $$$r - l + 1 \geq m$$$, после чего сначала будут поменяны пироги в позициях $$$a_l$$$ и $$$b_l$$$, затем пироги в позициях $$$a_{l + 1}$$$ и $$$b_{l + 1}$$$ и т.д. пока, наконец, не будут поменяны местами пироги $$$a_r$$$ и $$$b_r$$$.</p><p>Помогите Омкару выбрать подотрезок эльфов таким образом, чтобы количество позиций в итоговой расстановке Омкара, содержащих тот же тип пирога, что и в его идеальной расстановке, было максимально возможным. <span class="tex-font-style-bf">Обратите внимание, что поскольку Омкар обладает большим воображением, может случиться так, что количество пирогов каждого типа в его первоначальном расположении и в его идеальном расположении не совпадают</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$1 \leq m \leq n \leq 10^6$$$ и $$$2 \leq k \leq 20$$$) — число эльфов, минимальную длину подотрезка и число мест в подносе Омкара соответственно.</p><p>Вторая и третья строки содержат по строке длиной $$$k$$$, состоящей из $$$0$$$ и $$$1$$$, которые представляют собой начальное расположение пирогов и идеальное расположение пирогов; $$$j$$$-й символ в каждой строке равен $$$0$$$, если $$$j$$$-е место в расположении содержит шоколадный пирог, и равен $$$1$$$, если $$$j$$$-е место в расположении содержит тыквенный пирог. Не гарантируется, что две строки имеют одинаковое количество $$$0$$$ или одинаковое количество $$$1$$$.</p><p>Ниже следуют $$$n$$$ строк. $$$j$$$-я из этих строк содержит два целых числа $$$a_j$$$ и $$$b_j$$$, ($$$1 \leq a_j, b_j \leq k$$$, $$$a_j \neq b_j$$$), которые указывают на то, что $$$j$$$-й эльф слева может поменять местами пироги в подносе на позициях $$$a_j$$$ и $$$b_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выводите две строки. </p><p>Первая строка должна содержать одно целое $$$s$$$ ($$$0 \leq s \leq k$$$), равное количеству позиций, которые содержат один и тот же тип пирога в окончательном расположении Омкара и в идеальном расположении Омкара; $$$s$$$ должно быть максимально возможным. </p><p>Вторая строка должна содержать два целых числа $$$l$$$ и $$$r$$$, удовлетворяющих $$$1 \leq l \leq r \leq n$$$ и $$$r - l + 1 \geq m$$$, обозначающих, что Омкар должен пропустить свой поднос через подотрезок $$$l, l + 1, \dots, r$$$, чтобы добиться конечного расположения в котором есть $$$s$$$ позиций, в которых тот же тип пирога, что и в идеальном расположении.</p><p>Если ответов несколько, то можно вывести любой из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2 5
11000
00011
1 3
3 5
4 2
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
1 3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 3 5
11000
00011
1 3
1 5
2 4
1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
1 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, изменения будут проходить вот так: </p><ul> <li> Поменяйте $$$1$$$ и $$$3$$$: <span class="tex-font-style-tt">11000</span> становится <span class="tex-font-style-tt">01100</span> </li><li> Поменяйте $$$3$$$ и $$$5$$$: <span class="tex-font-style-tt">01100</span> становится <span class="tex-font-style-tt">01001</span> </li><li> Поменяйте $$$4$$$ и $$$2$$$: <span class="tex-font-style-tt">01001</span> становится <span class="tex-font-style-tt">00011</span> </li></ul> Окончательная расстановка такая же, как и у идеального пирога <span class="tex-font-style-tt">00011</span>, поэтому есть $$$5$$$ позиций с тем же типом пирога, что и в оптимальной.<p>Во втором примере, изменения будут идти вот так: </p><ul> <li> Поменяйте $$$1$$$ и $$$3$$$: <span class="tex-font-style-tt">11000</span> становится <span class="tex-font-style-tt">01100</span> </li><li> Поменяйте $$$1$$$ и $$$5$$$: <span class="tex-font-style-tt">01100</span> становится <span class="tex-font-style-tt">01100</span> </li><li> Поменяйте $$$4$$$ и $$$2$$$: <span class="tex-font-style-tt">01100</span> становится <span class="tex-font-style-tt">00110</span> </li><li> Поменяйте $$$1$$$ и $$$5$$$: <span class="tex-font-style-tt">00110</span> становится <span class="tex-font-style-tt">00110</span> </li></ul> Окончательная расстановка имеет $$$3$$$ позиции с тем же типом пирога, что и идеальная расстановка <span class="tex-font-style-tt">00011</span>, это позиции $$$1$$$, $$$2$$$ и $$$4$$$. В этом случае подотрезок эльфов $$$(l, r) = (2, 3)$$$ более оптимален, но этот подотрезок имеет только длину $$$2$$$ и поэтому не удовлетворяет ограничению, заключающемуся в том, что подотрезок должен иметь длину не менее $$$m = 3$$$.</div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=G]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:47</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a87da9492de5',t:'MTY5NjY2NjEyNy4xMjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2900"] | ||
1392H | 1392 | H | ru | H. ZS тасует карты | <div class="problem-statement"><div class="header"><div class="title">H. ZS тасует карты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У <span class="tex-font-style-tt">zscoder</span> есть колода из $$$n+m$$$ карт, изготовленная по индивидуальному заказу, которая состоит из $$$n$$$ карт пронумерованных от $$$1$$$ до $$$n$$$ и $$$m$$$ джокеров. Так как <span class="tex-font-style-tt">zscoder</span> одинок, он хочет поиграть с сам с собой, используя эти карты. </p><p>Изначально колода перетасовывается в случайном порядке и кладется на стол. У <span class="tex-font-style-tt">zscoder</span> есть изначально пустое множество $$$S$$$. </p><p>Каждую секунду <span class="tex-font-style-tt">zscoder</span> вытягивает верхнюю карту из колоды. </p><ul> <li> Если на карте написано число $$$x$$$, <span class="tex-font-style-tt">zscoder</span> снимает карту и добавляет $$$x$$$ в множество $$$S$$$. </li><li> Если извлеченная карта является джокером, <span class="tex-font-style-tt">zscoder</span> помещает все карты обратно в колоду и перетасовывает (равномерно случайным образом) все $$$n+m$$$ карт, получая новую колоду (следовательно, новая колода также содержит все карты от $$$1$$$ до $$$n$$$ и $$$m$$$ джокеров). Затем, если $$$S$$$ в настоящее время содержит все элементы от $$$1$$$ до $$$n$$$, игра заканчивается. Перетасовка колоды не занимает времени. </li></ul><p>Какое матожидание количества секунд до окончания игры? Можно показать, что ответ можно записать в виде $$$\frac{P}{Q}$$$, где $$$P, Q$$$ — взаимно простые целые числа, где $$$Q \neq 0 \bmod 998244353$$$. Выведите значение $$$(P \cdot Q^{-1})$$$ по модулю $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два целых числа, $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^{6}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число, значение $$$(P \cdot Q^{-1})$$$ по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
332748127
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
14 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
969862773
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера можно доказать, что ожидаемое время до окончания игры составляет $$$5$$$ секунд.</p><p>Для второго примера можно доказать, что ожидаемое время до окончания игры составляет $$$\frac{28}{3}$$$секунды.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="3696b235e7a6fddb21c07f0f3cb6bb74"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - H - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - H - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='3696b235e7a6fddb21c07f0f3cb6bb74'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FH%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='3696b235e7a6fddb21c07f0f3cb6bb74'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='3696b235e7a6fddb21c07f0f3cb6bb74'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика">
комбинаторика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др.">
теория вероятностей
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3000
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3696b235e7a6fddb21c07f0f3cb6bb74'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700624"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3696b235e7a6fddb21c07f0f3cb6bb74'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700624"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="H" data-uuid="ps_02f9e835532b52f99646818b6ccba0ddcc7885db">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">H. ZS тасует карты</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У <span class="tex-font-style-tt">zscoder</span> есть колода из $$$n+m$$$ карт, изготовленная по индивидуальному заказу, которая состоит из $$$n$$$ карт пронумерованных от $$$1$$$ до $$$n$$$ и $$$m$$$ джокеров. Так как <span class="tex-font-style-tt">zscoder</span> одинок, он хочет поиграть с сам с собой, используя эти карты. </p><p>Изначально колода перетасовывается в случайном порядке и кладется на стол. У <span class="tex-font-style-tt">zscoder</span> есть изначально пустое множество $$$S$$$. </p><p>Каждую секунду <span class="tex-font-style-tt">zscoder</span> вытягивает верхнюю карту из колоды. </p><ul> <li> Если на карте написано число $$$x$$$, <span class="tex-font-style-tt">zscoder</span> снимает карту и добавляет $$$x$$$ в множество $$$S$$$. </li><li> Если извлеченная карта является джокером, <span class="tex-font-style-tt">zscoder</span> помещает все карты обратно в колоду и перетасовывает (равномерно случайным образом) все $$$n+m$$$ карт, получая новую колоду (следовательно, новая колода также содержит все карты от $$$1$$$ до $$$n$$$ и $$$m$$$ джокеров). Затем, если $$$S$$$ в настоящее время содержит все элементы от $$$1$$$ до $$$n$$$, игра заканчивается. Перетасовка колоды не занимает времени. </li></ul><p>Какое матожидание количества секунд до окончания игры? Можно показать, что ответ можно записать в виде $$$\frac{P}{Q}$$$, где $$$P, Q$$$ — взаимно простые целые числа, где $$$Q \neq 0 \bmod 998244353$$$. Выведите значение $$$(P \cdot Q^{-1})$$$ по модулю $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит два целых числа, $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^{6}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число, значение $$$(P \cdot Q^{-1})$$$ по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
332748127
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
14 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
969862773
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера можно доказать, что ожидаемое время до окончания игры составляет $$$5$$$ секунд.</p><p>Для второго примера можно доказать, что ожидаемое время до окончания игры составляет $$$\frac{28}{3}$$$секунды.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=H]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:48</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a88629769d75',t:'MTY5NjY2NjEyOC41ODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0412\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0438, \u043c\u0430\u0442. \u043e\u0436\u0438\u0434\u0430\u043d\u0438\u044f, \u0441\u043b\u0443\u0447\u0430\u0439\u043d\u044b\u0435 \u0432\u0435\u043b\u0438\u0447\u0438\u043d\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3000"] | ||
1392I | 1392 | I | ru | I. Кевин и сетка | <div class="problem-statement"><div class="header"><div class="title">I. Кевин и сетка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Когда Кевин был в доме БигМена, внезапно ловушка послала его в сетку из $$$n$$$ строк и $$$m$$$ столбцов.</p><p>Ловушка Бигмена задается двумя массивами: массивом $$$a_1,a_2,\ldots,a_n$$$ и массивом $$$b_1,b_2,\ldots,b_m$$$.</p><p>В $$$i$$$-м ряду находится нагреватель, который нагревает строку на $$$a_i$$$ градусов, а в $$$j$$$-м столбце — нагреватель, который нагревает столбец на $$$b_j$$$ градусов, так что температура ячейки $$$(i,j)$$$ равна $$$a_i+b_j$$$.</p><p>К счастью, у Кевина есть костюм с одним параметром $$$x$$$ и двумя режимами:</p><ul> <li> теплостойкость. В этом режиме костюм может выдержать все температуры больше или равные $$$x$$$, но замерзает, как только достигает ячейки с температурой ниже $$$x$$$. </li><li> холодостойкость. В этом режиме костюм может выдержать все температуры ниже $$$x$$$, но замерзает, как только достигает ячейки с температурой не ниже $$$x$$$.</li></ul><p>Как только Кевин приземляется на ячейку, костюм автоматически переходит в режим холодостойкости, если ячейка имеет температуру ниже $$$x$$$, или в режим теплостойкости в противном случае, и не может измениться после этого.</p><p>Мы говорим, что две ячейки соседние, если они имеют общую сторону.</p><p>Назовем путем последовательность $$$c_1,c_2,\ldots,c_k$$$ ячеек такую, что $$$c_i$$$ и $$$c_{i+1}$$$ соседние для всех $$$1 \leq i \leq k-1$$$.</p><p>Скажем, что две ячейки соединены, если между ними есть путь, состоящий только из ячеек, на которые Кевин может наступать.</p><p>Связанная компонента — это максимальный набор попарно связанных ячеек.</p><p>Назовем связанную компоненту <span class="tex-font-style-bf">хорошей</span>, если Кевин может выбраться из сетки, начав в ней, то есть если она содержит хотя бы одну ячейку с границы сетки, и <span class="tex-font-style-bf">плохой</span> в противном случае.</p><p>Чтобы оценить ситуацию, Кевин дает оценку $$$1$$$ каждой хорошей компоненте и $$$2$$$ каждой плохой компоненте.</p><p>Итоговой оценкой будет разница между общей оценкой компонент с температурами больше или равными $$$x$$$ и общей оценкой компонентов с температурами меньше $$$x$$$.</p><p>Кевин может использовать $$$q$$$ возможных значений $$$x$$$, и для каждого из них Кевин хочет знать итоговую оценку.</p><p>Помогите Кевину победить Бигмена!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$,$$$m$$$,$$$q$$$ ($$$1 \leq n,m,q \leq 10^5$$$) — количество строк, столбцов и количество возможных значений для $$$x$$$ соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$).</p><p>Третья строка содержит $$$m$$$ целых чисел $$$b_1, b_2, \dots, b_m$$$ ($$$1 \leq b_i \leq 10^5$$$).</p><p>Каждая из следующих $$$q$$$ строк содержит одно целое число $$$x$$$ ($$$1 \leq x \leq 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк, в $$$i$$$-й строке выведите ответ на $$$i$$$-е возможное значение $$$x$$$ из входных данных.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5 5 1
1 3 2 3 1
1 3 2 3 1
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 3 2
1 2 2
2 1 2
3
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, оценка для компонентов с температурой менее $$$5$$$ составляет $$$1+2$$$, а оценка для компонентов с температурой хотя бы $$$5$$$ составляет $$$2$$$. Таким образом, итоговая оценка составляет $$$2-3=-1$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="80a0dbbcfdfb4e5f8822033f8d031d9f"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - I - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="656ccbbb33c600806cb2c1325d4eb16e9f6dd69e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - I - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='80a0dbbcfdfb4e5f8822033f8d031d9f'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1392%2Fproblem%2FI%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='80a0dbbcfdfb4e5f8822033f8d031d9f'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1392">Codeforces Global Round 10</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='80a0dbbcfdfb4e5f8822033f8d031d9f'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1392/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье">
бпф
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='80a0dbbcfdfb4e5f8822033f8d031d9f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="700625"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='80a0dbbcfdfb4e5f8822033f8d031d9f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="700625"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81377" title="Codeforces Global Round 10" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11614" resourceName="Codeforces Global Round 10"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81565" title="Codeforces Global Round 10 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11672" resourceName="Codeforces Global Round 10 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1392">Задачи</a></li>
<li><a
href="/contest/1392/submit">Отослать</a></li>
<li><a
href="/contest/1392/my">Мои посылки</a></li>
<li><a
href="/contest/1392/status">Статус</a></li>
<li><a
href="/contest/1392/hacks">Взломы</a></li>
<li><a
href="/contest/1392/room/1">Комната</a></li>
<li><a
href="/contest/1392/standings">Положение</a></li>
<li><a
href="/contest/1392/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="I" data-uuid="ps_0e471a13e47de5481c37a04fbd94b19652ba3d39">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">I. Кевин и сетка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Когда Кевин был в доме БигМена, внезапно ловушка послала его в сетку из $$$n$$$ строк и $$$m$$$ столбцов.</p><p>Ловушка Бигмена задается двумя массивами: массивом $$$a_1,a_2,\ldots,a_n$$$ и массивом $$$b_1,b_2,\ldots,b_m$$$.</p><p>В $$$i$$$-м ряду находится нагреватель, который нагревает строку на $$$a_i$$$ градусов, а в $$$j$$$-м столбце — нагреватель, который нагревает столбец на $$$b_j$$$ градусов, так что температура ячейки $$$(i,j)$$$ равна $$$a_i+b_j$$$.</p><p>К счастью, у Кевина есть костюм с одним параметром $$$x$$$ и двумя режимами:</p><ul> <li> теплостойкость. В этом режиме костюм может выдержать все температуры больше или равные $$$x$$$, но замерзает, как только достигает ячейки с температурой ниже $$$x$$$. </li><li> холодостойкость. В этом режиме костюм может выдержать все температуры ниже $$$x$$$, но замерзает, как только достигает ячейки с температурой не ниже $$$x$$$.</li></ul><p>Как только Кевин приземляется на ячейку, костюм автоматически переходит в режим холодостойкости, если ячейка имеет температуру ниже $$$x$$$, или в режим теплостойкости в противном случае, и не может измениться после этого.</p><p>Мы говорим, что две ячейки соседние, если они имеют общую сторону.</p><p>Назовем путем последовательность $$$c_1,c_2,\ldots,c_k$$$ ячеек такую, что $$$c_i$$$ и $$$c_{i+1}$$$ соседние для всех $$$1 \leq i \leq k-1$$$.</p><p>Скажем, что две ячейки соединены, если между ними есть путь, состоящий только из ячеек, на которые Кевин может наступать.</p><p>Связанная компонента — это максимальный набор попарно связанных ячеек.</p><p>Назовем связанную компоненту <span class="tex-font-style-bf">хорошей</span>, если Кевин может выбраться из сетки, начав в ней, то есть если она содержит хотя бы одну ячейку с границы сетки, и <span class="tex-font-style-bf">плохой</span> в противном случае.</p><p>Чтобы оценить ситуацию, Кевин дает оценку $$$1$$$ каждой хорошей компоненте и $$$2$$$ каждой плохой компоненте.</p><p>Итоговой оценкой будет разница между общей оценкой компонент с температурами больше или равными $$$x$$$ и общей оценкой компонентов с температурами меньше $$$x$$$.</p><p>Кевин может использовать $$$q$$$ возможных значений $$$x$$$, и для каждого из них Кевин хочет знать итоговую оценку.</p><p>Помогите Кевину победить Бигмена!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$,$$$m$$$,$$$q$$$ ($$$1 \leq n,m,q \leq 10^5$$$) — количество строк, столбцов и количество возможных значений для $$$x$$$ соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$).</p><p>Третья строка содержит $$$m$$$ целых чисел $$$b_1, b_2, \dots, b_m$$$ ($$$1 \leq b_i \leq 10^5$$$).</p><p>Каждая из следующих $$$q$$$ строк содержит одно целое число $$$x$$$ ($$$1 \leq x \leq 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк, в $$$i$$$-й строке выведите ответ на $$$i$$$-е возможное значение $$$x$$$ из входных данных.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5 5 1
1 3 2 3 1
1 3 2 3 1
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 3 2
1 2 2
2 1 2
3
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, оценка для компонентов с температурой менее $$$5$$$ составляет $$$1+2$$$, а оценка для компонентов с температурой хотя бы $$$5$$$ составляет $$$2$$$. Таким образом, итоговая оценка составляет $$$2-3=-1$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=I]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:50</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a88f5cbc7a64',t:'MTY5NjY2NjEzMC4wNTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u044b\u0441\u0442\u0440\u043e\u0435 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0424\u0443\u0440\u044c\u0435", "\u0413\u0440\u0430\u0444\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u043f\u0444", "\u0433\u0440\u0430\u0444\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3300"] | ||
1393A | 1393 | A | ru | A. Радуга, Флаттершай и шахматная раскраска | <div class="problem-statement"><div class="header"><div class="title">A. Радуга, Флаттершай и шахматная раскраска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Одним вечером Радуга и Флаттершай придумали игру. Так как пони дружат, то и в игре они решили не соревноваться, а вместе двигаться к общей цели.</p><p>Игра начинается на квадратном плоском поле, у которого изначально выложены внешние границы. У Радуги и Флаттершай есть квадратные плоские фишки размера $$$1\times1$$$, у Радуги бесконечное число голубых фишек, у Флаттершай бесконечное число желтых фишек. </p><p>Фишки выкладываются по следующему правилу: каждая новая выкладываемая фишка должна соприкасаться стороной с уже построенной фигурой (внешняя граница игрового поля считается построенной изначально). На очередном ходу одна пони может выложить любое количество фишек своего цвета в соответствие с правилами игры.</p><p>Радуга и Флаттершай догадались, что таким образом можно выкладывать различные узоры на игровом поле. Они решили начать с чего-то простого, поэтому решили выложить фишки так, чтобы они образовали <span class="tex-font-style-bf">шахматную раскраску</span>. Радуга славится своей скоростью, поэтому ей стало интересно, за какое минимальное количество ходов они с Флаттершай смогут получить шахматную раскраску, закрыв все поле фишками. Помогите ей найти это количество!</p><p>Так как пони могут играть много раз на разных досках, Радуга просит найти минимальное количество ходов для нескольких игровых полей.</p><p>Напоминаем, что шахматная раскраска поля в два цвета — та, в которой любая клетка соседствует по стороне только с клетками другого цвета.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество игровых полей. Каждая из следующих $$$T$$$ строк содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^9$$$) — сторона поля. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого игрового поля выведите минимальное количество ходов, чтобы выложить на нем шахматную раскраску из фишек.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
3
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для поля $$$3\times3$$$ пони могут сделать два следующих хода: <img class="tex-graphics" src="https://espresso.codeforces.com/d847e618f3087a23400280c5f2bee399134a4718.png" style="max-width: 100.0%;max-height: 100.0%;"/></p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="9790a709fcb52b79f5ac29af12fda9bf"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0f8d52ed84281d3834f7537189baefff5a31fe2f"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='9790a709fcb52b79f5ac29af12fda9bf'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1393%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='9790a709fcb52b79f5ac29af12fda9bf'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1393">Codeforces Round 662 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='9790a709fcb52b79f5ac29af12fda9bf'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1393/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9790a709fcb52b79f5ac29af12fda9bf'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="693070"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9790a709fcb52b79f5ac29af12fda9bf'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="693070"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81037" title="Codeforces Round #662 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11557:11558" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81161" title="Codeforces Round #662 Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11841:11842" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1393">Задачи</a></li>
<li><a
href="/contest/1393/submit">Отослать</a></li>
<li><a
href="/contest/1393/my">Мои посылки</a></li>
<li><a
href="/contest/1393/status">Статус</a></li>
<li><a
href="/contest/1393/hacks">Взломы</a></li>
<li><a
href="/contest/1393/room/1">Комната</a></li>
<li><a
href="/contest/1393/standings">Положение</a></li>
<li><a
href="/contest/1393/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_5f647f3bb60072effa8a43cd5fd5eed65ba431eb">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Радуга, Флаттершай и шахматная раскраска</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Одним вечером Радуга и Флаттершай придумали игру. Так как пони дружат, то и в игре они решили не соревноваться, а вместе двигаться к общей цели.</p><p>Игра начинается на квадратном плоском поле, у которого изначально выложены внешние границы. У Радуги и Флаттершай есть квадратные плоские фишки размера $$$1\times1$$$, у Радуги бесконечное число голубых фишек, у Флаттершай бесконечное число желтых фишек. </p><p>Фишки выкладываются по следующему правилу: каждая новая выкладываемая фишка должна соприкасаться стороной с уже построенной фигурой (внешняя граница игрового поля считается построенной изначально). На очередном ходу одна пони может выложить любое количество фишек своего цвета в соответствие с правилами игры.</p><p>Радуга и Флаттершай догадались, что таким образом можно выкладывать различные узоры на игровом поле. Они решили начать с чего-то простого, поэтому решили выложить фишки так, чтобы они образовали <span class="tex-font-style-bf">шахматную раскраску</span>. Радуга славится своей скоростью, поэтому ей стало интересно, за какое минимальное количество ходов они с Флаттершай смогут получить шахматную раскраску, закрыв все поле фишками. Помогите ей найти это количество!</p><p>Так как пони могут играть много раз на разных досках, Радуга просит найти минимальное количество ходов для нескольких игровых полей.</p><p>Напоминаем, что шахматная раскраска поля в два цвета — та, в которой любая клетка соседствует по стороне только с клетками другого цвета.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество игровых полей. Каждая из следующих $$$T$$$ строк содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^9$$$) — сторона поля. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого игрового поля выведите минимальное количество ходов, чтобы выложить на нем шахматную раскраску из фишек.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
3
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для поля $$$3\times3$$$ пони могут сделать два следующих хода: <img class="tex-graphics" src="https://espresso.codeforces.com/d847e618f3087a23400280c5f2bee399134a4718.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:51</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a898b9ac9d6f',t:'MTY5NjY2NjEzMS41OTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"] | ||
1393B | 1393 | B | ru | B. Эпплджек и хранилища | <div class="problem-statement"><div class="header"><div class="title">B. Эпплджек и хранилища</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Этот год в Эквестрии выдался урожайным, и Эпплджек захотела построить новые хранилища для яблок. По советам проектировщиков фермы она решила построить два хранилища ненулевой площади: одно в форме квадрата, другое в форме прямоугольника (который, возможно, тоже является квадратом).</p><p>Хранилища Эпплджек будет строить из досок, на каждую сторону хранилища она собирается потратить ровно одну доску. Доски она может заказать в одной фирме у своего приятеля. Изначально на складе фирмы есть $$$n$$$ досок, длины которых Эпплджек известны. Работа фирмы не стоит на месте, она периодически получает заказы и сама заказывает новые доски. Приятель Эпплджек может предоставить ей информацию о всех операциях. Для удобства он будет сообщать информацию в следующем формате:</p><ul> <li> $$$+$$$ $$$x$$$ — на склад поступила доска с длиной $$$x$$$ </li><li> $$$-$$$ $$$x$$$ — со склада отгрузили доску с длиной $$$x$$$ (при этом гарантируется, что на складе были какие-то доски длины $$$x$$$) </li></ul><p>Эпплджек пока не определилась, когда она будет заказывать доски, поэтому она хочет после каждого события на складе знать, может ли она заказать доски, чтобы построить прямоугольное и квадратное хранилища. Эпплджек занята сбором яблок, поэтому у нее нет времени на подсчеты, и она попросила вас помочь ей!</p><p>Напоминаем, что у квадрата все четыре стороны равны, а у прямоугольника две пары равных сторон.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — изначальное количество досок на складе фирмы, вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — длины досок.</p><p>Третья строка содержит одно целое число $$$q$$$ ($$$1 \le q \le 10^5$$$) — количество событий в фирме. Каждая из следующих $$$q$$$ строк содержит описание событий в данном формате: сначала идет тип события (символ $$$+$$$ или $$$-$$$), а затем число $$$x$$$ ($$$1 \le x \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>После каждого события на фирме выведите «<span class="tex-font-style-tt">YES</span>», если из досок на складе фирмы можно собрать два хранилища нужной формы, и «<span class="tex-font-style-tt">NO</span>» иначе (без кавычек). Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
1 1 1 2 1 1
6
+ 2
+ 1
- 1
+ 2
- 1
+ 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
YES
NO
NO
NO
YES
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>После второго события Эпплджек может построить прямоугольное хранилище из досок с длинами $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ и квадратное хранилище из досок с длинами $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.</p><p>После шестого события Эпплджек может построить прямоугольное хранилище из досок с длинами $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$ и квадратное хранилище из досок с длинами $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="e45f108e20a99966497c2747ab1bcad2"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0f8d52ed84281d3834f7537189baefff5a31fe2f"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='e45f108e20a99966497c2747ab1bcad2'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1393%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='e45f108e20a99966497c2747ab1bcad2'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1393">Codeforces Round 662 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='e45f108e20a99966497c2747ab1bcad2'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1393/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e45f108e20a99966497c2747ab1bcad2'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="693071"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e45f108e20a99966497c2747ab1bcad2'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="693071"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81037" title="Codeforces Round #662 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11557:11558" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81161" title="Codeforces Round #662 Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11841:11842" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1393">Задачи</a></li>
<li><a
href="/contest/1393/submit">Отослать</a></li>
<li><a
href="/contest/1393/my">Мои посылки</a></li>
<li><a
href="/contest/1393/status">Статус</a></li>
<li><a
href="/contest/1393/hacks">Взломы</a></li>
<li><a
href="/contest/1393/room/1">Комната</a></li>
<li><a
href="/contest/1393/standings">Положение</a></li>
<li><a
href="/contest/1393/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_c2eebf249c8533668b9275987bcd4f314f1ff449">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Эпплджек и хранилища</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Этот год в Эквестрии выдался урожайным, и Эпплджек захотела построить новые хранилища для яблок. По советам проектировщиков фермы она решила построить два хранилища ненулевой площади: одно в форме квадрата, другое в форме прямоугольника (который, возможно, тоже является квадратом).</p><p>Хранилища Эпплджек будет строить из досок, на каждую сторону хранилища она собирается потратить ровно одну доску. Доски она может заказать в одной фирме у своего приятеля. Изначально на складе фирмы есть $$$n$$$ досок, длины которых Эпплджек известны. Работа фирмы не стоит на месте, она периодически получает заказы и сама заказывает новые доски. Приятель Эпплджек может предоставить ей информацию о всех операциях. Для удобства он будет сообщать информацию в следующем формате:</p><ul> <li> $$$+$$$ $$$x$$$ — на склад поступила доска с длиной $$$x$$$ </li><li> $$$-$$$ $$$x$$$ — со склада отгрузили доску с длиной $$$x$$$ (при этом гарантируется, что на складе были какие-то доски длины $$$x$$$) </li></ul><p>Эпплджек пока не определилась, когда она будет заказывать доски, поэтому она хочет после каждого события на складе знать, может ли она заказать доски, чтобы построить прямоугольное и квадратное хранилища. Эпплджек занята сбором яблок, поэтому у нее нет времени на подсчеты, и она попросила вас помочь ей!</p><p>Напоминаем, что у квадрата все четыре стороны равны, а у прямоугольника две пары равных сторон.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — изначальное количество досок на складе фирмы, вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — длины досок.</p><p>Третья строка содержит одно целое число $$$q$$$ ($$$1 \le q \le 10^5$$$) — количество событий в фирме. Каждая из следующих $$$q$$$ строк содержит описание событий в данном формате: сначала идет тип события (символ $$$+$$$ или $$$-$$$), а затем число $$$x$$$ ($$$1 \le x \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>После каждого события на фирме выведите «<span class="tex-font-style-tt">YES</span>», если из досок на складе фирмы можно собрать два хранилища нужной формы, и «<span class="tex-font-style-tt">NO</span>» иначе (без кавычек). Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
1 1 1 2 1 1
6
+ 2
+ 1
- 1
+ 2
- 1
+ 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
YES
NO
NO
NO
YES
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>После второго события Эпплджек может построить прямоугольное хранилище из досок с длинами $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ и квадратное хранилище из досок с длинами $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.</p><p>После шестого события Эпплджек может построить прямоугольное хранилище из досок с длинами $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$ и квадратное хранилище из досок с длинами $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:53</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8a22a46167e',t:'MTY5NjY2NjEzMy4wMzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1400"] | ||
1393C | 1393 | C | ru | C. Пинки Пай поедает пирожные | <div class="problem-statement"><div class="header"><div class="title">C. Пинки Пай поедает пирожные</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Пинки Пай купила пакет пирожных с разными начинками! Но оказалось, что не все пирожные различаются начинкой между собой, то есть в пакете есть какие-то пирожные с одинаковой начинкой.</p><p>Пинки Пай ест пирожные по одному подряд. Она любит веселиться, поэтому решила не просто поедать пирожные, а стараться не есть пирожные с одной начинкой слишком часто. Для этого она хочет, чтобы минимальное расстояние между съеденными пирожными с одинаковой начинкой было как можно больше. При этом расстоянием между двумя пирожными Пинки Пай решила назвать количество съеденных пирожных между ними.</p><p>Пинки Пай может поедать пирожные в любом порядке. Ей не терпится скорее съесть все пирожные, поэтому она просит вас помочь посчитать наибольшее минимальное расстояние между съеденными пирожными с одинаковой начинкой среди всех возможных порядков поедания!</p><p>Пинки Пай собирается покупать еще пакеты с пирожными, поэтому просит вас решить задачу для нескольких пакетов!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество пакетов, для которых нужно решить задачу.</p><p>Первая строка описания пакета содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — количество пирожных в нем. Вторая строка описания пакета содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — информация о начинках пирожных: одинаковые начинки обозначены одинаковым числом, разные начинки — разным. Гарантируется, что в каждом пакете есть как минимум два пирожных с одинаковой начинкой.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем пакетам не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого пакета в отдельной выведите одно целое число — наибольшее минимальное расстояние между съеденными пирожными с одинаковой начинкой среди всех возможных порядков поедания пирожных из этого пакета.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
7
1 7 1 6 4 4 6
8
1 1 4 6 4 6 4 7
3
3 3 3
6
2 5 2 3 1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
2
0
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого пакета Пинки Пай может есть пирожные в следующем порядке (по начинкам): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (таким образом, минимальное расстояние будет равно $$$3$$$).</p><p>Для второго пакета Пинки Пай может есть пирожные в следующем порядке (по начинкам): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (таким образом, минимальное расстояние будет равно $$$2$$$).</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="91858b6b4c5d85474bbae6533fe4b600"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0f8d52ed84281d3834f7537189baefff5a31fe2f"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='91858b6b4c5d85474bbae6533fe4b600'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1393%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='91858b6b4c5d85474bbae6533fe4b600'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1393">Codeforces Round 662 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='91858b6b4c5d85474bbae6533fe4b600'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1393/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1700
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='91858b6b4c5d85474bbae6533fe4b600'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="693072"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='91858b6b4c5d85474bbae6533fe4b600'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="693072"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81037" title="Codeforces Round #662 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11557:11558" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81161" title="Codeforces Round #662 Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11841:11842" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1393">Задачи</a></li>
<li><a
href="/contest/1393/submit">Отослать</a></li>
<li><a
href="/contest/1393/my">Мои посылки</a></li>
<li><a
href="/contest/1393/status">Статус</a></li>
<li><a
href="/contest/1393/hacks">Взломы</a></li>
<li><a
href="/contest/1393/room/1">Комната</a></li>
<li><a
href="/contest/1393/standings">Положение</a></li>
<li><a
href="/contest/1393/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_444179631dc753c61957477ce49dace69f673824">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Пинки Пай поедает пирожные</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Пинки Пай купила пакет пирожных с разными начинками! Но оказалось, что не все пирожные различаются начинкой между собой, то есть в пакете есть какие-то пирожные с одинаковой начинкой.</p><p>Пинки Пай ест пирожные по одному подряд. Она любит веселиться, поэтому решила не просто поедать пирожные, а стараться не есть пирожные с одной начинкой слишком часто. Для этого она хочет, чтобы минимальное расстояние между съеденными пирожными с одинаковой начинкой было как можно больше. При этом расстоянием между двумя пирожными Пинки Пай решила назвать количество съеденных пирожных между ними.</p><p>Пинки Пай может поедать пирожные в любом порядке. Ей не терпится скорее съесть все пирожные, поэтому она просит вас помочь посчитать наибольшее минимальное расстояние между съеденными пирожными с одинаковой начинкой среди всех возможных порядков поедания!</p><p>Пинки Пай собирается покупать еще пакеты с пирожными, поэтому просит вас решить задачу для нескольких пакетов!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество пакетов, для которых нужно решить задачу.</p><p>Первая строка описания пакета содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — количество пирожных в нем. Вторая строка описания пакета содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — информация о начинках пирожных: одинаковые начинки обозначены одинаковым числом, разные начинки — разным. Гарантируется, что в каждом пакете есть как минимум два пирожных с одинаковой начинкой.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем пакетам не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого пакета в отдельной выведите одно целое число — наибольшее минимальное расстояние между съеденными пирожными с одинаковой начинкой среди всех возможных порядков поедания пирожных из этого пакета.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
7
1 7 1 6 4 4 6
8
1 1 4 6 4 6 4 7
3
3 3 3
6
2 5 2 3 1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
2
0
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого пакета Пинки Пай может есть пирожные в следующем порядке (по начинкам): $$$1$$$, $$$6$$$, $$$4$$$, $$$7$$$, $$$1$$$, $$$6$$$, $$$4$$$ (таким образом, минимальное расстояние будет равно $$$3$$$).</p><p>Для второго пакета Пинки Пай может есть пирожные в следующем порядке (по начинкам): $$$1$$$, $$$4$$$, $$$6$$$, $$$7$$$, $$$4$$$, $$$1$$$, $$$6$$$, $$$4$$$ (таким образом, минимальное расстояние будет равно $$$2$$$).</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:54</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8ab2b4c163a',t:'MTY5NjY2NjEzNC40MTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1700"] | ||
1393D | 1393 | D | ru | D. Рарити и новое платье | <div class="problem-statement"><div class="header"><div class="title">D. Рарити и новое платье</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В бутике Карусель вновь кипит работа! Рарити решила посетить бал пони и для этого ей, конечно, необходимо новое платье, ведь выходить в свет в одном и том же платье несколько раз является признаком дурного тона. Для того чтобы сшить платье, ей прежде всего нужна выкройка, которую она вырежет из прямоугольного куска разноцветной ткани.</p><p>Кусок разноцветной ткани состоит из $$$n \times m$$$ отдельных квадратных лоскутков. Так как Рарити любит платья со вкусом, выкройка должна быть целиком составлена из лоскутков одного цвета. Выкройка должна быть квадратной и, так как Рарити обожает ромбы, его стороны должны находиться под углом $$$45^{\circ}$$$ к сторонам куска ткани (так он больше всего похож на классическое представление ромба).</p><p>Примеры подходящих выкроек: <img class="tex-graphics" src="https://espresso.codeforces.com/2756dfb01eeaf6b75dd6dd252612345a7bad4ffd.png" style="max-width: 100.0%;max-height: 100.0%;"/> Примеры неподходящих выкроек: <img class="tex-graphics" src="https://espresso.codeforces.com/b740e2ece16c83803cdb78a1392a61c56ace12de.png" style="max-width: 100.0%;max-height: 100.0%;"/> Первая состоит из лоскутков разного цвета, вторая выходит за границы куска ткани, третья не является квадратом со сторонами под углом $$$45^{\circ}$$$ к сторонам куска ткани.</p><p>Рарити интересно, сколько существует вариантов вырезать выкройку, которая удовлетворяет всем нужным условиям. Помогите ей удовлетворить свое любопытство, чтобы она могла продолжать работу над своим новым шедевром!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2000$$$). Каждая из следующих $$$n$$$ строк содержит $$$m$$$ символов — строчных латинских букв, $$$j$$$-я из которых соответствует лоскутку в текущей строке и $$$j$$$-м столбце. Лоскутки с одинаковыми буквами имеют одинаковые цвета, с различными — различные.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — количество способов вырезать выкройку, чтобы удовлетворить условия Рарити.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 3
aaa
aaa
aaa
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 4
abab
baba
abab
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5
zbacg
baaac
aaaaa
eaaad
weadd
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
31
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте из условия подходят все выкройки размера $$$1$$$ и одна размера $$$2$$$.</p><p>Во втором тесте из условия подходят только выкройки размера $$$1$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="45a50aeeb31cb2ff8e8baaccdd96887f"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0f8d52ed84281d3834f7537189baefff5a31fe2f"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='45a50aeeb31cb2ff8e8baaccdd96887f'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1393%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='45a50aeeb31cb2ff8e8baaccdd96887f'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1393">Codeforces Round 662 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='45a50aeeb31cb2ff8e8baaccdd96887f'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1393/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах">
кратчайшие пути
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2100
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='45a50aeeb31cb2ff8e8baaccdd96887f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="693073"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='45a50aeeb31cb2ff8e8baaccdd96887f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="693073"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81037" title="Codeforces Round #662 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11557:11558" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81161" title="Codeforces Round #662 Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11841:11842" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1393">Задачи</a></li>
<li><a
href="/contest/1393/submit">Отослать</a></li>
<li><a
href="/contest/1393/my">Мои посылки</a></li>
<li><a
href="/contest/1393/status">Статус</a></li>
<li><a
href="/contest/1393/hacks">Взломы</a></li>
<li><a
href="/contest/1393/room/1">Комната</a></li>
<li><a
href="/contest/1393/standings">Положение</a></li>
<li><a
href="/contest/1393/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_09ba3f6b116162a82afc4487bf3dddbb6858d345">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Рарити и новое платье</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В бутике Карусель вновь кипит работа! Рарити решила посетить бал пони и для этого ей, конечно, необходимо новое платье, ведь выходить в свет в одном и том же платье несколько раз является признаком дурного тона. Для того чтобы сшить платье, ей прежде всего нужна выкройка, которую она вырежет из прямоугольного куска разноцветной ткани.</p><p>Кусок разноцветной ткани состоит из $$$n \times m$$$ отдельных квадратных лоскутков. Так как Рарити любит платья со вкусом, выкройка должна быть целиком составлена из лоскутков одного цвета. Выкройка должна быть квадратной и, так как Рарити обожает ромбы, его стороны должны находиться под углом $$$45^{\circ}$$$ к сторонам куска ткани (так он больше всего похож на классическое представление ромба).</p><p>Примеры подходящих выкроек: <img class="tex-graphics" src="https://espresso.codeforces.com/2756dfb01eeaf6b75dd6dd252612345a7bad4ffd.png" style="max-width: 100.0%;max-height: 100.0%;" /> Примеры неподходящих выкроек: <img class="tex-graphics" src="https://espresso.codeforces.com/b740e2ece16c83803cdb78a1392a61c56ace12de.png" style="max-width: 100.0%;max-height: 100.0%;" /> Первая состоит из лоскутков разного цвета, вторая выходит за границы куска ткани, третья не является квадратом со сторонами под углом $$$45^{\circ}$$$ к сторонам куска ткани.</p><p>Рарити интересно, сколько существует вариантов вырезать выкройку, которая удовлетворяет всем нужным условиям. Помогите ей удовлетворить свое любопытство, чтобы она могла продолжать работу над своим новым шедевром!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2000$$$). Каждая из следующих $$$n$$$ строк содержит $$$m$$$ символов — строчных латинских букв, $$$j$$$-я из которых соответствует лоскутку в текущей строке и $$$j$$$-м столбце. Лоскутки с одинаковыми буквами имеют одинаковые цвета, с различными — различные.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — количество способов вырезать выкройку, чтобы удовлетворить условия Рарити.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 3
aaa
aaa
aaa
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 4
abab
baba
abab
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5
zbacg
baaac
aaaaa
eaaad
weadd
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
31
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте из условия подходят все выкройки размера $$$1$$$ и одна размера $$$2$$$.</p><p>Во втором тесте из условия подходят только выкройки размера $$$1$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:55</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8b3cac0162e',t:'MTY5NjY2NjEzNS44MjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2100"] | ||
1393E1 | 1393 | E1 | ru | E1. Искорка и древний свиток (упрощенная версия) | <div class="problem-statement"><div class="header"><div class="title">E1. Искорка и древний свиток (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более простая версия задачи E с меньшими ограничениями.</span></p><p>Сумеречная Искорка получила новое задание от принцессы Селестии. В этот раз Искорке нужно расшифровать древний свиток, содержащий важные знания о происхождении пони.</p><p>Чтобы скрыть важнейшую информацию от злых глаз, старейшины пони заколдовали свиток. Заклинание вставляет ровно одну букву в любое место каждого словa, к которому оно применено. Чтобы сделать путь к знанию более запутанным, старейшины выбрали некоторые из слов свитка и применили к ним заклинание.</p><p>Сумеречная Искорка знает, что старейшины во всем почитали порядок, поэтому изначально свиток содержал слова в <span class="tex-font-style-bf">лексикографически неубывающем порядке</span>. Искорке нужно удалить по одной букве из некоторых слов в свитке (чтобы отменить заклинание), для того чтобы получить какую-то версию изначального свитка. </p><p>К сожалению, Искорка не всегда может однозначно восстановить древний свиток. Чтобы не упустить важные знания, ей придется перебрать все варианты изначального свитка и найти нужный. Чтобы оценить максимальное время, которое Искорка потратит на работу, ей нужно знать количество вариантов, которые ей нужно перебрать. Она просит вас найти это количество! Так как это количество может быть слишком большим, Искорке достаточно лишь знать его по модулю $$$10^9+7$$$, остальную часть она сможет оценить сама.</p><p>Могло случиться так, что принцесса Селестия отправила неверный свиток, и Искорка не сможет получить никакую версию изначального свитка.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в строке $$$a$$$ находится буква, которая встречается в алфавите раньше, чем соответствующая буква в $$$b$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 1000$$$) — количество слов в свитке. $$$i$$$-я из следующих $$$n$$$ строк содержит строку, состоящую из строчных букв латинского алфавита — $$$i$$$-е слово свитка. Длина каждого слова больше либо равна $$$1$$$. Суммарная длина всех слов не превосходит $$$20000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество вариантов получить версию оригинала из свитка по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
abcd
zaza
ataka
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
dfs
bfs
sms
mms
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
abc
bcd
a
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
lapochka
kartyshka
bigbabytape
morgenshtern
ssshhhiiittt
queen
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2028
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Заметьте, что старейшины могли написать пустое слово (но тогда они точно применили к нему заклинание, и таким образом это слово теперь имеет длину $$$1$$$).</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="dcf72debcee93f0825b1910f86a61357"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E1 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0f8d52ed84281d3834f7537189baefff5a31fe2f"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E1 - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='dcf72debcee93f0825b1910f86a61357'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1393%2Fproblem%2FE1%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='dcf72debcee93f0825b1910f86a61357'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1393">Codeforces Round 662 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='dcf72debcee93f0825b1910f86a61357'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1393/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Суффиксные массивы, деревья и автоматы">
строковые суфф. структуры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы">
хэши
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dcf72debcee93f0825b1910f86a61357'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="693074"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dcf72debcee93f0825b1910f86a61357'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="693074"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81037" title="Codeforces Round #662 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11557:11558" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81161" title="Codeforces Round #662 Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11841:11842" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1393">Задачи</a></li>
<li><a
href="/contest/1393/submit">Отослать</a></li>
<li><a
href="/contest/1393/my">Мои посылки</a></li>
<li><a
href="/contest/1393/status">Статус</a></li>
<li><a
href="/contest/1393/hacks">Взломы</a></li>
<li><a
href="/contest/1393/room/1">Комната</a></li>
<li><a
href="/contest/1393/standings">Положение</a></li>
<li><a
href="/contest/1393/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E1" data-uuid="ps_793c8a7a23730f90e3d4bf3541c5978cc32d19b4">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E1. Искорка и древний свиток (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более простая версия задачи E с меньшими ограничениями.</span></p><p>Сумеречная Искорка получила новое задание от принцессы Селестии. В этот раз Искорке нужно расшифровать древний свиток, содержащий важные знания о происхождении пони.</p><p>Чтобы скрыть важнейшую информацию от злых глаз, старейшины пони заколдовали свиток. Заклинание вставляет ровно одну букву в любое место каждого словa, к которому оно применено. Чтобы сделать путь к знанию более запутанным, старейшины выбрали некоторые из слов свитка и применили к ним заклинание.</p><p>Сумеречная Искорка знает, что старейшины во всем почитали порядок, поэтому изначально свиток содержал слова в <span class="tex-font-style-bf">лексикографически неубывающем порядке</span>. Искорке нужно удалить по одной букве из некоторых слов в свитке (чтобы отменить заклинание), для того чтобы получить какую-то версию изначального свитка. </p><p>К сожалению, Искорка не всегда может однозначно восстановить древний свиток. Чтобы не упустить важные знания, ей придется перебрать все варианты изначального свитка и найти нужный. Чтобы оценить максимальное время, которое Искорка потратит на работу, ей нужно знать количество вариантов, которые ей нужно перебрать. Она просит вас найти это количество! Так как это количество может быть слишком большим, Искорке достаточно лишь знать его по модулю $$$10^9+7$$$, остальную часть она сможет оценить сама.</p><p>Могло случиться так, что принцесса Селестия отправила неверный свиток, и Искорка не сможет получить никакую версию изначального свитка.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в строке $$$a$$$ находится буква, которая встречается в алфавите раньше, чем соответствующая буква в $$$b$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 1000$$$) — количество слов в свитке. $$$i$$$-я из следующих $$$n$$$ строк содержит строку, состоящую из строчных букв латинского алфавита — $$$i$$$-е слово свитка. Длина каждого слова больше либо равна $$$1$$$. Суммарная длина всех слов не превосходит $$$20000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество вариантов получить версию оригинала из свитка по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
abcd
zaza
ataka
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
dfs
bfs
sms
mms
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
abc
bcd
a
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
lapochka
kartyshka
bigbabytape
morgenshtern
ssshhhiiittt
queen
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2028
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Заметьте, что старейшины могли написать пустое слово (но тогда они точно применили к нему заклинание, и таким образом это слово теперь имеет длину $$$1$$$).</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E1]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:57</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8bcdef016f7',t:'MTY5NjY2NjEzNy40NTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u044b, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u044b", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u043e\u043a\u043e\u0432\u044b\u0435 \u0441\u0443\u0444\u0444. \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b", "\u0445\u044d\u0448\u0438", "*2800"] | ||
1393E2 | 1393 | E2 | ru | E2. Искорка и древний свиток (усложненная версия) | <div class="problem-statement"><div class="header"><div class="title">E2. Искорка и древний свиток (усложненная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более сложная версия задачи E с большими ограничениями.</span></p><p>Сумеречная Искорка получила новое задание от принцессы Селестии. В этот раз Искорке нужно расшифровать древний свиток, содержащий важные знания о происхождении пони.</p><p>Чтобы скрыть важнейшую информацию от злых глаз, старейшины пони заколдовали свиток. Заклинание вставляет ровно одну букву в любое место каждого словa, к которому оно применено. Чтобы сделать путь к знанию более запутанным, старейшины выбрали некоторые из слов свитка и применили к ним заклинание.</p><p>Сумеречная Искорка знает, что старейшины во всем почитали порядок, поэтому изначально свиток содержал слова в <span class="tex-font-style-bf">лексикографически неубывающем порядке</span>. Искорке нужно удалить по одной букве из некоторых слов в свитке (чтобы отменить заклинание), для того чтобы получить какую-то версию изначального свитка. </p><p>К сожалению, Искорка не всегда может однозначно восстановить древний свиток. Чтобы не упустить важные знания, ей придется перебрать все варианты изначального свитка и найти нужный. Чтобы оценить максимальное время, которое Искорка потратит на работу, ей нужно знать количество вариантов, которые ей нужно перебрать. Она просит вас найти это количество! Так как это количество может быть слишком большим, Искорке достаточно лишь знать его по модулю $$$10^9+7$$$, остальную часть она сможет оценить сама.</p><p>Могло случиться так, что принцесса Селестия отправила неверный свиток, и Искорка не сможет получить никакую версию изначального свитка.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в строке $$$a$$$ находится буква, которая встречается в алфавите раньше, чем соответствующая буква в $$$b$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество слов в свитке. $$$i$$$-я из следующих $$$n$$$ строк содержит строку, состоящую из строчных букв латинского алфавита — $$$i$$$-е слово свитка. Длина каждого слова хотя бы один. Суммарная длина всех слов не превосходит $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество вариантов получить версию оригинала из свитка по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
abcd
zaza
ataka
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
dfs
bfs
sms
mms
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
abc
bcd
a
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
lapochka
kartyshka
bigbabytape
morgenshtern
ssshhhiiittt
queen
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2028
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Заметьте, что старейшины могли написать пустое слово (но тогда они точно применили к нему заклинание, и таким образом это слово теперь имеет длину $$$1$$$).</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="306eb152b15bd9227dbd7304d278e5ea"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E2 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0f8d52ed84281d3834f7537189baefff5a31fe2f"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E2 - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='306eb152b15bd9227dbd7304d278e5ea'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1393%2Fproblem%2FE2%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='306eb152b15bd9227dbd7304d278e5ea'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1393">Codeforces Round 662 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='306eb152b15bd9227dbd7304d278e5ea'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1393/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Суффиксные массивы, деревья и автоматы">
строковые суфф. структуры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы">
хэши
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='306eb152b15bd9227dbd7304d278e5ea'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="693075"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='306eb152b15bd9227dbd7304d278e5ea'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="693075"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81037" title="Codeforces Round #662 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11557:11558" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81161" title="Codeforces Round #662 Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11841:11842" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1393">Задачи</a></li>
<li><a
href="/contest/1393/submit">Отослать</a></li>
<li><a
href="/contest/1393/my">Мои посылки</a></li>
<li><a
href="/contest/1393/status">Статус</a></li>
<li><a
href="/contest/1393/hacks">Взломы</a></li>
<li><a
href="/contest/1393/room/1">Комната</a></li>
<li><a
href="/contest/1393/standings">Положение</a></li>
<li><a
href="/contest/1393/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E2" data-uuid="ps_16c939469e38e0abeb84a8b091b74c1d603e833a">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E2. Искорка и древний свиток (усложненная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более сложная версия задачи E с большими ограничениями.</span></p><p>Сумеречная Искорка получила новое задание от принцессы Селестии. В этот раз Искорке нужно расшифровать древний свиток, содержащий важные знания о происхождении пони.</p><p>Чтобы скрыть важнейшую информацию от злых глаз, старейшины пони заколдовали свиток. Заклинание вставляет ровно одну букву в любое место каждого словa, к которому оно применено. Чтобы сделать путь к знанию более запутанным, старейшины выбрали некоторые из слов свитка и применили к ним заклинание.</p><p>Сумеречная Искорка знает, что старейшины во всем почитали порядок, поэтому изначально свиток содержал слова в <span class="tex-font-style-bf">лексикографически неубывающем порядке</span>. Искорке нужно удалить по одной букве из некоторых слов в свитке (чтобы отменить заклинание), для того чтобы получить какую-то версию изначального свитка. </p><p>К сожалению, Искорка не всегда может однозначно восстановить древний свиток. Чтобы не упустить важные знания, ей придется перебрать все варианты изначального свитка и найти нужный. Чтобы оценить максимальное время, которое Искорка потратит на работу, ей нужно знать количество вариантов, которые ей нужно перебрать. Она просит вас найти это количество! Так как это количество может быть слишком большим, Искорке достаточно лишь знать его по модулю $$$10^9+7$$$, остальную часть она сможет оценить сама.</p><p>Могло случиться так, что принцесса Селестия отправила неверный свиток, и Искорка не сможет получить никакую версию изначального свитка.</p><p>Строка $$$a$$$ лексикографически меньше строки $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в строке $$$a$$$ находится буква, которая встречается в алфавите раньше, чем соответствующая буква в $$$b$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество слов в свитке. $$$i$$$-я из следующих $$$n$$$ строк содержит строку, состоящую из строчных букв латинского алфавита — $$$i$$$-е слово свитка. Длина каждого слова хотя бы один. Суммарная длина всех слов не превосходит $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество вариантов получить версию оригинала из свитка по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
abcd
zaza
ataka
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
dfs
bfs
sms
mms
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
abc
bcd
a
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
lapochka
kartyshka
bigbabytape
morgenshtern
ssshhhiiittt
queen
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2028
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Заметьте, что старейшины могли написать пустое слово (но тогда они точно применили к нему заклинание, и таким образом это слово теперь имеет длину $$$1$$$).</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E2]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:08:58</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8c6ba97169f',t:'MTY5NjY2NjEzOC45MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u044b, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u044b", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u043e\u043a\u043e\u0432\u044b\u0435 \u0441\u0443\u0444\u0444. \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b", "\u0445\u044d\u0448\u0438", "*3200"] | ||
1394A | 1394 | A | ru | A. Boboniu общается с Du | <div class="problem-statement"><div class="header"><div class="title">A. Boboniu общается с Du</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Слышали ли вы когда-нибудь о мессенджере QQ? В групповых чатах QQ администратор может заглушить пользователя на несколько дней.</p><p>В групповом чате Boboniu, есть человек, которого зовут Du Yi, который любит подшучивать над Boboniu каждый день.</p><p>Du будет общаться в чате на протяжении $$$n$$$ дней. В $$$i$$$-й день:</p><ul> <li> Если Du может разговаривать, он подшутит над Boboniu с фактором веселья $$$a_i$$$. Но, после этого, он может быть заглушен, в зависимости от настроения Boboniu. </li><li> Иначе, Du не будет ничего делать. </li></ul><p>Настроение Boboniu это константа $$$m$$$. В $$$i$$$-й день:</p><ul> <li> Если Du может разговаривать и $$$a_i>m$$$, тогда Boboniu разозлится и заглушит его на $$$d$$$ дней, это означает, что Du не сможет говорить в дни $$$i+1, i+2, \cdots, \min(i+d,n)$$$.</li><li> Иначе, Boboniu не будет ничего делать. </li></ul><p>Итоговой фактор веселья это сумма факторов веселья в дни, когда Du мог разговаривать.</p><p>Du попросил вас найти наибольший возможный фактор веселья по всем перестановкам $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$d$$$ и $$$m$$$ ($$$1\le d\le n\le 10^5,0\le m\le 10^9$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \ldots,a_n$$$ ($$$0\le a_i\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: максимальный итоговый фактор веселья по всем перестановкам $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5 2 11
8 10 15 23 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
48
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
195
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вы можете переставить $$$a'=[15, 5, 8, 10, 23]$$$. Тогда история общения Du будет выглядеть следующим образом:</p><ol> <li> Подшутить над Boboniu с фактором веселья $$$15$$$. </li><li> Быть заглушенным. </li><li> Быть заглушенным. </li><li> Подшутить над Boboniu с фактором веселья $$$10$$$. </li><li> Подшутить над Boboniu с фактором веселья $$$23$$$. </li></ol><p>Таким образом, итоговый фактор веселья равен $$$48$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="d27306d83663cede9f678fdedd239cb4"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8c09703a091363235a17cba1bd9c9886c4cb7a65"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='d27306d83663cede9f678fdedd239cb4'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1394%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='d27306d83663cede9f678fdedd239cb4'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1394">Codeforces Round 664 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='d27306d83663cede9f678fdedd239cb4'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1394/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d27306d83663cede9f678fdedd239cb4'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697384"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d27306d83663cede9f678fdedd239cb4'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697384"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11589" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11608" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1394">Задачи</a></li>
<li><a
href="/contest/1394/submit">Отослать</a></li>
<li><a
href="/contest/1394/my">Мои посылки</a></li>
<li><a
href="/contest/1394/status">Статус</a></li>
<li><a
href="/contest/1394/hacks">Взломы</a></li>
<li><a
href="/contest/1394/room/1">Комната</a></li>
<li><a
href="/contest/1394/standings">Положение</a></li>
<li><a
href="/contest/1394/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_85897109015bdbc69808221ad4c2d8eead946b85">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Boboniu общается с Du</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Слышали ли вы когда-нибудь о мессенджере QQ? В групповых чатах QQ администратор может заглушить пользователя на несколько дней.</p><p>В групповом чате Boboniu, есть человек, которого зовут Du Yi, который любит подшучивать над Boboniu каждый день.</p><p>Du будет общаться в чате на протяжении $$$n$$$ дней. В $$$i$$$-й день:</p><ul> <li> Если Du может разговаривать, он подшутит над Boboniu с фактором веселья $$$a_i$$$. Но, после этого, он может быть заглушен, в зависимости от настроения Boboniu. </li><li> Иначе, Du не будет ничего делать. </li></ul><p>Настроение Boboniu это константа $$$m$$$. В $$$i$$$-й день:</p><ul> <li> Если Du может разговаривать и $$$a_i>m$$$, тогда Boboniu разозлится и заглушит его на $$$d$$$ дней, это означает, что Du не сможет говорить в дни $$$i+1, i+2, \cdots, \min(i+d,n)$$$.</li><li> Иначе, Boboniu не будет ничего делать. </li></ul><p>Итоговой фактор веселья это сумма факторов веселья в дни, когда Du мог разговаривать.</p><p>Du попросил вас найти наибольший возможный фактор веселья по всем перестановкам $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$d$$$ и $$$m$$$ ($$$1\le d\le n\le 10^5,0\le m\le 10^9$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \ldots,a_n$$$ ($$$0\le a_i\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: максимальный итоговый фактор веселья по всем перестановкам $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5 2 11
8 10 15 23 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
48
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
195
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вы можете переставить $$$a'=[15, 5, 8, 10, 23]$$$. Тогда история общения Du будет выглядеть следующим образом:</p><ol> <li> Подшутить над Boboniu с фактором веселья $$$15$$$. </li><li> Быть заглушенным. </li><li> Быть заглушенным. </li><li> Подшутить над Boboniu с фактором веселья $$$10$$$. </li><li> Подшутить над Boboniu с фактором веселья $$$23$$$. </li></ol><p>Таким образом, итоговый фактор веселья равен $$$48$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:00</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8d008c89d70',t:'MTY5NjY2NjE0MC4zMjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"] | ||
1394B | 1394 | B | ru | B. Boboniu ходит по графу | <div class="problem-statement"><div class="header"><div class="title">B. Boboniu ходит по графу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Boboniu есть <span class="tex-font-style-bf">ориентированный</span> граф с $$$n$$$ вершинами и $$$m$$$ ребрами.</p><p>Исходящая степень каждой вершины не превосходит $$$k$$$.</p><p>У каждого ребра есть целочисленный вес от $$$1$$$ до $$$m$$$. Никакие два ребра не имеют одинаковый вес.</p><p>Boboniu любит ходить по графу придерживаясь определенных правил, которые задаются последовательностью $$$(c_1,c_2,\ldots,c_k)$$$. Если в текущий момент он стоит в вершине $$$u$$$ с исходящей степени $$$i$$$, тогда после этого он перейдет в вершину по ребру с $$$c_i$$$-м $$$(1\le c_i\le i)$$$ номером в отсортированном по весу порядке среди всех ребер исходящих из $$$u$$$.</p><p>Boboniu попросил вас посчитать число таких последовательностей $$$(c_1,c_2,\ldots,c_k)$$$, что:</p><ul> <li> $$$1\le c_i\le i$$$ для всех $$$i$$$ ($$$1\le i\le k$$$). </li><li> Начав с любой вершины $$$u$$$, возможно вернуться обратно в $$$u$$$ за конечное время передвигаясь по графу по описанным правилам. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$2\le m\le \min(2\cdot 10^5,n(n-1) )$$$, $$$1\le k\le 9$$$).</p><p>Каждая из следующих $$$m$$$ строк содержит три целых числа $$$u$$$, $$$v$$$ и $$$w$$$ $$$(1\le u,v\le n,u\ne v,1\le w\le m)$$$, описывающих ребро из $$$u$$$ в $$$v$$$ с весом $$$w$$$. Гарантируется, что в графе нет петель и кратных ребер, и из каждой вершины исходит хотя бы одно ребро.</p><p>Гарантируется, что исходящая степень каждой вершины не превышает $$$k$$$ и никакие два ребра не имеют одинаковый вес.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: количество последовательностей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть две последовательности: $$$(1,1,3)$$$ и $$$(1,2,3)$$$. Синие ребра обозначают $$$c_i$$$-е по весу ребра, по которым решил ходить Boboniu.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/18b25cb4a2e95553ec2ab4c1a33b3356cec54b53.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Для третьего примера есть только одна последовательность: $$$(1,2,2,2)$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/50f654d1a0fdc5dc0ca33ee1cb93b19c4aaff275.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-it">Исходящая степень</span> вершины $$$u$$$ это количество ребер исходящих из $$$u$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="b41b8dcf03aefed53bf271a6dda73ca4"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8c09703a091363235a17cba1bd9c9886c4cb7a65"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='b41b8dcf03aefed53bf271a6dda73ca4'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1394%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='b41b8dcf03aefed53bf271a6dda73ca4'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1394">Codeforces Round 664 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='b41b8dcf03aefed53bf271a6dda73ca4'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1394/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы">
хэши
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b41b8dcf03aefed53bf271a6dda73ca4'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697385"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b41b8dcf03aefed53bf271a6dda73ca4'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697385"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11589" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11608" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1394">Задачи</a></li>
<li><a
href="/contest/1394/submit">Отослать</a></li>
<li><a
href="/contest/1394/my">Мои посылки</a></li>
<li><a
href="/contest/1394/status">Статус</a></li>
<li><a
href="/contest/1394/hacks">Взломы</a></li>
<li><a
href="/contest/1394/room/1">Комната</a></li>
<li><a
href="/contest/1394/standings">Положение</a></li>
<li><a
href="/contest/1394/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_464057c4532ff63d95297b1bb57d43047501927f">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Boboniu ходит по графу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Boboniu есть <span class="tex-font-style-bf">ориентированный</span> граф с $$$n$$$ вершинами и $$$m$$$ ребрами.</p><p>Исходящая степень каждой вершины не превосходит $$$k$$$.</p><p>У каждого ребра есть целочисленный вес от $$$1$$$ до $$$m$$$. Никакие два ребра не имеют одинаковый вес.</p><p>Boboniu любит ходить по графу придерживаясь определенных правил, которые задаются последовательностью $$$(c_1,c_2,\ldots,c_k)$$$. Если в текущий момент он стоит в вершине $$$u$$$ с исходящей степени $$$i$$$, тогда после этого он перейдет в вершину по ребру с $$$c_i$$$-м $$$(1\le c_i\le i)$$$ номером в отсортированном по весу порядке среди всех ребер исходящих из $$$u$$$.</p><p>Boboniu попросил вас посчитать число таких последовательностей $$$(c_1,c_2,\ldots,c_k)$$$, что:</p><ul> <li> $$$1\le c_i\le i$$$ для всех $$$i$$$ ($$$1\le i\le k$$$). </li><li> Начав с любой вершины $$$u$$$, возможно вернуться обратно в $$$u$$$ за конечное время передвигаясь по графу по описанным правилам. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$2\le m\le \min(2\cdot 10^5,n(n-1) )$$$, $$$1\le k\le 9$$$).</p><p>Каждая из следующих $$$m$$$ строк содержит три целых числа $$$u$$$, $$$v$$$ и $$$w$$$ $$$(1\le u,v\le n,u\ne v,1\le w\le m)$$$, описывающих ребро из $$$u$$$ в $$$v$$$ с весом $$$w$$$. Гарантируется, что в графе нет петель и кратных ребер, и из каждой вершины исходит хотя бы одно ребро.</p><p>Гарантируется, что исходящая степень каждой вершины не превышает $$$k$$$ и никакие два ребра не имеют одинаковый вес.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: количество последовательностей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть две последовательности: $$$(1,1,3)$$$ и $$$(1,2,3)$$$. Синие ребра обозначают $$$c_i$$$-е по весу ребра, по которым решил ходить Boboniu.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/18b25cb4a2e95553ec2ab4c1a33b3356cec54b53.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Для третьего примера есть только одна последовательность: $$$(1,2,2,2)$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/50f654d1a0fdc5dc0ca33ee1cb93b19c4aaff275.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-it">Исходящая степень</span> вершины $$$u$$$ это количество ребер исходящих из $$$u$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:01</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8d8be9d2de2',t:'MTY5NjY2NjE0MS44MTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0445\u044d\u0448\u0438", "*2300"] | ||
1394C | 1394 | C | ru | C. Boboniu и строка | <div class="problem-statement"><div class="header"><div class="title">C. Boboniu и строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu определяет <span class="tex-font-style-it">BN-строку</span> как строку $$$s$$$ из символов 'B' и 'N'.</p><p>Он может совершать следующие операции над BN-строкой $$$s$$$:</p><ul> <li> Удалить один символ из $$$s$$$. </li><li> Удалить подстроку «<span class="tex-font-style-tt">BN</span>» или «<span class="tex-font-style-tt">NB</span>» из $$$s$$$. </li><li> Добавить символ 'B' или 'N' в конец $$$s$$$. </li><li> Добавить строку «<span class="tex-font-style-tt">BN</span>» или «<span class="tex-font-style-tt">NB</span>» в конец $$$s$$$. </li></ul><p>Строка $$$a$$$ является <span class="tex-font-style-it">подстрокой</span> строки $$$b$$$ если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, нуля или всех) символов из начала и нескольких (возможно, нуля или всех) символов из конца.</p><p>Boboniu считает, что BN-строки $$$s$$$ и $$$t$$$ <span class="tex-font-style-it">похожи</span> если и только если:</p><ul> <li> $$$|s|=|t|$$$. </li><li> Существует перестановка $$$p_1, p_2, \ldots, p_{|s|}$$$, что для всех $$$i$$$ ($$$1\le i\le |s|$$$), $$$s_{p_i}=t_i$$$. </li></ul><p>Boboniu также определяет $$$\text{dist}(s,t)$$$, <span class="tex-font-style-it">расстояние</span> между $$$s$$$ и $$$t$$$, как минимальное число операций, необходимое чтобы сделать $$$s$$$ <span class="tex-font-style-it">похожей</span> на $$$t$$$.</p><p>Теперь Boboniu дал вам $$$n$$$ непустых BN-строк $$$s_1,s_2,\ldots, s_n$$$ и просит вас найти <span class="tex-font-style-bf">непустую</span> BN-строку $$$t$$$, что максимальное расстояние до строки из $$$s$$$ минимизировано, т.е. вам нужно минимизировать $$$\max_{i=1}^n \text{dist}(s_i,t)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит слову $$$s_i$$$ ($$$1\le |s_i| \le 5\cdot 10^5$$$). Гарантируется, что $$$s_i$$$ состоит только из 'B' и 'N'. Сумма $$$|s_i|$$$ не превосходит $$$5\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке, выведите минимальное значение $$$\max_{i=1}^n \text{dist}(s_i,t)$$$.</p><p>Во второй строке, выведите подходящее $$$t$$$.</p><p>Если есть несколько возможных $$$t$$$, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
B
N
BN
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
BN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
N
BBBBBB
BNNNBBNBB
NNNNBNBNNBNNNBBN
NBNBN
NNNNNN
BNBNBNBBBBNNNNBBBBNNBBNBNBBNBBBBBBBB
NNNNBN
NBBBBBBBB
NNNNNN
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBBBBBBBBBNNNNNNNNNNNN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
NNN
NNN
BBNNBBBN
NNNBNN
B
NNN
NNNNBNN
NNNNNNNNNNNNNNNBNNNNNNNBNB
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBNNNNNNNNNNNN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
BNNNBNNNNBNBBNNNBBNNNNBBBBNNBBBBBBNBBBBBNBBBNNBBBNBNBBBN
BBBNBBBBNNNNNBBNBBBNNNBB
BBBBBBBBBBBBBBNBBBBBNBBBBBNBBBBNB
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBBBBBBBBBBBBBBBBBBBBBBBNNNNNNNNNNNN
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$\text{dist(B,BN)}=\text{dist(N,BN)}=1$$$, $$$\text{dist(BN,BN)}=0$$$. Таким образом максимальное значение равно $$$1$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="e7665d127d193d1bc08b639586a1f34a"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8c09703a091363235a17cba1bd9c9886c4cb7a65"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='e7665d127d193d1bc08b639586a1f34a'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1394%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='e7665d127d193d1bc08b639586a1f34a'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1394">Codeforces Round 664 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='e7665d127d193d1bc08b639586a1f34a'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1394/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Геометрия">
геометрия
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Тернарный поиск">
тернарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e7665d127d193d1bc08b639586a1f34a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697386"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e7665d127d193d1bc08b639586a1f34a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697386"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11589" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11608" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1394">Задачи</a></li>
<li><a
href="/contest/1394/submit">Отослать</a></li>
<li><a
href="/contest/1394/my">Мои посылки</a></li>
<li><a
href="/contest/1394/status">Статус</a></li>
<li><a
href="/contest/1394/hacks">Взломы</a></li>
<li><a
href="/contest/1394/room/1">Комната</a></li>
<li><a
href="/contest/1394/standings">Положение</a></li>
<li><a
href="/contest/1394/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_d2a3374c1787b1a6aaec73fc68132f675d56bf5c">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Boboniu и строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu определяет <span class="tex-font-style-it">BN-строку</span> как строку $$$s$$$ из символов 'B' и 'N'.</p><p>Он может совершать следующие операции над BN-строкой $$$s$$$:</p><ul> <li> Удалить один символ из $$$s$$$. </li><li> Удалить подстроку «<span class="tex-font-style-tt">BN</span>» или «<span class="tex-font-style-tt">NB</span>» из $$$s$$$. </li><li> Добавить символ 'B' или 'N' в конец $$$s$$$. </li><li> Добавить строку «<span class="tex-font-style-tt">BN</span>» или «<span class="tex-font-style-tt">NB</span>» в конец $$$s$$$. </li></ul><p>Строка $$$a$$$ является <span class="tex-font-style-it">подстрокой</span> строки $$$b$$$ если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, нуля или всех) символов из начала и нескольких (возможно, нуля или всех) символов из конца.</p><p>Boboniu считает, что BN-строки $$$s$$$ и $$$t$$$ <span class="tex-font-style-it">похожи</span> если и только если:</p><ul> <li> $$$|s|=|t|$$$. </li><li> Существует перестановка $$$p_1, p_2, \ldots, p_{|s|}$$$, что для всех $$$i$$$ ($$$1\le i\le |s|$$$), $$$s_{p_i}=t_i$$$. </li></ul><p>Boboniu также определяет $$$\text{dist}(s,t)$$$, <span class="tex-font-style-it">расстояние</span> между $$$s$$$ и $$$t$$$, как минимальное число операций, необходимое чтобы сделать $$$s$$$ <span class="tex-font-style-it">похожей</span> на $$$t$$$.</p><p>Теперь Boboniu дал вам $$$n$$$ непустых BN-строк $$$s_1,s_2,\ldots, s_n$$$ и просит вас найти <span class="tex-font-style-bf">непустую</span> BN-строку $$$t$$$, что максимальное расстояние до строки из $$$s$$$ минимизировано, т.е. вам нужно минимизировать $$$\max_{i=1}^n \text{dist}(s_i,t)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит слову $$$s_i$$$ ($$$1\le |s_i| \le 5\cdot 10^5$$$). Гарантируется, что $$$s_i$$$ состоит только из 'B' и 'N'. Сумма $$$|s_i|$$$ не превосходит $$$5\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке, выведите минимальное значение $$$\max_{i=1}^n \text{dist}(s_i,t)$$$.</p><p>Во второй строке, выведите подходящее $$$t$$$.</p><p>Если есть несколько возможных $$$t$$$, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
B
N
BN
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
BN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
N
BBBBBB
BNNNBBNBB
NNNNBNBNNBNNNBBN
NBNBN
NNNNNN
BNBNBNBBBBNNNNBBBBNNBBNBNBBNBBBBBBBB
NNNNBN
NBBBBBBBB
NNNNNN
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBBBBBBBBBNNNNNNNNNNNN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
NNN
NNN
BBNNBBBN
NNNBNN
B
NNN
NNNNBNN
NNNNNNNNNNNNNNNBNNNNNNNBNB
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBNNNNNNNNNNNN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
BNNNBNNNNBNBBNNNBBNNNNBBBBNNBBBBBBNBBBBBNBBBNNBBBNBNBBBN
BBBNBBBBNNNNNBBNBBBNNNBB
BBBBBBBBBBBBBBNBBBBBNBBBBBNBBBBNB
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBBBBBBBBBBBBBBBBBBBBBBBNNNNNNNNNNNN
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$\text{dist(B,BN)}=\text{dist(N,BN)}=1$$$, $$$\text{dist(BN,BN)}=0$$$. Таким образом максимальное значение равно $$$1$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:03</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8e219d41604',t:'MTY5NjY2NjE0My4xNTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0422\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0442\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "*2600"] | ||
1394D | 1394 | D | ru | D. Boboniu и Jianghu | <div class="problem-statement"><div class="header"><div class="title">D. Boboniu и Jianghu</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>После того как Boboniu закончил строительство своего Jianghu, он занимался кунг-фу на этих горах каждый день.</p><p>Boboniu разработал карту для своих $$$n$$$ гор. Он использовал $$$n-1$$$ дорогу чтобы соединить все $$$n$$$ гор. Все горы связны с помощью дорог.</p><p>Для $$$i$$$-й горы, Boboniu оценил скучность кунг-фу на ней как $$$t_i$$$. Он также оценил высоту каждой горы как $$$h_i$$$.</p><p><span class="tex-font-style-it">Путь</span> это такая последовательность гор $$$M$$$, что для всех $$$i$$$ ($$$1 \le i < |M|$$$), существует дорога между $$$M_i$$$ и $$$M_{i+1}$$$. Boboniu считает <span class="tex-font-style-it">путь</span> <span class="tex-font-style-it">испытанием</span> если для всех $$$i$$$ ($$$1\le i<|M|$$$), $$$h_{M_i}\le h_{M_{i+1}}$$$.</p><p>Boboniu хочет разделить <span class="tex-font-style-bf">все</span> $$$n-1$$$ дорог на несколько <span class="tex-font-style-it">испытаний</span>. Обратите внимание, что каждая дорога должна встречаться <span class="tex-font-style-bf">ровно в одном</span> испытании, но гора может встречаться в нескольких испытаниях. </p><p>Boboniu хочет минимизировать суммарную скучность всех <span class="tex-font-style-it">испытаний</span>. Скучность <span class="tex-font-style-it">испытания</span> $$$M$$$ это сумма скучностей всех гор в ней, т.е. $$$\sum_{i=1}^{|M|}t_{M_i}$$$. </p><p>Он попросил вас найти минимальную возможную суммарную скучность всех испытаний. В награду за вашу работу, вы станете охранником в его Jianghu.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$), обозначающее число гор.</p><p>Во второй строке записано $$$n$$$ целых чисел $$$t_1, t_2, \ldots, t_n$$$ ($$$1 \le t_i \le 10^6$$$), обозначающих скучность исполнения кунг-фу для Boboniu на каждой из гор.</p><p>В третьей строке записаны $$$n$$$ целых чисел $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^6$$$), описывающих высоты всех гор.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит два целых числа $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n, u_i \neq v_i$$$), обозначающих концы дороги. Гарантируется, что все горы связны по дорогам.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: минимальную возможную суммарную скучность всех испытаний.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
40 10 30 50 20
2 3 2 3 1
1 2
1 3
2 4
2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
160
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
1000000 1 1 1 1
1000000 1 1 1 1
1 2
1 3
1 4
1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4000004
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
510916 760492 684704 32545 484888 933975 116895 77095 127679 989957
402815 705067 705067 705067 623759 103335 749243 138306 138306 844737
1 2
3 2
4 3
1 5
6 4
6 7
8 7
8 9
9 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6390572
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a29254cb6f3d8121bb0ba257c8fac4a01509c7ee.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>На картинке, чем светлее точка, тем выше гора, которую она представляет. Одно из лучших разделений это:</p><ul> <li> Испытание $$$1$$$: $$$3 \to 1 \to 2$$$ </li><li> Испытание $$$2$$$: $$$5 \to 2 \to 4$$$ </li></ul><p>Суммарно скучность для Boboniu равна $$$(30 + 40 + 10) + (20 + 10 + 50) = 160$$$. Можно показать, что это является минимальной возможной скучностью.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="2fa6275b4f0216194cedb54e4ec3bcf5"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8c09703a091363235a17cba1bd9c9886c4cb7a65"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='2fa6275b4f0216194cedb54e4ec3bcf5'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1394%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='2fa6275b4f0216194cedb54e4ec3bcf5'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1394">Codeforces Round 664 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='2fa6275b4f0216194cedb54e4ec3bcf5'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1394/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2fa6275b4f0216194cedb54e4ec3bcf5'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697387"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2fa6275b4f0216194cedb54e4ec3bcf5'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697387"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11589" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11608" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1394">Задачи</a></li>
<li><a
href="/contest/1394/submit">Отослать</a></li>
<li><a
href="/contest/1394/my">Мои посылки</a></li>
<li><a
href="/contest/1394/status">Статус</a></li>
<li><a
href="/contest/1394/hacks">Взломы</a></li>
<li><a
href="/contest/1394/room/1">Комната</a></li>
<li><a
href="/contest/1394/standings">Положение</a></li>
<li><a
href="/contest/1394/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_7f396d31e12e88441fe62603a05dfecb84071c09">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Boboniu и Jianghu</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>После того как Boboniu закончил строительство своего Jianghu, он занимался кунг-фу на этих горах каждый день.</p><p>Boboniu разработал карту для своих $$$n$$$ гор. Он использовал $$$n-1$$$ дорогу чтобы соединить все $$$n$$$ гор. Все горы связны с помощью дорог.</p><p>Для $$$i$$$-й горы, Boboniu оценил скучность кунг-фу на ней как $$$t_i$$$. Он также оценил высоту каждой горы как $$$h_i$$$.</p><p><span class="tex-font-style-it">Путь</span> это такая последовательность гор $$$M$$$, что для всех $$$i$$$ ($$$1 \le i < |M|$$$), существует дорога между $$$M_i$$$ и $$$M_{i+1}$$$. Boboniu считает <span class="tex-font-style-it">путь</span> <span class="tex-font-style-it">испытанием</span> если для всех $$$i$$$ ($$$1\le i<|M|$$$), $$$h_{M_i}\le h_{M_{i+1}}$$$.</p><p>Boboniu хочет разделить <span class="tex-font-style-bf">все</span> $$$n-1$$$ дорог на несколько <span class="tex-font-style-it">испытаний</span>. Обратите внимание, что каждая дорога должна встречаться <span class="tex-font-style-bf">ровно в одном</span> испытании, но гора может встречаться в нескольких испытаниях. </p><p>Boboniu хочет минимизировать суммарную скучность всех <span class="tex-font-style-it">испытаний</span>. Скучность <span class="tex-font-style-it">испытания</span> $$$M$$$ это сумма скучностей всех гор в ней, т.е. $$$\sum_{i=1}^{|M|}t_{M_i}$$$. </p><p>Он попросил вас найти минимальную возможную суммарную скучность всех испытаний. В награду за вашу работу, вы станете охранником в его Jianghu.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$), обозначающее число гор.</p><p>Во второй строке записано $$$n$$$ целых чисел $$$t_1, t_2, \ldots, t_n$$$ ($$$1 \le t_i \le 10^6$$$), обозначающих скучность исполнения кунг-фу для Boboniu на каждой из гор.</p><p>В третьей строке записаны $$$n$$$ целых чисел $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^6$$$), описывающих высоты всех гор.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит два целых числа $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n, u_i \neq v_i$$$), обозначающих концы дороги. Гарантируется, что все горы связны по дорогам.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: минимальную возможную суммарную скучность всех испытаний.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
40 10 30 50 20
2 3 2 3 1
1 2
1 3
2 4
2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
160
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
1000000 1 1 1 1
1000000 1 1 1 1
1 2
1 3
1 4
1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4000004
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
510916 760492 684704 32545 484888 933975 116895 77095 127679 989957
402815 705067 705067 705067 623759 103335 749243 138306 138306 844737
1 2
3 2
4 3
1 5
6 4
6 7
8 7
8 9
9 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6390572
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a29254cb6f3d8121bb0ba257c8fac4a01509c7ee.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>На картинке, чем светлее точка, тем выше гора, которую она представляет. Одно из лучших разделений это:</p><ul> <li> Испытание $$$1$$$: $$$3 \to 1 \to 2$$$ </li><li> Испытание $$$2$$$: $$$5 \to 2 \to 4$$$ </li></ul><p>Суммарно скучность для Boboniu равна $$$(30 + 40 + 10) + (20 + 10 + 50) = 160$$$. Можно показать, что это является минимальной возможной скучностью.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:04</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8ea6de31678',t:'MTY5NjY2NjE0NC42NjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2800"] | ||
1394E | 1394 | E | ru | E. Boboniu и коллекция банкнот | <div class="problem-statement"><div class="header"><div class="title">E. Boboniu и коллекция банкнот</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">No matter what trouble you're in, don't be afraid, but face it with a smile.</span></p><p><span class="tex-font-style-it">I've made another billion dollars!</span></p><p><span class="tex-font-style-it"> — Boboniu</span></p><p>Boboniu выпустил свои валюты, под названием Bobo Yuan. Bobo Yuan (BBY) это серия валют. Boboniu присвоил каждой из них положительные целочисленные номера, такие как BBY-1, BBY-2, и так далее.</p><p>У Boboniu есть коллекция BBY. Его коллекция выглядит как последовательность. Например:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cc58eb001fee58dd9838da6f9968c3d16f18575b.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Мы можем использовать последовательность $$$a=[1,2,3,3,2,1,4,4,1]$$$ длины $$$n=9$$$ чтобы описать ее.</p><p>Теперь Boboniu хочет <span class="tex-font-style-it">сложить</span> его коллекцию. Вы можете представить, что Boboniu приклеил свою последовательность на длинный лист бумаги и сгибает его между валютами:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b7784e5ff2cb1e3ba617a45850b2fa12f92ae949.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Boboniu будет складывать вместе только валюты с одинаковым номером. Иначе говоря, если $$$a_i$$$ после сгиба находится над $$$a_j$$$ ($$$1\le i,j\le n$$$), то должно выполняться условие $$$a_i=a_j$$$. Boboniu не волнует, выполнялось ли это условие во время сгиба. Но когда сгиб совершен, это условие должно соблюдаться.</p><p>Формально определение <span class="tex-font-style-it">сгиба</span> описано в примечании.</p><p>Согласно картинке выше, вы можете <span class="tex-font-style-it">согнуть</span> $$$a$$$ два раза. На самом деле, вы можете <span class="tex-font-style-it">согнуть</span> $$$a=[1,2,3,3,2,1,4,4,1]$$$ не более двух раз. Поэтому максимальное число сгибов равно $$$2$$$.</p><p>Как международного фаната Boboniu, вас просят найти наибольшее число сгибов. </p><p>Вам дана последовательность $$$a$$$ длины $$$n$$$, для каждого $$$i$$$ ($$$1\le i\le n$$$), вам нужно найти наибольшее возможное число сгибов последовательности $$$[a_1,a_2,\ldots,a_i]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1\le n\le 10^5$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел. $$$i$$$-е из них должно быть равно максимальному числу сгибов последовательности $$$[a_1,a_2,\ldots,a_i]$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
9
1 2 3 3 2 1 4 4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 0 1 1 1 1 2 2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
9
1 2 2 2 2 1 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 1 2 3 3 4 4 5
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
15
1 2 3 4 5 5 4 3 2 2 3 4 4 3 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 0 0 0 1 1 1 1 2 2 2 3 3 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
50
1 2 4 6 6 4 2 1 3 5 5 3 1 2 4 4 2 1 3 3 1 2 2 1 1 1 2 4 6 6 4 2 1 3 5 5 3 1 2 4 4 2 1 3 3 1 2 2 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6 7 3 3 3 4 4 4 4 3 3 4 4 4 4 4 5 5 5 5 6 6 6 7 7 8
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Формально, для последовательности $$$a$$$ длины $$$n$$$, определим <span class="tex-font-style-it">последовательность сгибов</span> как такую последовательность $$$b$$$ длины $$$n$$$, что:</p><ul> <li> $$$b_i$$$ ($$$1\le i\le n$$$) равно $$$1$$$ или $$$-1$$$. </li><li> Определим $$$p(i)=[b_i=1]+\sum_{j=1}^{i-1}b_j$$$. Для всех $$$1\le i<j\le n$$$, если $$$p(i)=p(j)$$$, то $$$a_i$$$ должно быть равно $$$a_j$$$. </li></ul><p>($$$[A]$$$ это значение логического выражения $$$A$$$. т.е. $$$[A]=1$$$ если $$$A$$$ истинно, иначе $$$[A]=0$$$).</p><p>Определим количество сгибов $$$b$$$ как $$$f(b)=\sum_{i=1}^{n-1}[b_i\ne b_{i+1}]$$$.</p><p>Максимальное количество сгибов $$$a$$$ это $$$F(a)=\max\{ f(b)\mid b \text{ является последовательностью сгибов }a \}$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="0d975a524c5156bce75dea516d96841b"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8c09703a091363235a17cba1bd9c9886c4cb7a65"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='0d975a524c5156bce75dea516d96841b'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1394%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='0d975a524c5156bce75dea516d96841b'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1394">Codeforces Round 664 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='0d975a524c5156bce75dea516d96841b'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1394/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0d975a524c5156bce75dea516d96841b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697388"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0d975a524c5156bce75dea516d96841b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697388"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11589" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11608" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1394">Задачи</a></li>
<li><a
href="/contest/1394/submit">Отослать</a></li>
<li><a
href="/contest/1394/my">Мои посылки</a></li>
<li><a
href="/contest/1394/status">Статус</a></li>
<li><a
href="/contest/1394/hacks">Взломы</a></li>
<li><a
href="/contest/1394/room/1">Комната</a></li>
<li><a
href="/contest/1394/standings">Положение</a></li>
<li><a
href="/contest/1394/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_a1c9019ca8e0926cc964c2968a7c9811914832c7">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Boboniu и коллекция банкнот</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">No matter what trouble you're in, don't be afraid, but face it with a smile.</span></p><p><span class="tex-font-style-it">I've made another billion dollars!</span></p><p><span class="tex-font-style-it"> — Boboniu</span></p><p>Boboniu выпустил свои валюты, под названием Bobo Yuan. Bobo Yuan (BBY) это серия валют. Boboniu присвоил каждой из них положительные целочисленные номера, такие как BBY-1, BBY-2, и так далее.</p><p>У Boboniu есть коллекция BBY. Его коллекция выглядит как последовательность. Например:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cc58eb001fee58dd9838da6f9968c3d16f18575b.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Мы можем использовать последовательность $$$a=[1,2,3,3,2,1,4,4,1]$$$ длины $$$n=9$$$ чтобы описать ее.</p><p>Теперь Boboniu хочет <span class="tex-font-style-it">сложить</span> его коллекцию. Вы можете представить, что Boboniu приклеил свою последовательность на длинный лист бумаги и сгибает его между валютами:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b7784e5ff2cb1e3ba617a45850b2fa12f92ae949.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Boboniu будет складывать вместе только валюты с одинаковым номером. Иначе говоря, если $$$a_i$$$ после сгиба находится над $$$a_j$$$ ($$$1\le i,j\le n$$$), то должно выполняться условие $$$a_i=a_j$$$. Boboniu не волнует, выполнялось ли это условие во время сгиба. Но когда сгиб совершен, это условие должно соблюдаться.</p><p>Формально определение <span class="tex-font-style-it">сгиба</span> описано в примечании.</p><p>Согласно картинке выше, вы можете <span class="tex-font-style-it">согнуть</span> $$$a$$$ два раза. На самом деле, вы можете <span class="tex-font-style-it">согнуть</span> $$$a=[1,2,3,3,2,1,4,4,1]$$$ не более двух раз. Поэтому максимальное число сгибов равно $$$2$$$.</p><p>Как международного фаната Boboniu, вас просят найти наибольшее число сгибов. </p><p>Вам дана последовательность $$$a$$$ длины $$$n$$$, для каждого $$$i$$$ ($$$1\le i\le n$$$), вам нужно найти наибольшее возможное число сгибов последовательности $$$[a_1,a_2,\ldots,a_i]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1\le n\le 10^5$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$1\le a_i\le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел. $$$i$$$-е из них должно быть равно максимальному числу сгибов последовательности $$$[a_1,a_2,\ldots,a_i]$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
9
1 2 3 3 2 1 4 4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 0 1 1 1 1 2 2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
9
1 2 2 2 2 1 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 1 2 3 3 4 4 5
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
15
1 2 3 4 5 5 4 3 2 2 3 4 4 3 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 0 0 0 1 1 1 1 2 2 2 3 3 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
50
1 2 4 6 6 4 2 1 3 5 5 3 1 2 4 4 2 1 3 3 1 2 2 1 1 1 2 4 6 6 4 2 1 3 5 5 3 1 2 4 4 2 1 3 3 1 2 2 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6 7 3 3 3 4 4 4 4 3 3 4 4 4 4 4 5 5 5 5 6 6 6 7 7 8
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Формально, для последовательности $$$a$$$ длины $$$n$$$, определим <span class="tex-font-style-it">последовательность сгибов</span> как такую последовательность $$$b$$$ длины $$$n$$$, что:</p><ul> <li> $$$b_i$$$ ($$$1\le i\le n$$$) равно $$$1$$$ или $$$-1$$$. </li><li> Определим $$$p(i)=[b_i=1]+\sum_{j=1}^{i-1}b_j$$$. Для всех $$$1\le i<j\le n$$$, если $$$p(i)=p(j)$$$, то $$$a_i$$$ должно быть равно $$$a_j$$$. </li></ul><p>($$$[A]$$$ это значение логического выражения $$$A$$$. т.е. $$$[A]=1$$$ если $$$A$$$ истинно, иначе $$$[A]=0$$$).</p><p>Определим количество сгибов $$$b$$$ как $$$f(b)=\sum_{i=1}^{n-1}[b_i\ne b_{i+1}]$$$.</p><p>Максимальное количество сгибов $$$a$$$ это $$$F(a)=\max\{ f(b)\mid b \text{ является последовательностью сгибов }a \}$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:06</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8f3cdf016ec',t:'MTY5NjY2NjE0Ni4wNDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0441\u0442\u0440\u043e\u043a\u0438", "*3500"] | ||
1395A | 1395 | A | ru | A. Boboniu нравится раскрашивать шары | <div class="problem-statement"><div class="header"><div class="title">A. Boboniu нравится раскрашивать шары</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu дал вам</p><ul> <li> $$$r$$$ красных шаров, </li><li> $$$g$$$ зеленых шаров, </li><li> $$$b$$$ синих шаров, </li><li> $$$w$$$ белых шаров. </li></ul><p>Он разрешил вам применять следующую операцию сколько угодно раз: </p><ul> <li> Взять один красный шар, один зеленый шар и один синий шар и заменить цвет каждого из них на белый. </li></ul><p>Вам нужно ответить, возможно ли расположить в ряд все шары, чтобы получить <span class="tex-font-style-it">палиндром</span>, после применения описанной операции несколько (возможно ноль) раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1\le T\le 100$$$), описывающее количество наборов входных данных.</p><p>Для каждого из $$$T$$$ наборов входных данных, в первой строке записаны четыре целых числа $$$r$$$, $$$g$$$, $$$b$$$ и $$$w$$$ ($$$0\le r,g,b,w\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Yes</span>», если возможно расположить в ряд все шары, чтобы получить <span class="tex-font-style-it">палиндром</span>, после применения описанной операции несколько (возможно ноль) раз. Иначе, выведите «<span class="tex-font-style-tt">No</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
0 1 1 1
8 1 9 3
0 0 0 0
1000000000 1000000000 1000000000 1000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
Yes
Yes
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере вы не можете применить ни одной операции, и соответственно расположить все шары в палиндром тоже нельзя.</p><p>Во втором примере после применения одной операции количества шаров поменяются с $$$(8,1,9,3)$$$ на $$$(7,0,8,6)$$$, а далее один из возможных палиндромов может быть таким: «<span class="tex-font-style-tt">rrrwwwbbbbrbbbbwwwrrr</span>».</p><p><span class="tex-font-style-it">Палиндром</span> это слово, фраза, или последовательность которая читается одинаково. Например, «<span class="tex-font-style-tt">rggbwbggr</span>», «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">gg</span>» — палиндромы, а «<span class="tex-font-style-tt">rgbb</span>», «<span class="tex-font-style-tt">gbbgr</span>» — нет.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="0b875b085ba8944c241cf4fe560440c4"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fdd9133615c7e819b2ed22ec268acec8998efdbb"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='0b875b085ba8944c241cf4fe560440c4'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1395%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='0b875b085ba8944c241cf4fe560440c4'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1395">Codeforces Round 664 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='0b875b085ba8944c241cf4fe560440c4'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1395/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1000
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0b875b085ba8944c241cf4fe560440c4'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697389"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0b875b085ba8944c241cf4fe560440c4'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697389"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11590" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11609" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1395">Задачи</a></li>
<li><a
href="/contest/1395/submit">Отослать</a></li>
<li><a
href="/contest/1395/my">Мои посылки</a></li>
<li><a
href="/contest/1395/status">Статус</a></li>
<li><a
href="/contest/1395/hacks">Взломы</a></li>
<li><a
href="/contest/1395/room/1">Комната</a></li>
<li><a
href="/contest/1395/standings">Положение</a></li>
<li><a
href="/contest/1395/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_35cb7660ca62744191b42111b3dd1b3f78a8b067">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Boboniu нравится раскрашивать шары</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu дал вам</p><ul> <li> $$$r$$$ красных шаров, </li><li> $$$g$$$ зеленых шаров, </li><li> $$$b$$$ синих шаров, </li><li> $$$w$$$ белых шаров. </li></ul><p>Он разрешил вам применять следующую операцию сколько угодно раз: </p><ul> <li> Взять один красный шар, один зеленый шар и один синий шар и заменить цвет каждого из них на белый. </li></ul><p>Вам нужно ответить, возможно ли расположить в ряд все шары, чтобы получить <span class="tex-font-style-it">палиндром</span>, после применения описанной операции несколько (возможно ноль) раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1\le T\le 100$$$), описывающее количество наборов входных данных.</p><p>Для каждого из $$$T$$$ наборов входных данных, в первой строке записаны четыре целых числа $$$r$$$, $$$g$$$, $$$b$$$ и $$$w$$$ ($$$0\le r,g,b,w\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Yes</span>», если возможно расположить в ряд все шары, чтобы получить <span class="tex-font-style-it">палиндром</span>, после применения описанной операции несколько (возможно ноль) раз. Иначе, выведите «<span class="tex-font-style-tt">No</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
0 1 1 1
8 1 9 3
0 0 0 0
1000000000 1000000000 1000000000 1000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
Yes
Yes
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере вы не можете применить ни одной операции, и соответственно расположить все шары в палиндром тоже нельзя.</p><p>Во втором примере после применения одной операции количества шаров поменяются с $$$(8,1,9,3)$$$ на $$$(7,0,8,6)$$$, а далее один из возможных палиндромов может быть таким: «<span class="tex-font-style-tt">rrrwwwbbbbrbbbbwwwrrr</span>».</p><p><span class="tex-font-style-it">Палиндром</span> это слово, фраза, или последовательность которая читается одинаково. Например, «<span class="tex-font-style-tt">rggbwbggr</span>», «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">gg</span>» — палиндромы, а «<span class="tex-font-style-tt">rgbb</span>», «<span class="tex-font-style-tt">gbbgr</span>» — нет.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:07</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a8fc7df13a7d',t:'MTY5NjY2NjE0Ny42NTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1000"] | ||
1395B | 1395 | B | ru | B. Boboniu играет в шахматы | <div class="problem-statement"><div class="header"><div class="title">B. Boboniu играет в шахматы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu любит играть в шахматы со своими подчиненными. Как мы знаем, никакой подчиненный не может победить босса в шахматах, поэтому Boboniu никогда не проигрывает.</p><p>Вы проходите собеседование в его компанию. Boboniu решил озадачить вас следующей шахматной задачей:</p><p>Рассмотрим поле $$$n\times m$$$ (строки пронумерованы от $$$1$$$ до $$$n$$$, столцбы пронумерованы от $$$1$$$ до $$$m$$$). У вас есть шахматная фигура которая стоит в клетке $$$(S_x,S_y)$$$, которая исходно находится не на границе поля (т.е. $$$2 \le S_x \le n-1$$$ и $$$2 \le S_y \le m-1$$$).</p><p>Из клетки $$$(x,y)$$$, вы можете подвинуть вашу шахматную фигуру на клетку $$$(x,y')$$$ ($$$1\le y'\le m, y' \neq y$$$) или $$$(x',y)$$$ ($$$1\le x'\le n, x'\neq x$$$). Другими словами, фигура ходит как ладья. Из клетки вы можете перейти в любую клетку на той же строке или столбце.</p><p>Ваша задача — посетить каждую клетку <span class="tex-font-style-bf">ровно один раз</span>. Можете ли вы найти решение?</p><p>Обратите внимание, что клетки на пути между двумя соседними клетками в маршруте не считаются посещенными, и что вам не требуется возвращаться в исходную клетку.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны четыре целых числа $$$n$$$, $$$m$$$, $$$S_x$$$ и $$$S_y$$$ ($$$3\le n,m\le 100$$$, $$$2 \le S_x \le n-1$$$, $$$2 \le S_y \le m-1$$$) — количество строк, столбцов, и исходная позиция фигуры, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$n\cdot m$$$ строк.</p><p>В $$$i$$$-й строке должны быть записаны два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$), обозначающие $$$i$$$-ю посещенную вами клетку. Вы должны вывести ровно $$$nm$$$ пар $$$(x_i, y_i)$$$, это должны быть все возможные пары $$$(x_i, y_i)$$$, что $$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$.</p><p>Можно показать, что в данных ограничениях всегда существует решение. Если есть несколько возможных решений, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 3 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 2
1 2
1 3
2 3
3 3
3 2
3 1
2 1
1 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 4 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 2
2 1
2 3
2 4
1 4
3 4
3 3
3 2
3 1
1 1
1 2
1 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможные маршруты для двух примеров:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/af28ac2dd32473969962b9ede6a9224b524014bb.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="4a7305f1164cf9c89019353603840bc7"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fdd9133615c7e819b2ed22ec268acec8998efdbb"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='4a7305f1164cf9c89019353603840bc7'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1395%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='4a7305f1164cf9c89019353603840bc7'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1395">Codeforces Round 664 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='4a7305f1164cf9c89019353603840bc7'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1395/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1100
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4a7305f1164cf9c89019353603840bc7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697390"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4a7305f1164cf9c89019353603840bc7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697390"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11590" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11609" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1395">Задачи</a></li>
<li><a
href="/contest/1395/submit">Отослать</a></li>
<li><a
href="/contest/1395/my">Мои посылки</a></li>
<li><a
href="/contest/1395/status">Статус</a></li>
<li><a
href="/contest/1395/hacks">Взломы</a></li>
<li><a
href="/contest/1395/room/1">Комната</a></li>
<li><a
href="/contest/1395/standings">Положение</a></li>
<li><a
href="/contest/1395/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_9b1e2b9038a1bb19cf840e73d6d7695617865af4">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Boboniu играет в шахматы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu любит играть в шахматы со своими подчиненными. Как мы знаем, никакой подчиненный не может победить босса в шахматах, поэтому Boboniu никогда не проигрывает.</p><p>Вы проходите собеседование в его компанию. Boboniu решил озадачить вас следующей шахматной задачей:</p><p>Рассмотрим поле $$$n\times m$$$ (строки пронумерованы от $$$1$$$ до $$$n$$$, столцбы пронумерованы от $$$1$$$ до $$$m$$$). У вас есть шахматная фигура которая стоит в клетке $$$(S_x,S_y)$$$, которая исходно находится не на границе поля (т.е. $$$2 \le S_x \le n-1$$$ и $$$2 \le S_y \le m-1$$$).</p><p>Из клетки $$$(x,y)$$$, вы можете подвинуть вашу шахматную фигуру на клетку $$$(x,y')$$$ ($$$1\le y'\le m, y' \neq y$$$) или $$$(x',y)$$$ ($$$1\le x'\le n, x'\neq x$$$). Другими словами, фигура ходит как ладья. Из клетки вы можете перейти в любую клетку на той же строке или столбце.</p><p>Ваша задача — посетить каждую клетку <span class="tex-font-style-bf">ровно один раз</span>. Можете ли вы найти решение?</p><p>Обратите внимание, что клетки на пути между двумя соседними клетками в маршруте не считаются посещенными, и что вам не требуется возвращаться в исходную клетку.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны четыре целых числа $$$n$$$, $$$m$$$, $$$S_x$$$ и $$$S_y$$$ ($$$3\le n,m\le 100$$$, $$$2 \le S_x \le n-1$$$, $$$2 \le S_y \le m-1$$$) — количество строк, столбцов, и исходная позиция фигуры, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести $$$n\cdot m$$$ строк.</p><p>В $$$i$$$-й строке должны быть записаны два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$), обозначающие $$$i$$$-ю посещенную вами клетку. Вы должны вывести ровно $$$nm$$$ пар $$$(x_i, y_i)$$$, это должны быть все возможные пары $$$(x_i, y_i)$$$, что $$$1 \leq x_i \leq n$$$, $$$1 \leq y_i \leq m$$$.</p><p>Можно показать, что в данных ограничениях всегда существует решение. Если есть несколько возможных решений, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 3 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 2
1 2
1 3
2 3
3 3
3 2
3 1
2 1
1 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 4 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 2
2 1
2 3
2 4
1 4
3 4
3 3
3 2
3 1
1 1
1 2
1 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможные маршруты для двух примеров:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/af28ac2dd32473969962b9ede6a9224b524014bb.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:08</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a90688b09d40',t:'MTY5NjY2NjE0OS4wMDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1100"] | ||
1395C | 1395 | C | ru | C. Boboniu и битовые операции | <div class="problem-statement"><div class="header"><div class="title">C. Boboniu и битовые операции</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu нравятся битовые операции, он решил поиграть с вами в игру.</p><p>Boboniu дает вам две последовательности неотрицателных целых чисел $$$a_1,a_2,\ldots,a_n$$$ and $$$b_1,b_2,\ldots,b_m$$$.</p><p>Для каждого $$$i$$$ ($$$1\le i\le n$$$), вам нужно выбрать $$$j$$$ ($$$1\le j\le m$$$) и определить $$$c_i=a_i\& b_j$$$, где $$$\&$$$ обозначает <a href="https://en.wikipedia.org/wiki/Bitwise_operation#AND">операцию побитовое И</a>. Обратите внимание, что вы можете выбрать одинаковые $$$j$$$ для разных $$$i$$$.</p><p>Найдите минимальное возможное $$$c_1 | c_2 | \ldots | c_n$$$, где $$$|$$$ обозначает <a href="https://en.wikipedia.org/wiki/Bitwise_operation#OR">операцию побитовое ИЛИ</a>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1\le n,m\le 200$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i < 2^9$$$).</p><p>В третьей строке записаны $$$m$$$ целых чисел $$$b_1,b_2,\ldots,b_m$$$ ($$$0\le b_i < 2^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: минимальное возможное значение $$$c_1 | c_2 | \ldots | c_n$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2
2 6 4 0
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 6
1 9 1 9 8 1 0
1 1 4 5 1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8 5
179 261 432 162 82 43 10 38
379 357 202 184 197
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
147</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера, рассмотрим $$$c_1=a_1\& b_2=0$$$, $$$c_2=a_2\& b_1=2$$$, $$$c_3=a_3\& b_1=0$$$, $$$c_4 = a_4\& b_1=0$$$. Следовательно, $$$c_1 | c_2 | c_3 |c_4 =2$$$, и это минимальный возможный ответ.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="093d16c781020e62164bc3bf4f0ef225"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fdd9133615c7e819b2ed22ec268acec8998efdbb"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='093d16c781020e62164bc3bf4f0ef225'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1395%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='093d16c781020e62164bc3bf4f0ef225'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1395">Codeforces Round 664 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='093d16c781020e62164bc3bf4f0ef225'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1395/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Битовые маски">
битмаски
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='093d16c781020e62164bc3bf4f0ef225'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697391"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='093d16c781020e62164bc3bf4f0ef225'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697391"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11590" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11609" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1395">Задачи</a></li>
<li><a
href="/contest/1395/submit">Отослать</a></li>
<li><a
href="/contest/1395/my">Мои посылки</a></li>
<li><a
href="/contest/1395/status">Статус</a></li>
<li><a
href="/contest/1395/hacks">Взломы</a></li>
<li><a
href="/contest/1395/room/1">Комната</a></li>
<li><a
href="/contest/1395/standings">Положение</a></li>
<li><a
href="/contest/1395/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_2e230fc1ee826b3e8dfa2a35b5cceeb54d870ff2">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Boboniu и битовые операции</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu нравятся битовые операции, он решил поиграть с вами в игру.</p><p>Boboniu дает вам две последовательности неотрицателных целых чисел $$$a_1,a_2,\ldots,a_n$$$ and $$$b_1,b_2,\ldots,b_m$$$.</p><p>Для каждого $$$i$$$ ($$$1\le i\le n$$$), вам нужно выбрать $$$j$$$ ($$$1\le j\le m$$$) и определить $$$c_i=a_i\& b_j$$$, где $$$\&$$$ обозначает <a href="https://en.wikipedia.org/wiki/Bitwise_operation#AND">операцию побитовое И</a>. Обратите внимание, что вы можете выбрать одинаковые $$$j$$$ для разных $$$i$$$.</p><p>Найдите минимальное возможное $$$c_1 | c_2 | \ldots | c_n$$$, где $$$|$$$ обозначает <a href="https://en.wikipedia.org/wiki/Bitwise_operation#OR">операцию побитовое ИЛИ</a>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1\le n,m\le 200$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i < 2^9$$$).</p><p>В третьей строке записаны $$$m$$$ целых чисел $$$b_1,b_2,\ldots,b_m$$$ ($$$0\le b_i < 2^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: минимальное возможное значение $$$c_1 | c_2 | \ldots | c_n$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2
2 6 4 0
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 6
1 9 1 9 8 1 0
1 1 4 5 1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8 5
179 261 432 162 82 43 10 38
379 357 202 184 197
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
147</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера, рассмотрим $$$c_1=a_1\& b_2=0$$$, $$$c_2=a_2\& b_1=2$$$, $$$c_3=a_3\& b_1=0$$$, $$$c_4 = a_4\& b_1=0$$$. Следовательно, $$$c_1 | c_2 | c_3 |c_4 =2$$$, и это минимальный возможный ответ.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:10</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a90efa2d1628',t:'MTY5NjY2NjE1MC4zNjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1600"] | ||
1395D | 1395 | D | ru | D. Boboniu общается с Du | <div class="problem-statement"><div class="header"><div class="title">D. Boboniu общается с Du</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Слышали ли вы когда-нибудь о мессенджере QQ? В групповых чатах QQ администратор может заглушить пользователя на несколько дней.</p><p>В групповом чате Boboniu, есть человек, которого зовут Du Yi, который любит подшучивать над Boboniu каждый день.</p><p>Du будет общаться в чате на протяжении $$$n$$$ дней. В $$$i$$$-й день:</p><ul> <li> Если Du может разговаривать, он подшутит над Boboniu с фактором веселья $$$a_i$$$. Но, после этого, он может быть заглушен, в зависимости от настроения Boboniu. </li><li> Иначе, Du не будет ничего делать. </li></ul><p>Настроение Boboniu это константа $$$m$$$. В $$$i$$$-й день:</p><ul> <li> Если Du может разговаривать и $$$a_i>m$$$, тогда Boboniu разозлится и заглушит его на $$$d$$$ дней, это означает, что Du не сможет говорить в дни $$$i+1, i+2, \cdots, \min(i+d,n)$$$.</li><li> Иначе, Boboniu не будет ничего делать. </li></ul><p>Итоговой фактор веселья это сумма факторов веселья в дни, когда Du мог разговаривать.</p><p>Du попросил вас найти наибольший возможный фактор веселья по всем перестановкам $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$d$$$ и $$$m$$$ ($$$1\le d\le n\le 10^5,0\le m\le 10^9$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \ldots,a_n$$$ ($$$0\le a_i\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: максимальный итоговый фактор веселья по всем перестановкам $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5 2 11
8 10 15 23 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
48
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
195
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вы можете переставить $$$a'=[15, 5, 8, 10, 23]$$$. Тогда история общения Du будет выглядеть следующим образом:</p><ol> <li> Подшутить над Boboniu с фактором веселья $$$15$$$. </li><li> Быть заглушенным. </li><li> Быть заглушенным. </li><li> Подшутить над Boboniu с фактором веселья $$$10$$$. </li><li> Подшутить над Boboniu с фактором веселья $$$23$$$. </li></ol><p>Таким образом, итоговый фактор веселья равен $$$48$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="b66dc566df8bc861992d4182bde97d1b"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fdd9133615c7e819b2ed22ec268acec8998efdbb"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='b66dc566df8bc861992d4182bde97d1b'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1395%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='b66dc566df8bc861992d4182bde97d1b'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1395">Codeforces Round 664 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='b66dc566df8bc861992d4182bde97d1b'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1395/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b66dc566df8bc861992d4182bde97d1b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697392"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b66dc566df8bc861992d4182bde97d1b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697392"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11590" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11609" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1395">Задачи</a></li>
<li><a
href="/contest/1395/submit">Отослать</a></li>
<li><a
href="/contest/1395/my">Мои посылки</a></li>
<li><a
href="/contest/1395/status">Статус</a></li>
<li><a
href="/contest/1395/hacks">Взломы</a></li>
<li><a
href="/contest/1395/room/1">Комната</a></li>
<li><a
href="/contest/1395/standings">Положение</a></li>
<li><a
href="/contest/1395/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_09faf7fbf801d4b5d272fe2b4c6ca62e5fd9ee80">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Boboniu общается с Du</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Слышали ли вы когда-нибудь о мессенджере QQ? В групповых чатах QQ администратор может заглушить пользователя на несколько дней.</p><p>В групповом чате Boboniu, есть человек, которого зовут Du Yi, который любит подшучивать над Boboniu каждый день.</p><p>Du будет общаться в чате на протяжении $$$n$$$ дней. В $$$i$$$-й день:</p><ul> <li> Если Du может разговаривать, он подшутит над Boboniu с фактором веселья $$$a_i$$$. Но, после этого, он может быть заглушен, в зависимости от настроения Boboniu. </li><li> Иначе, Du не будет ничего делать. </li></ul><p>Настроение Boboniu это константа $$$m$$$. В $$$i$$$-й день:</p><ul> <li> Если Du может разговаривать и $$$a_i>m$$$, тогда Boboniu разозлится и заглушит его на $$$d$$$ дней, это означает, что Du не сможет говорить в дни $$$i+1, i+2, \cdots, \min(i+d,n)$$$.</li><li> Иначе, Boboniu не будет ничего делать. </li></ul><p>Итоговой фактор веселья это сумма факторов веселья в дни, когда Du мог разговаривать.</p><p>Du попросил вас найти наибольший возможный фактор веселья по всем перестановкам $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$d$$$ и $$$m$$$ ($$$1\le d\le n\le 10^5,0\le m\le 10^9$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \ldots,a_n$$$ ($$$0\le a_i\le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: максимальный итоговый фактор веселья по всем перестановкам $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5 2 11
8 10 15 23 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
48
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
20 2 16
20 5 8 2 18 16 2 16 16 1 5 16 2 13 6 16 4 17 21 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
195
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, вы можете переставить $$$a'=[15, 5, 8, 10, 23]$$$. Тогда история общения Du будет выглядеть следующим образом:</p><ol> <li> Подшутить над Boboniu с фактором веселья $$$15$$$. </li><li> Быть заглушенным. </li><li> Быть заглушенным. </li><li> Подшутить над Boboniu с фактором веселья $$$10$$$. </li><li> Подшутить над Boboniu с фактором веселья $$$23$$$. </li></ol><p>Таким образом, итоговый фактор веселья равен $$$48$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:11</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9176d8b13b4',t:'MTY5NjY2NjE1MS42ODYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"] | ||
1395E | 1395 | E | ru | E. Boboniu ходит по графу | <div class="problem-statement"><div class="header"><div class="title">E. Boboniu ходит по графу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Boboniu есть <span class="tex-font-style-bf">ориентированный</span> граф с $$$n$$$ вершинами и $$$m$$$ ребрами.</p><p>Исходящая степень каждой вершины не превосходит $$$k$$$.</p><p>У каждого ребра есть целочисленный вес от $$$1$$$ до $$$m$$$. Никакие два ребра не имеют одинаковый вес.</p><p>Boboniu любит ходить по графу придерживаясь определенных правил, которые задаются последовательностью $$$(c_1,c_2,\ldots,c_k)$$$. Если в текущий момент он стоит в вершине $$$u$$$ с исходящей степени $$$i$$$, тогда после этого он перейдет в вершину по ребру с $$$c_i$$$-м $$$(1\le c_i\le i)$$$ номером в отсортированном по весу порядке среди всех ребер исходящих из $$$u$$$.</p><p>Boboniu попросил вас посчитать число таких последовательностей $$$(c_1,c_2,\ldots,c_k)$$$, что:</p><ul> <li> $$$1\le c_i\le i$$$ для всех $$$i$$$ ($$$1\le i\le k$$$). </li><li> Начав с любой вершины $$$u$$$, возможно вернуться обратно в $$$u$$$ за конечное время передвигаясь по графу по описанным правилам. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$2\le m\le \min(2\cdot 10^5,n(n-1) )$$$, $$$1\le k\le 9$$$).</p><p>Каждая из следующих $$$m$$$ строк содержит три целых числа $$$u$$$, $$$v$$$ и $$$w$$$ $$$(1\le u,v\le n,u\ne v,1\le w\le m)$$$, описывающих ребро из $$$u$$$ в $$$v$$$ с весом $$$w$$$. Гарантируется, что в графе нет петель и кратных ребер, и из каждой вершины исходит хотя бы одно ребро.</p><p>Гарантируется, что исходящая степень каждой вершины не превышает $$$k$$$ и никакие два ребра не имеют одинаковый вес.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: количество последовательностей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть две последовательности: $$$(1,1,3)$$$ и $$$(1,2,3)$$$. Синие ребра обозначают $$$c_i$$$-е по весу ребра, по которым решил ходить Boboniu.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/18b25cb4a2e95553ec2ab4c1a33b3356cec54b53.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Для третьего примера есть только одна последовательность: $$$(1,2,2,2)$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/50f654d1a0fdc5dc0ca33ee1cb93b19c4aaff275.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-it">Исходящая степень</span> вершины $$$u$$$ это количество ребер исходящих из $$$u$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="2c92c16b7ba096d496851c4536936002"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fdd9133615c7e819b2ed22ec268acec8998efdbb"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='2c92c16b7ba096d496851c4536936002'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1395%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='2c92c16b7ba096d496851c4536936002'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1395">Codeforces Round 664 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='2c92c16b7ba096d496851c4536936002'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1395/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы">
хэши
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2c92c16b7ba096d496851c4536936002'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697393"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2c92c16b7ba096d496851c4536936002'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697393"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11590" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11609" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1395">Задачи</a></li>
<li><a
href="/contest/1395/submit">Отослать</a></li>
<li><a
href="/contest/1395/my">Мои посылки</a></li>
<li><a
href="/contest/1395/status">Статус</a></li>
<li><a
href="/contest/1395/hacks">Взломы</a></li>
<li><a
href="/contest/1395/room/1">Комната</a></li>
<li><a
href="/contest/1395/standings">Положение</a></li>
<li><a
href="/contest/1395/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_7006f8aa4ad3e480265076fd08af6b9fcb1c109a">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Boboniu ходит по графу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Boboniu есть <span class="tex-font-style-bf">ориентированный</span> граф с $$$n$$$ вершинами и $$$m$$$ ребрами.</p><p>Исходящая степень каждой вершины не превосходит $$$k$$$.</p><p>У каждого ребра есть целочисленный вес от $$$1$$$ до $$$m$$$. Никакие два ребра не имеют одинаковый вес.</p><p>Boboniu любит ходить по графу придерживаясь определенных правил, которые задаются последовательностью $$$(c_1,c_2,\ldots,c_k)$$$. Если в текущий момент он стоит в вершине $$$u$$$ с исходящей степени $$$i$$$, тогда после этого он перейдет в вершину по ребру с $$$c_i$$$-м $$$(1\le c_i\le i)$$$ номером в отсортированном по весу порядке среди всех ребер исходящих из $$$u$$$.</p><p>Boboniu попросил вас посчитать число таких последовательностей $$$(c_1,c_2,\ldots,c_k)$$$, что:</p><ul> <li> $$$1\le c_i\le i$$$ для всех $$$i$$$ ($$$1\le i\le k$$$). </li><li> Начав с любой вершины $$$u$$$, возможно вернуться обратно в $$$u$$$ за конечное время передвигаясь по графу по описанным правилам. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$2\le m\le \min(2\cdot 10^5,n(n-1) )$$$, $$$1\le k\le 9$$$).</p><p>Каждая из следующих $$$m$$$ строк содержит три целых числа $$$u$$$, $$$v$$$ и $$$w$$$ $$$(1\le u,v\le n,u\ne v,1\le w\le m)$$$, описывающих ребро из $$$u$$$ в $$$v$$$ с весом $$$w$$$. Гарантируется, что в графе нет петель и кратных ребер, и из каждой вершины исходит хотя бы одно ребро.</p><p>Гарантируется, что исходящая степень каждой вершины не превышает $$$k$$$ и никакие два ребра не имеют одинаковый вес.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число: количество последовательностей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 6 3
4 2 1
1 2 2
2 4 3
4 1 4
4 3 5
3 1 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5 1
1 4 1
5 1 2
2 5 3
4 3 4
3 2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 13 4
3 5 1
2 5 2
6 3 3
1 4 4
2 6 5
5 3 6
4 1 7
4 3 8
5 2 9
4 2 10
2 1 11
6 1 12
4 6 13
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть две последовательности: $$$(1,1,3)$$$ и $$$(1,2,3)$$$. Синие ребра обозначают $$$c_i$$$-е по весу ребра, по которым решил ходить Boboniu.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/18b25cb4a2e95553ec2ab4c1a33b3356cec54b53.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Для третьего примера есть только одна последовательность: $$$(1,2,2,2)$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/50f654d1a0fdc5dc0ca33ee1cb93b19c4aaff275.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-it">Исходящая степень</span> вершины $$$u$$$ это количество ребер исходящих из $$$u$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:12</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a91f9f3c3aad',t:'MTY5NjY2NjE1My4wMDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0445\u044d\u0448\u0438", "*2300"] | ||
1395F | 1395 | F | ru | F. Boboniu и строка | <div class="problem-statement"><div class="header"><div class="title">F. Boboniu и строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu определяет <span class="tex-font-style-it">BN-строку</span> как строку $$$s$$$ из символов 'B' и 'N'.</p><p>Он может совершать следующие операции над BN-строкой $$$s$$$:</p><ul> <li> Удалить один символ из $$$s$$$. </li><li> Удалить подстроку «<span class="tex-font-style-tt">BN</span>» или «<span class="tex-font-style-tt">NB</span>» из $$$s$$$. </li><li> Добавить символ 'B' или 'N' в конец $$$s$$$. </li><li> Добавить строку «<span class="tex-font-style-tt">BN</span>» или «<span class="tex-font-style-tt">NB</span>» в конец $$$s$$$. </li></ul><p>Строка $$$a$$$ является <span class="tex-font-style-it">подстрокой</span> строки $$$b$$$ если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, нуля или всех) символов из начала и нескольких (возможно, нуля или всех) символов из конца.</p><p>Boboniu считает, что BN-строки $$$s$$$ и $$$t$$$ <span class="tex-font-style-it">похожи</span> если и только если:</p><ul> <li> $$$|s|=|t|$$$. </li><li> Существует перестановка $$$p_1, p_2, \ldots, p_{|s|}$$$, что для всех $$$i$$$ ($$$1\le i\le |s|$$$), $$$s_{p_i}=t_i$$$. </li></ul><p>Boboniu также определяет $$$\text{dist}(s,t)$$$, <span class="tex-font-style-it">расстояние</span> между $$$s$$$ и $$$t$$$, как минимальное число операций, необходимое чтобы сделать $$$s$$$ <span class="tex-font-style-it">похожей</span> на $$$t$$$.</p><p>Теперь Boboniu дал вам $$$n$$$ непустых BN-строк $$$s_1,s_2,\ldots, s_n$$$ и просит вас найти <span class="tex-font-style-bf">непустую</span> BN-строку $$$t$$$, что максимальное расстояние до строки из $$$s$$$ минимизировано, т.е. вам нужно минимизировать $$$\max_{i=1}^n \text{dist}(s_i,t)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит слову $$$s_i$$$ ($$$1\le |s_i| \le 5\cdot 10^5$$$). Гарантируется, что $$$s_i$$$ состоит только из 'B' и 'N'. Сумма $$$|s_i|$$$ не превосходит $$$5\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке, выведите минимальное значение $$$\max_{i=1}^n \text{dist}(s_i,t)$$$.</p><p>Во второй строке, выведите подходящее $$$t$$$.</p><p>Если есть несколько возможных $$$t$$$, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
B
N
BN
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
BN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
N
BBBBBB
BNNNBBNBB
NNNNBNBNNBNNNBBN
NBNBN
NNNNNN
BNBNBNBBBBNNNNBBBBNNBBNBNBBNBBBBBBBB
NNNNBN
NBBBBBBBB
NNNNNN
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBBBBBBBBBNNNNNNNNNNNN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
NNN
NNN
BBNNBBBN
NNNBNN
B
NNN
NNNNBNN
NNNNNNNNNNNNNNNBNNNNNNNBNB
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBNNNNNNNNNNNN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
BNNNBNNNNBNBBNNNBBNNNNBBBBNNBBBBBBNBBBBBNBBBNNBBBNBNBBBN
BBBNBBBBNNNNNBBNBBBNNNBB
BBBBBBBBBBBBBBNBBBBBNBBBBBNBBBBNB
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBBBBBBBBBBBBBBBBBBBBBBBNNNNNNNNNNNN
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$\text{dist(B,BN)}=\text{dist(N,BN)}=1$$$, $$$\text{dist(BN,BN)}=0$$$. Таким образом максимальное значение равно $$$1$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="e556c1e268d8727038da33d1df929e04"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - F - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fdd9133615c7e819b2ed22ec268acec8998efdbb"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='e556c1e268d8727038da33d1df929e04'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1395%2Fproblem%2FF%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='e556c1e268d8727038da33d1df929e04'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1395">Codeforces Round 664 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='e556c1e268d8727038da33d1df929e04'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1395/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Геометрия">
геометрия
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e556c1e268d8727038da33d1df929e04'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="697394"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e556c1e268d8727038da33d1df929e04'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="697394"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81319" title="Codeforces Round #664" target="_blank">Codeforces Round #664 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11590" resourceName="Codeforces Round #664"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81355" title="Codeforces Round #664 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11609" resourceName="Codeforces Round #664 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1395">Задачи</a></li>
<li><a
href="/contest/1395/submit">Отослать</a></li>
<li><a
href="/contest/1395/my">Мои посылки</a></li>
<li><a
href="/contest/1395/status">Статус</a></li>
<li><a
href="/contest/1395/hacks">Взломы</a></li>
<li><a
href="/contest/1395/room/1">Комната</a></li>
<li><a
href="/contest/1395/standings">Положение</a></li>
<li><a
href="/contest/1395/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="F" data-uuid="ps_bd68a5d757671782cb4b866900a2e5005cd9c97a">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Boboniu и строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Boboniu определяет <span class="tex-font-style-it">BN-строку</span> как строку $$$s$$$ из символов 'B' и 'N'.</p><p>Он может совершать следующие операции над BN-строкой $$$s$$$:</p><ul> <li> Удалить один символ из $$$s$$$. </li><li> Удалить подстроку «<span class="tex-font-style-tt">BN</span>» или «<span class="tex-font-style-tt">NB</span>» из $$$s$$$. </li><li> Добавить символ 'B' или 'N' в конец $$$s$$$. </li><li> Добавить строку «<span class="tex-font-style-tt">BN</span>» или «<span class="tex-font-style-tt">NB</span>» в конец $$$s$$$. </li></ul><p>Строка $$$a$$$ является <span class="tex-font-style-it">подстрокой</span> строки $$$b$$$ если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, нуля или всех) символов из начала и нескольких (возможно, нуля или всех) символов из конца.</p><p>Boboniu считает, что BN-строки $$$s$$$ и $$$t$$$ <span class="tex-font-style-it">похожи</span> если и только если:</p><ul> <li> $$$|s|=|t|$$$. </li><li> Существует перестановка $$$p_1, p_2, \ldots, p_{|s|}$$$, что для всех $$$i$$$ ($$$1\le i\le |s|$$$), $$$s_{p_i}=t_i$$$. </li></ul><p>Boboniu также определяет $$$\text{dist}(s,t)$$$, <span class="tex-font-style-it">расстояние</span> между $$$s$$$ и $$$t$$$, как минимальное число операций, необходимое чтобы сделать $$$s$$$ <span class="tex-font-style-it">похожей</span> на $$$t$$$.</p><p>Теперь Boboniu дал вам $$$n$$$ непустых BN-строк $$$s_1,s_2,\ldots, s_n$$$ и просит вас найти <span class="tex-font-style-bf">непустую</span> BN-строку $$$t$$$, что максимальное расстояние до строки из $$$s$$$ минимизировано, т.е. вам нужно минимизировать $$$\max_{i=1}^n \text{dist}(s_i,t)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1\le n\le 3\cdot 10^5$$$).</p><p>Каждая из следующих $$$n$$$ строк содержит слову $$$s_i$$$ ($$$1\le |s_i| \le 5\cdot 10^5$$$). Гарантируется, что $$$s_i$$$ состоит только из 'B' и 'N'. Сумма $$$|s_i|$$$ не превосходит $$$5\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке, выведите минимальное значение $$$\max_{i=1}^n \text{dist}(s_i,t)$$$.</p><p>Во второй строке, выведите подходящее $$$t$$$.</p><p>Если есть несколько возможных $$$t$$$, вы можете вывести любое.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
B
N
BN
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
BN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
N
BBBBBB
BNNNBBNBB
NNNNBNBNNBNNNBBN
NBNBN
NNNNNN
BNBNBNBBBBNNNNBBBBNNBBNBNBBNBBBBBBBB
NNNNBN
NBBBBBBBB
NNNNNN
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBBBBBBBBBNNNNNNNNNNNN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
NNN
NNN
BBNNBBBN
NNNBNN
B
NNN
NNNNBNN
NNNNNNNNNNNNNNNBNNNNNNNBNB
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBNNNNNNNNNNNN
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
BNNNBNNNNBNBBNNNBBNNNNBBBBNNBBBBBBNBBBBBNBBBNNBBBNBNBBBN
BBBNBBBBNNNNNBBNBBBNNNBB
BBBBBBBBBBBBBBNBBBBBNBBBBBNBBBBNB
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
BBBBBBBBBBBBBBBBBBBBBBBBBBNNNNNNNNNNNN
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$\text{dist(B,BN)}=\text{dist(N,BN)}=1$$$, $$$\text{dist(BN,BN)}=0$$$. Таким образом максимальное значение равно $$$1$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:14</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a927fbd49dae',t:'MTY5NjY2NjE1NC4zMTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*2600"] | ||
1396A | 1396 | A | ru | A. Кратные длине | <div class="problem-statement"><div class="header"><div class="title">A. Кратные длине</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел.</p><p>Вы хотите сделать все элементы $$$a$$$ равными нулю, применив следующую операцию <span class="tex-font-style-bf">ровно три</span> раза:</p><ul> <li> Выберите отрезок, к каждому числу на этом отрезке добавьте число кратное $$$len$$$, где $$$len$$$ это длина этого отрезка (добавленные числа могут быть разными). </li></ul><p>Можно доказать, что таким образом всегда можно превратить все элементы $$$a$$$ в нули.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 100\,000$$$): количество элементов массиве.</p><p>Во второй строке записаны $$$n$$$ элементов массива $$$a$$$, разделенные пробелами: $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите шесть строк, описывающих три операции.</p><p>Для каждой операции, выведите две строки:</p><ul><p> </p><li> В первой строке выведите два числа $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n$$$): границы выбранного отрезка.<p> </p></li><li> Во второй строке выведите $$$r-l+1$$$ целых чисел $$$b_l, b_{l+1}, \dots, b_r$$$ ($$$-10^{18} \le b_i \le 10^{18}$$$): числа, которые нужно прибавить к $$$a_l, a_{l+1}, \ldots, a_r$$$, соответственно; $$$b_i$$$ должно делиться на $$$r - l + 1$$$.</li></ul> </div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 3 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 1
-1
3 4
4 2
2 4
-3 -6 -6</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="9c9151b1d66bd925ea52d5531d0fcc7b"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="ba1f88c3587bbb20752b89168959853f472e1c01"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='9c9151b1d66bd925ea52d5531d0fcc7b'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1396%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='9c9151b1d66bd925ea52d5531d0fcc7b'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1396">Codeforces Round 666 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='9c9151b1d66bd925ea52d5531d0fcc7b'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1396/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9c9151b1d66bd925ea52d5531d0fcc7b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712374"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9c9151b1d66bd925ea52d5531d0fcc7b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712374"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11780" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11827" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1396">Задачи</a></li>
<li><a
href="/contest/1396/submit">Отослать</a></li>
<li><a
href="/contest/1396/my">Мои посылки</a></li>
<li><a
href="/contest/1396/status">Статус</a></li>
<li><a
href="/contest/1396/hacks">Взломы</a></li>
<li><a
href="/contest/1396/room/1">Комната</a></li>
<li><a
href="/contest/1396/standings">Положение</a></li>
<li><a
href="/contest/1396/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_d175ed003edfca40d2b32e4eca70ef38e0111db2">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Кратные длине</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел.</p><p>Вы хотите сделать все элементы $$$a$$$ равными нулю, применив следующую операцию <span class="tex-font-style-bf">ровно три</span> раза:</p><ul> <li> Выберите отрезок, к каждому числу на этом отрезке добавьте число кратное $$$len$$$, где $$$len$$$ это длина этого отрезка (добавленные числа могут быть разными). </li></ul><p>Можно доказать, что таким образом всегда можно превратить все элементы $$$a$$$ в нули.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 100\,000$$$): количество элементов массиве.</p><p>Во второй строке записаны $$$n$$$ элементов массива $$$a$$$, разделенные пробелами: $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите шесть строк, описывающих три операции.</p><p>Для каждой операции, выведите две строки:</p><ul><p> </p><li> В первой строке выведите два числа $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n$$$): границы выбранного отрезка.<p> </p></li><li> Во второй строке выведите $$$r-l+1$$$ целых чисел $$$b_l, b_{l+1}, \dots, b_r$$$ ($$$-10^{18} \le b_i \le 10^{18}$$$): числа, которые нужно прибавить к $$$a_l, a_{l+1}, \ldots, a_r$$$, соответственно; $$$b_i$$$ должно делиться на $$$r - l + 1$$$.</li></ul> </div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 3 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 1
-1
3 4
4 2
2 4
-3 -6 -6</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:16</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a930b9791672',t:'MTY5NjY2NjE1Ni4yMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"] | ||
1396B | 1396 | B | ru | B. Каменная игра | <div class="problem-statement"><div class="header"><div class="title">B. Каменная игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>T играет в игру со своим другом HL.</p><p>Есть $$$n$$$ кучек с камнями, в $$$i$$$-й из них исходно содержится $$$a_i$$$ камней. </p><p>T и HL будут ходить чередуясь, и T ходит первым. В каждом ходу, игрок выбирает непустую кучу и удаляет из нее один камень. Однако, нельзя выбирать кучку, которая была выбрана на прошлом ходу (кучку которая была выбрана другим игроком, или если текущий ход это первый ход первого игрока, то можно выбрать любую кучу). Игрок, который не может выбрать кучу на своем ходу, проигрывает.</p><p>Считая, что оба игрока играют оптимально, для заданных стартовых конфигураций $$$t$$$ игр, определите победителя.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ $$$(1 \le t \le 100)$$$ — количество игр. Далее следуют описания игр, описание каждой игры состоит из двух строк:</p><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 100)$$$ — количество куч.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 100)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой игры, выведите в отдельной строке имя победителя, «<span class="tex-font-style-tt">T</span>» или «<span class="tex-font-style-tt">HL</span>» (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1
2
2
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
T
HL
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первой игре, T убирает один камень из единственной кучи. После этого, несмотря на то, что в куче еще остался $$$1$$$ камень, HL не можем сходить, из-за того что T использовал эту кучу на прошлом ходу. Таким образом, T побеждает.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="3580fdb4d22f577a989563c2c72376c7"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="ba1f88c3587bbb20752b89168959853f472e1c01"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='3580fdb4d22f577a989563c2c72376c7'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1396%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='3580fdb4d22f577a989563c2c72376c7'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1396">Codeforces Round 666 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='3580fdb4d22f577a989563c2c72376c7'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1396/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди">
игры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3580fdb4d22f577a989563c2c72376c7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712375"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3580fdb4d22f577a989563c2c72376c7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712375"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11780" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11827" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1396">Задачи</a></li>
<li><a
href="/contest/1396/submit">Отослать</a></li>
<li><a
href="/contest/1396/my">Мои посылки</a></li>
<li><a
href="/contest/1396/status">Статус</a></li>
<li><a
href="/contest/1396/hacks">Взломы</a></li>
<li><a
href="/contest/1396/room/1">Комната</a></li>
<li><a
href="/contest/1396/standings">Положение</a></li>
<li><a
href="/contest/1396/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_ab5f87b22b60231e04b7e24770740d52c3bbd41b">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Каменная игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>T играет в игру со своим другом HL.</p><p>Есть $$$n$$$ кучек с камнями, в $$$i$$$-й из них исходно содержится $$$a_i$$$ камней. </p><p>T и HL будут ходить чередуясь, и T ходит первым. В каждом ходу, игрок выбирает непустую кучу и удаляет из нее один камень. Однако, нельзя выбирать кучку, которая была выбрана на прошлом ходу (кучку которая была выбрана другим игроком, или если текущий ход это первый ход первого игрока, то можно выбрать любую кучу). Игрок, который не может выбрать кучу на своем ходу, проигрывает.</p><p>Считая, что оба игрока играют оптимально, для заданных стартовых конфигураций $$$t$$$ игр, определите победителя.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ $$$(1 \le t \le 100)$$$ — количество игр. Далее следуют описания игр, описание каждой игры состоит из двух строк:</p><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 100)$$$ — количество куч.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 100)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой игры, выведите в отдельной строке имя победителя, «<span class="tex-font-style-tt">T</span>» или «<span class="tex-font-style-tt">HL</span>» (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1
2
2
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
T
HL
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первой игре, T убирает один камень из единственной кучи. После этого, несмотря на то, что в куче еще остался $$$1$$$ камень, HL не можем сходить, из-за того что T использовал эту кучу на прошлом ходу. Таким образом, T побеждает.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:17</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a93c3b6915f6',t:'MTY5NjY2NjE1Ny43NzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u0433\u0440\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1800"] | ||
1396C | 1396 | C | ru | C. Monster Invaders | <div class="problem-statement"><div class="header"><div class="title">C. Monster Invaders</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ziota нашел игру, которая назыается «Monster Invaders».</p><p>Аналогично другим RPG стрелялкам, в «Monster Invaders» требуется уничтожать монстров и боссов с помощью оружия.</p><p>Для простоты, мы рассмотрим только два вида монстров и три вида оружия.</p><p>А именно, два вида монстров это: </p><ul> <li> обычный монстр с $$$1$$$ hp. </li><li> босс с $$$2$$$ hp. </li></ul><p>И три вида оружия: </p><ul> <li> Пистолет, наносит $$$1$$$ hp урона одному монстру, время перезарядки равно $$$r_1$$$ </li><li> Лазерная пушка, наносит $$$1$$$ hp урона всем монстрам в данном уровне (включая босса), время перезарядки равно $$$r_2$$$ </li><li> AWP, мгновенно убивает любого монстра, время перезарядки равно $$$r_3$$$ </li></ul><p><span class="tex-font-style-bf">Исходно оружия незаряжены, и Ziota не может перезаряжать несколько оружий одновременно.</span></p><p>Этапы в игре могут быть описаны массивом $$$a_1, a_2, \ldots, a_n$$$, в котором <span class="tex-font-style-bf">$$$i$$$-й этап содержит $$$a_i$$$ обычных монстров и одного босса</span>. Из-за натуры игры, <span class="tex-font-style-bf">Ziota не может использовать пистолет (оружие первого типа) или AWP (оружие третьего типа) чтобы выстрелить в босса, до того как будут убиты все $$$a_i$$$ обычных монстров</span>.</p><p>Если Ziota ранит босса, но не убивает его полностью, <span class="tex-font-style-bf">он обязан уйти с текущего этапа на любой соседний этап</span> (соседние к этапу $$$i$$$ $$$(1 < i < n)$$$ это этапы $$$i - 1$$$ и $$$i + 1$$$, единственный сосед этапа $$$1$$$ это этап $$$2$$$, единственный этап соседний к этапу $$$n$$$ это $$$n - 1$$$). Ziota также может уйти в любом соседний уровень в любой момент времени. <span class="tex-font-style-bf">Каждый переход между соседними уровнями выполняется с помощью портала, с временем телепортации $$$d$$$.</span></p><p>Чтобы не повредить пространственно-временной континуум внутри игры, <span class="tex-font-style-bf">запрещено перезаряжаться или стрелять в монстров во время телепортации. </span></p><p>Ziota начинает игру на этапе 1. Его задача довольно проста, убить всех монстров на всех этапах. Он хочет узнать минимальное время, которое ему нужно, чтобы этого добиться (вы можете считать, что выстрел в монстров происходит мгновенно и у него есть бесконечное количество патронов для каждого оружия). Пожалуйста, помогите ему найти это значение.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны пять целых чисел, разделенных пробелами: $$$n$$$ $$$(2 \le n \le 10^6)$$$ — количество этапов, $$$r_1, r_2, r_3$$$ $$$(1 \le r_1 \le r_2 \le r_3 \le 10^9)$$$ — времена перезарядки трех оружий, $$$d$$$ $$$(1 \le d \le 10^9)$$$ — время перехода между соседними уровнями.</p><p>Во второй строке записаны $$$n$$$ разделенных пробелами целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6, 1 \le i \le n)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, минимальное время, которое требуется для прохождения игры.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 1 3 4 3
3 2 5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
34</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 2 4 4 1
4 5 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
31</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, оптимальная стратегия это:</p><ul> <li> Используйте пистолет чтобы убить трех обычных монстров и AWP, чтобы убить босса (Итоговое время равно $$$1\cdot3+4=7$$$) </li><li> Переместитесь на этап два (Итоговое время $$$7+3=10$$$) </li><li> Используйте пистолет дважды и AWP чтобы убить босса (Итоговое время $$$10+1\cdot2+4=16$$$) </li><li> Переместитесь на этап три (Итоговое время $$$16+3=19$$$) </li><li> Используйте лазерную пушку, теперь мы обязаны переместиться на этап два или четыре, мы движемся на этап четыре (Итоговое время $$$19+3+3=25$$$) </li><li> Используйте пистолет один раз, используйте AWP, чтобы убить босса (Итоговое время $$$25+1\cdot1+4=30$$$) </li><li> Двигайтесь обратно на этап три (Итоговое время $$$30+3=33$$$) </li><li> Убейте босса на третьем этапе пистолетом (Итоговое время $$$33+1=34$$$) </li></ul><p>Обратите внимание, что здесь мы останавливаемся не на этапе $$$n$$$, а когда все боссы убиты.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="34348b642c8e5b896a97107943bdc5fc"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="ba1f88c3587bbb20752b89168959853f472e1c01"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='34348b642c8e5b896a97107943bdc5fc'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1396%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='34348b642c8e5b896a97107943bdc5fc'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1396">Codeforces Round 666 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='34348b642c8e5b896a97107943bdc5fc'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1396/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='34348b642c8e5b896a97107943bdc5fc'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712378"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='34348b642c8e5b896a97107943bdc5fc'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712378"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11780" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11827" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1396">Задачи</a></li>
<li><a
href="/contest/1396/submit">Отослать</a></li>
<li><a
href="/contest/1396/my">Мои посылки</a></li>
<li><a
href="/contest/1396/status">Статус</a></li>
<li><a
href="/contest/1396/hacks">Взломы</a></li>
<li><a
href="/contest/1396/room/1">Комната</a></li>
<li><a
href="/contest/1396/standings">Положение</a></li>
<li><a
href="/contest/1396/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_70ece30630e1dea8aeb92b9c3494217aa0f999c4">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Monster Invaders</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ziota нашел игру, которая назыается «Monster Invaders».</p><p>Аналогично другим RPG стрелялкам, в «Monster Invaders» требуется уничтожать монстров и боссов с помощью оружия.</p><p>Для простоты, мы рассмотрим только два вида монстров и три вида оружия.</p><p>А именно, два вида монстров это: </p><ul> <li> обычный монстр с $$$1$$$ hp. </li><li> босс с $$$2$$$ hp. </li></ul><p>И три вида оружия: </p><ul> <li> Пистолет, наносит $$$1$$$ hp урона одному монстру, время перезарядки равно $$$r_1$$$ </li><li> Лазерная пушка, наносит $$$1$$$ hp урона всем монстрам в данном уровне (включая босса), время перезарядки равно $$$r_2$$$ </li><li> AWP, мгновенно убивает любого монстра, время перезарядки равно $$$r_3$$$ </li></ul><p><span class="tex-font-style-bf">Исходно оружия незаряжены, и Ziota не может перезаряжать несколько оружий одновременно.</span></p><p>Этапы в игре могут быть описаны массивом $$$a_1, a_2, \ldots, a_n$$$, в котором <span class="tex-font-style-bf">$$$i$$$-й этап содержит $$$a_i$$$ обычных монстров и одного босса</span>. Из-за натуры игры, <span class="tex-font-style-bf">Ziota не может использовать пистолет (оружие первого типа) или AWP (оружие третьего типа) чтобы выстрелить в босса, до того как будут убиты все $$$a_i$$$ обычных монстров</span>.</p><p>Если Ziota ранит босса, но не убивает его полностью, <span class="tex-font-style-bf">он обязан уйти с текущего этапа на любой соседний этап</span> (соседние к этапу $$$i$$$ $$$(1 < i < n)$$$ это этапы $$$i - 1$$$ и $$$i + 1$$$, единственный сосед этапа $$$1$$$ это этап $$$2$$$, единственный этап соседний к этапу $$$n$$$ это $$$n - 1$$$). Ziota также может уйти в любом соседний уровень в любой момент времени. <span class="tex-font-style-bf">Каждый переход между соседними уровнями выполняется с помощью портала, с временем телепортации $$$d$$$.</span></p><p>Чтобы не повредить пространственно-временной континуум внутри игры, <span class="tex-font-style-bf">запрещено перезаряжаться или стрелять в монстров во время телепортации. </span></p><p>Ziota начинает игру на этапе 1. Его задача довольно проста, убить всех монстров на всех этапах. Он хочет узнать минимальное время, которое ему нужно, чтобы этого добиться (вы можете считать, что выстрел в монстров происходит мгновенно и у него есть бесконечное количество патронов для каждого оружия). Пожалуйста, помогите ему найти это значение.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны пять целых чисел, разделенных пробелами: $$$n$$$ $$$(2 \le n \le 10^6)$$$ — количество этапов, $$$r_1, r_2, r_3$$$ $$$(1 \le r_1 \le r_2 \le r_3 \le 10^9)$$$ — времена перезарядки трех оружий, $$$d$$$ $$$(1 \le d \le 10^9)$$$ — время перехода между соседними уровнями.</p><p>Во второй строке записаны $$$n$$$ разделенных пробелами целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6, 1 \le i \le n)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, минимальное время, которое требуется для прохождения игры.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 1 3 4 3
3 2 5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
34</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 2 4 4 1
4 5 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
31</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, оптимальная стратегия это:</p><ul> <li> Используйте пистолет чтобы убить трех обычных монстров и AWP, чтобы убить босса (Итоговое время равно $$$1\cdot3+4=7$$$) </li><li> Переместитесь на этап два (Итоговое время $$$7+3=10$$$) </li><li> Используйте пистолет дважды и AWP чтобы убить босса (Итоговое время $$$10+1\cdot2+4=16$$$) </li><li> Переместитесь на этап три (Итоговое время $$$16+3=19$$$) </li><li> Используйте лазерную пушку, теперь мы обязаны переместиться на этап два или четыре, мы движемся на этап четыре (Итоговое время $$$19+3+3=25$$$) </li><li> Используйте пистолет один раз, используйте AWP, чтобы убить босса (Итоговое время $$$25+1\cdot1+4=30$$$) </li><li> Двигайтесь обратно на этап три (Итоговое время $$$30+3=33$$$) </li><li> Убейте босса на третьем этапе пистолетом (Итоговое время $$$33+1=34$$$) </li></ul><p>Обратите внимание, что здесь мы останавливаемся не на этапе $$$n$$$, а когда все боссы убиты.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:19</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a945b8859d76',t:'MTY5NjY2NjE1OS4xMTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2300"] | ||
1396D | 1396 | D | ru | D. Радужные прямоугольники | <div class="problem-statement"><div class="header"><div class="title">D. Радужные прямоугольники</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Shrimpy Duc это пухлый и жадный мальчик, который всегда голоден. После бесчисленных попыток найти еду, чтобы утолить его нескончаемый голод, Shrimpy Duc нашел конфеты M&M, лежащие на поле $$$L \times L$$$. Есть $$$n$$$ конфеток M&M на этом поле, $$$i$$$-я из них находится в точке $$$(x_i + 0.5, y_i + 0.5),$$$ и имеет цвет $$$c_i$$$, один из возможных $$$k$$$ цветов (размерами M&Ms можно пренебречь).</p><p>Shrimpy Duc хочет украсть <span class="tex-font-style-bf">прямоугольник</span> M&Ms, а именно, он хочет выбрать прямоугольник с <span class="tex-font-style-bf">целочисленными</span> координатами внутри поля, и украсть все M&Ms в нем. Ему необязательно красть все конфеты, однако, он хочет украсть <span class="tex-font-style-bf">хотя бы одну конфету каждого цвета</span>.</p><p>Иначе говоря, он хочет посчитать количество таких прямоугольников, в которых левая нижняя вершина находится в $$$(X_1, Y_1)$$$, правая верхняя в $$$(X_2, Y_2)$$$, они являются точками с целочисленными координатами, удовлетворяющие условиям $$$0 \le X_1 < X_2 \le L$$$ и $$$0 \le Y_1 < Y_2 \le L$$$, что для каждого $$$1 \le c \le k$$$ существует хотя бы одна M&M с цветом $$$c$$$, которая лежит в этом прямоугольнике.</p><p>Сколько существует таких прямоугольников? Это число может быть большим, так что вам достаточно найти его по модулю $$$10^9 + 7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n, k, L$$$ $$$(1 \leq k \leq n \leq 2 \cdot 10^3, 1 \leq L \leq 10^9 )$$$ — количество M&Ms, количество цветов, и размер поля, соответственно.</p><p>Каждая из следующих $$$n$$$ строк описывает M&Ms. В каждой строке записано три целых числа $$$x_i, y_i, c_i$$$ $$$(0 \leq x_i, y_i < L, 1 \le c_i \le k)$$$ — координаты и цвет $$$i$$$-й M&M, соответственно. </p><p>Разные M&Ms имеют разные координаты ($$$x_i \ne x_j$$$ или $$$y_i \ne y_j$$$ для всех $$$i \ne j$$$), и для каждого $$$1 \le c \le k$$$ есть хотя бы одна M&M с цветом $$$c$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество прямоугольников, удовлетворяющих условиям Shrimpy Duc, по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2 4
3 2 2
3 1 1
1 1 1
1 2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
20
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 3 10
6 5 3
5 3 1
7 9 1
2 3 2
5 0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
300
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 4 10
5 4 4
0 0 3
6 0 1
3 9 2
8 7 1
8 1 3
2 1 3
6 3 2
3 5 3
4 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
226
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Поле для первого примера:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/b59d7cc029b38e682398953edce2f8c14b7c0c4c.png" style="max-width: 100.0%;max-height: 100.0%;"/></p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="8a4bd3da7fc5674ab74e29f85bdf775f"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="ba1f88c3587bbb20752b89168959853f472e1c01"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='8a4bd3da7fc5674ab74e29f85bdf775f'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1396%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='8a4bd3da7fc5674ab74e29f85bdf775f'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1396">Codeforces Round 666 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='8a4bd3da7fc5674ab74e29f85bdf775f'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1396/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8a4bd3da7fc5674ab74e29f85bdf775f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712376"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8a4bd3da7fc5674ab74e29f85bdf775f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712376"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11780" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11827" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1396">Задачи</a></li>
<li><a
href="/contest/1396/submit">Отослать</a></li>
<li><a
href="/contest/1396/my">Мои посылки</a></li>
<li><a
href="/contest/1396/status">Статус</a></li>
<li><a
href="/contest/1396/hacks">Взломы</a></li>
<li><a
href="/contest/1396/room/1">Комната</a></li>
<li><a
href="/contest/1396/standings">Положение</a></li>
<li><a
href="/contest/1396/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_3b2a5e516b66a77c14b47bbab53f5dc1487fdc1b">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Радужные прямоугольники</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Shrimpy Duc это пухлый и жадный мальчик, который всегда голоден. После бесчисленных попыток найти еду, чтобы утолить его нескончаемый голод, Shrimpy Duc нашел конфеты M&M, лежащие на поле $$$L \times L$$$. Есть $$$n$$$ конфеток M&M на этом поле, $$$i$$$-я из них находится в точке $$$(x_i + 0.5, y_i + 0.5),$$$ и имеет цвет $$$c_i$$$, один из возможных $$$k$$$ цветов (размерами M&Ms можно пренебречь).</p><p>Shrimpy Duc хочет украсть <span class="tex-font-style-bf">прямоугольник</span> M&Ms, а именно, он хочет выбрать прямоугольник с <span class="tex-font-style-bf">целочисленными</span> координатами внутри поля, и украсть все M&Ms в нем. Ему необязательно красть все конфеты, однако, он хочет украсть <span class="tex-font-style-bf">хотя бы одну конфету каждого цвета</span>.</p><p>Иначе говоря, он хочет посчитать количество таких прямоугольников, в которых левая нижняя вершина находится в $$$(X_1, Y_1)$$$, правая верхняя в $$$(X_2, Y_2)$$$, они являются точками с целочисленными координатами, удовлетворяющие условиям $$$0 \le X_1 < X_2 \le L$$$ и $$$0 \le Y_1 < Y_2 \le L$$$, что для каждого $$$1 \le c \le k$$$ существует хотя бы одна M&M с цветом $$$c$$$, которая лежит в этом прямоугольнике.</p><p>Сколько существует таких прямоугольников? Это число может быть большим, так что вам достаточно найти его по модулю $$$10^9 + 7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n, k, L$$$ $$$(1 \leq k \leq n \leq 2 \cdot 10^3, 1 \leq L \leq 10^9 )$$$ — количество M&Ms, количество цветов, и размер поля, соответственно.</p><p>Каждая из следующих $$$n$$$ строк описывает M&Ms. В каждой строке записано три целых числа $$$x_i, y_i, c_i$$$ $$$(0 \leq x_i, y_i < L, 1 \le c_i \le k)$$$ — координаты и цвет $$$i$$$-й M&M, соответственно. </p><p>Разные M&Ms имеют разные координаты ($$$x_i \ne x_j$$$ или $$$y_i \ne y_j$$$ для всех $$$i \ne j$$$), и для каждого $$$1 \le c \le k$$$ есть хотя бы одна M&M с цветом $$$c$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество прямоугольников, удовлетворяющих условиям Shrimpy Duc, по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2 4
3 2 2
3 1 1
1 1 1
1 2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
20
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 3 10
6 5 3
5 3 1
7 9 1
2 3 2
5 0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
300
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 4 10
5 4 4
0 0 3
6 0 1
3 9 2
8 7 1
8 1 3
2 1 3
6 3 2
3 5 3
4 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
226
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Поле для первого примера:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/b59d7cc029b38e682398953edce2f8c14b7c0c4c.png" style="max-width: 100.0%;max-height: 100.0%;" /></p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:20</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a94e29729d76',t:'MTY5NjY2NjE2MC41MDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3300"] | ||
1396E | 1396 | E | ru | E. Паросочетание с расстояниями | <div class="problem-statement"><div class="header"><div class="title">E. Паросочетание с расстояниями</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано целое число $$$k$$$ и <span class="tex-font-style-it">дерево</span> $$$T$$$ с $$$n$$$ вершинами ($$$n$$$ четно).</p><p>Обозначим за $$$dist(u, v)$$$ количество ребер на кратчайшем пути между вершинами $$$u$$$ и $$$v$$$ в $$$T$$$.</p><p>Определим <span class="tex-font-style-it">неориентированный взвешенный полный граф</span> $$$G = (V, E)$$$ следующим образом: </p><ul> <li> $$$V = \{x \mid 1 \le x \le n \}$$$ т.е. множество целых чисел от $$$1$$$ до $$$n$$$</li><li> $$$E = \{(u, v, w) \mid 1 \le u, v \le n, u \neq v, w = dist(u, v) \}$$$ т.е. существует ребро между каждой парой разных вершин, вес ребра равен расстоянию между соотвествующими вершинами в $$$T$$$ </li></ul><p>Ваша задача — найти <span class="tex-font-style-it">совершенное паросочетание</span> в $$$G$$$ с суммой весов ребер $$$k$$$ $$$(1 \le k \le n^2)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$, $$$k$$$ ($$$2 \le n \le 100\,000$$$, $$$n$$$ четное, $$$1 \le k \le n^2$$$): количество вершин и необходимый вес паросочетания.</p><p>В $$$i$$$-й из следующих $$$n - 1$$$ строк записаны два целых числа $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$), описывающих ребро между вершинами $$$v_i$$$ и $$$u_i$$$ в $$$T$$$. Гарантируется, что данный граф является деревом. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует необходимого паросочетания, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек) в единственной строке. </p><p>Иначе, выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек) в первой строке вывода.</p><p>Затем, выведите $$$\frac{n}{2}$$$ строк, в $$$i$$$-й из них выведите $$$p_i, q_i$$$ ($$$1 \le p_i, q_i \le n$$$): $$$i$$$-ю пару в паросочетании.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2
1 2
2 3
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
2 1
3 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 4
1 2
2 3
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
3 1
2 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-it">Дерево</span> это связный неориентированный граф без циклов.</p><p><span class="tex-font-style-it">Паросочетание</span> это множество попарно несмежных ребер, без петель; таким образом, никакие два ребра не имеют общих концов. </p><p><span class="tex-font-style-it">Совершенное паросочетание</span> это паросочетание, которое покрывает все вершины графа; таким образом, каждая вершина инцидентна ровно одному ребру паросочетания.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="3774d659b7e318df1fa07a75d167b12c"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="ba1f88c3587bbb20752b89168959853f472e1c01"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='3774d659b7e318df1fa07a75d167b12c'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1396%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='3774d659b7e318df1fa07a75d167b12c'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1396">Codeforces Round 666 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='3774d659b7e318df1fa07a75d167b12c'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1396/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3774d659b7e318df1fa07a75d167b12c'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712377"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3774d659b7e318df1fa07a75d167b12c'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712377"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11780" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11827" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1396">Задачи</a></li>
<li><a
href="/contest/1396/submit">Отослать</a></li>
<li><a
href="/contest/1396/my">Мои посылки</a></li>
<li><a
href="/contest/1396/status">Статус</a></li>
<li><a
href="/contest/1396/hacks">Взломы</a></li>
<li><a
href="/contest/1396/room/1">Комната</a></li>
<li><a
href="/contest/1396/standings">Положение</a></li>
<li><a
href="/contest/1396/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_f6fe862259927d6c793fbd6e0a798c2bf430e42d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Паросочетание с расстояниями</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано целое число $$$k$$$ и <span class="tex-font-style-it">дерево</span> $$$T$$$ с $$$n$$$ вершинами ($$$n$$$ четно).</p><p>Обозначим за $$$dist(u, v)$$$ количество ребер на кратчайшем пути между вершинами $$$u$$$ и $$$v$$$ в $$$T$$$.</p><p>Определим <span class="tex-font-style-it">неориентированный взвешенный полный граф</span> $$$G = (V, E)$$$ следующим образом: </p><ul> <li> $$$V = \{x \mid 1 \le x \le n \}$$$ т.е. множество целых чисел от $$$1$$$ до $$$n$$$</li><li> $$$E = \{(u, v, w) \mid 1 \le u, v \le n, u \neq v, w = dist(u, v) \}$$$ т.е. существует ребро между каждой парой разных вершин, вес ребра равен расстоянию между соотвествующими вершинами в $$$T$$$ </li></ul><p>Ваша задача — найти <span class="tex-font-style-it">совершенное паросочетание</span> в $$$G$$$ с суммой весов ребер $$$k$$$ $$$(1 \le k \le n^2)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$, $$$k$$$ ($$$2 \le n \le 100\,000$$$, $$$n$$$ четное, $$$1 \le k \le n^2$$$): количество вершин и необходимый вес паросочетания.</p><p>В $$$i$$$-й из следующих $$$n - 1$$$ строк записаны два целых числа $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$), описывающих ребро между вершинами $$$v_i$$$ и $$$u_i$$$ в $$$T$$$. Гарантируется, что данный граф является деревом. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует необходимого паросочетания, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек) в единственной строке. </p><p>Иначе, выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек) в первой строке вывода.</p><p>Затем, выведите $$$\frac{n}{2}$$$ строк, в $$$i$$$-й из них выведите $$$p_i, q_i$$$ ($$$1 \le p_i, q_i \le n$$$): $$$i$$$-ю пару в паросочетании.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2
1 2
2 3
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
2 1
3 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 4
1 2
2 3
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
3 1
2 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-it">Дерево</span> это связный неориентированный граф без циклов.</p><p><span class="tex-font-style-it">Паросочетание</span> это множество попарно несмежных ребер, без петель; таким образом, никакие два ребра не имеют общих концов. </p><p><span class="tex-font-style-it">Совершенное паросочетание</span> это паросочетание, которое покрывает все вершины графа; таким образом, каждая вершина инцидентна ровно одному ребру паросочетания.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:21</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a956cbf9160a',t:'MTY5NjY2NjE2MS45MjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*3200"] | ||
1397A | 1397 | A | ru | A. Жонглирование буквами | <div class="problem-statement"><div class="header"><div class="title">A. Жонглирование буквами</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано $$$n$$$ строк $$$s_1, s_2, \ldots, s_n$$$ состоящих из строчных букв латинского алфавита.</p><p>За одну операцию вы можете удалить один символ из строки $$$s_i$$$ и вставить его в любую позицию строки $$$s_j$$$ ($$$j$$$ может быть равно $$$i$$$). Вы можете совершать эту операцию сколько угодно раз. Возможно ли сделать все $$$n$$$ строк равными?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10$$$): количество наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$1 \le n \le 1000$$$): количество строк.</p><p>В следующих $$$n$$$ строках, $$$i$$$-я из них содержит $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$).</p><p>Сумма длин всех строк по всем наборам входных данных не превосходит $$$1000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если возможно сделать все строки равными, выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек).</p><p>Иначе, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждый символ как в нижнем, так и в верхнем регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, вы можете сделать следующее: </p><ul> <li> Удалить третий символ первой строки и вставить его после второго символа второй строки, превратив две строки в «<span class="tex-font-style-tt">ca</span>» и «<span class="tex-font-style-tt">cbab</span>», соотвестственно.</li><li> Удалить второй символ второй строки и вставить его после второго символа первой строки, сделав обе строки равными «<span class="tex-font-style-tt">cab</span>». </li></ul><p>Во втором наборе входных данных невозможно сделать все $$$n$$$ строк равными.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="42291d8a1039ffcec346ea780e750f16"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="86947c66c2e4266e165431a2ba9ba9adffb8005d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='42291d8a1039ffcec346ea780e750f16'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1397%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='42291d8a1039ffcec346ea780e750f16'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1397">Codeforces Round 666 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='42291d8a1039ffcec346ea780e750f16'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1397/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='42291d8a1039ffcec346ea780e750f16'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712379"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='42291d8a1039ffcec346ea780e750f16'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712379"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11781" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11828" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1397">Задачи</a></li>
<li><a
href="/contest/1397/submit">Отослать</a></li>
<li><a
href="/contest/1397/my">Мои посылки</a></li>
<li><a
href="/contest/1397/status">Статус</a></li>
<li><a
href="/contest/1397/hacks">Взломы</a></li>
<li><a
href="/contest/1397/room/1">Комната</a></li>
<li><a
href="/contest/1397/standings">Положение</a></li>
<li><a
href="/contest/1397/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_42a8654573c047db1964a862c2945cc7aabc6f33">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Жонглирование буквами</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано $$$n$$$ строк $$$s_1, s_2, \ldots, s_n$$$ состоящих из строчных букв латинского алфавита.</p><p>За одну операцию вы можете удалить один символ из строки $$$s_i$$$ и вставить его в любую позицию строки $$$s_j$$$ ($$$j$$$ может быть равно $$$i$$$). Вы можете совершать эту операцию сколько угодно раз. Возможно ли сделать все $$$n$$$ строк равными?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10$$$): количество наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$1 \le n \le 1000$$$): количество строк.</p><p>В следующих $$$n$$$ строках, $$$i$$$-я из них содержит $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$).</p><p>Сумма длин всех строк по всем наборам входных данных не превосходит $$$1000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если возможно сделать все строки равными, выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек).</p><p>Иначе, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждый символ как в нижнем, так и в верхнем регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
2
caa
cbb
3
cba
cba
cbb
4
ccab
cbac
bca
acbcc
4
acb
caf
c
cbafc
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, вы можете сделать следующее: </p><ul> <li> Удалить третий символ первой строки и вставить его после второго символа второй строки, превратив две строки в «<span class="tex-font-style-tt">ca</span>» и «<span class="tex-font-style-tt">cbab</span>», соотвестственно.</li><li> Удалить второй символ второй строки и вставить его после второго символа первой строки, сделав обе строки равными «<span class="tex-font-style-tt">cab</span>». </li></ul><p>Во втором наборе входных данных невозможно сделать все $$$n$$$ строк равными.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:23</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a95fbe6b064b',t:'MTY5NjY2NjE2My4zODEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u043e\u043a\u0438", "*800"] | ||
1397B | 1397 | B | ru | B. Степенная последовательность | <div class="problem-statement"><div class="header"><div class="title">B. Степенная последовательность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем последовательность положительных чисел $$$a_0, a_1, ..., a_{n-1}$$$ <span class="tex-font-style-bf">степенной последовательностью</span>, если найдется такое положительное целое число $$$c$$$, что для всех $$$0 \le i \le n-1$$$, $$$a_i = c^i$$$.</p><p>Вам дана последовательность из $$$n$$$ положительных чисел $$$a_0, a_1, ..., a_{n-1}$$$, вам разрешается:</p><ul> <li> Переупорядочить последовательность (иначе говоря, выбрать перестановку $$$p$$$ из $$$\{0,1,...,n - 1\}$$$ и заменить $$$a_i$$$ на $$$a_{p_i}$$$), и затем </li><li> Выполнить следующую операцию любое количество раз: выбрать индекс $$$i$$$ и заменить $$$a_i$$$ на $$$a_i - 1$$$ или $$$a_i + 1$$$ (иначе говоря, уменьшить или увеличить $$$a_i$$$ на $$$1$$$) за стоимость $$$1$$$. </li></ul><p>Найдите минимальную стоимость, необходимую для превращения $$$a_0, a_1, ..., a_{n-1}$$$ в степенную последовательность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$3 \le n \le 10^5$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальную стоимость, необходимую для превращения $$$a_0, a_1, ..., a_{n-1}$$$ в степенную последовательность.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
1 3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1000000000 1000000000 1000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1999982505
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере сначала можно переупорядочить $$$\{1, 3, 2\}$$$ в $$$\{1, 2, 3\}$$$, затем увеличить $$$a_2$$$ до $$$4$$$ за стоимость $$$1$$$, чтобы получить степенную последовательность $$$\{1, 2, 4\}$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="a480797f989390b329b442ecfc38f9e8"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="86947c66c2e4266e165431a2ba9ba9adffb8005d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='a480797f989390b329b442ecfc38f9e8'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1397%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='a480797f989390b329b442ecfc38f9e8'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1397">Codeforces Round 666 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='a480797f989390b329b442ecfc38f9e8'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1397/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a480797f989390b329b442ecfc38f9e8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712380"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a480797f989390b329b442ecfc38f9e8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712380"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11781" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11828" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1397">Задачи</a></li>
<li><a
href="/contest/1397/submit">Отослать</a></li>
<li><a
href="/contest/1397/my">Мои посылки</a></li>
<li><a
href="/contest/1397/status">Статус</a></li>
<li><a
href="/contest/1397/hacks">Взломы</a></li>
<li><a
href="/contest/1397/room/1">Комната</a></li>
<li><a
href="/contest/1397/standings">Положение</a></li>
<li><a
href="/contest/1397/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_61a4424cfc80479bc84f068496cb3a6431264eeb">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Степенная последовательность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовем последовательность положительных чисел $$$a_0, a_1, ..., a_{n-1}$$$ <span class="tex-font-style-bf">степенной последовательностью</span>, если найдется такое положительное целое число $$$c$$$, что для всех $$$0 \le i \le n-1$$$, $$$a_i = c^i$$$.</p><p>Вам дана последовательность из $$$n$$$ положительных чисел $$$a_0, a_1, ..., a_{n-1}$$$, вам разрешается:</p><ul> <li> Переупорядочить последовательность (иначе говоря, выбрать перестановку $$$p$$$ из $$$\{0,1,...,n - 1\}$$$ и заменить $$$a_i$$$ на $$$a_{p_i}$$$), и затем </li><li> Выполнить следующую операцию любое количество раз: выбрать индекс $$$i$$$ и заменить $$$a_i$$$ на $$$a_i - 1$$$ или $$$a_i + 1$$$ (иначе говоря, уменьшить или увеличить $$$a_i$$$ на $$$1$$$) за стоимость $$$1$$$. </li></ul><p>Найдите минимальную стоимость, необходимую для превращения $$$a_0, a_1, ..., a_{n-1}$$$ в степенную последовательность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$3 \le n \le 10^5$$$).</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_0, a_1, ..., a_{n-1}$$$ ($$$1 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальную стоимость, необходимую для превращения $$$a_0, a_1, ..., a_{n-1}$$$ в степенную последовательность.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
1 3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1000000000 1000000000 1000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1999982505
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере сначала можно переупорядочить $$$\{1, 3, 2\}$$$ в $$$\{1, 2, 3\}$$$, затем увеличить $$$a_2$$$ до $$$4$$$ за стоимость $$$1$$$, чтобы получить степенную последовательность $$$\{1, 2, 4\}$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:24</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a968d90c164b',t:'MTY5NjY2NjE2NC44MzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1500"] | ||
1397C | 1397 | C | ru | C. Кратные длине | <div class="problem-statement"><div class="header"><div class="title">C. Кратные длине</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел.</p><p>Вы хотите сделать все элементы $$$a$$$ равными нулю, применив следующую операцию <span class="tex-font-style-bf">ровно три</span> раза:</p><ul> <li> Выберите отрезок, к каждому числу на этом отрезке добавьте число кратное $$$len$$$, где $$$len$$$ это длина этого отрезка (добавленные числа могут быть разными). </li></ul><p>Можно доказать, что таким образом всегда можно превратить все элементы $$$a$$$ в нули.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 100\,000$$$): количество элементов массиве.</p><p>Во второй строке записаны $$$n$$$ элементов массива $$$a$$$, разделенные пробелами: $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите шесть строк, описывающих три операции.</p><p>Для каждой операции, выведите две строки:</p><ul><p> </p><li> В первой строке выведите два числа $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n$$$): границы выбранного отрезка.<p> </p></li><li> Во второй строке выведите $$$r-l+1$$$ целых чисел $$$b_l, b_{l+1}, \dots, b_r$$$ ($$$-10^{18} \le b_i \le 10^{18}$$$): числа, которые нужно прибавить к $$$a_l, a_{l+1}, \ldots, a_r$$$, соответственно; $$$b_i$$$ должно делиться на $$$r - l + 1$$$.</li></ul> </div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 3 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 1
-1
3 4
4 2
2 4
-3 -6 -6</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="7fa38d38123eb02876021cfb8fdbc335"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="86947c66c2e4266e165431a2ba9ba9adffb8005d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='7fa38d38123eb02876021cfb8fdbc335'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1397%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='7fa38d38123eb02876021cfb8fdbc335'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1397">Codeforces Round 666 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='7fa38d38123eb02876021cfb8fdbc335'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1397/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7fa38d38123eb02876021cfb8fdbc335'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712381"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7fa38d38123eb02876021cfb8fdbc335'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712381"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11781" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11828" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1397">Задачи</a></li>
<li><a
href="/contest/1397/submit">Отослать</a></li>
<li><a
href="/contest/1397/my">Мои посылки</a></li>
<li><a
href="/contest/1397/status">Статус</a></li>
<li><a
href="/contest/1397/hacks">Взломы</a></li>
<li><a
href="/contest/1397/room/1">Комната</a></li>
<li><a
href="/contest/1397/standings">Положение</a></li>
<li><a
href="/contest/1397/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_11270956e1cb044505de93ab94e01ab4edfd7fe1">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Кратные длине</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел.</p><p>Вы хотите сделать все элементы $$$a$$$ равными нулю, применив следующую операцию <span class="tex-font-style-bf">ровно три</span> раза:</p><ul> <li> Выберите отрезок, к каждому числу на этом отрезке добавьте число кратное $$$len$$$, где $$$len$$$ это длина этого отрезка (добавленные числа могут быть разными). </li></ul><p>Можно доказать, что таким образом всегда можно превратить все элементы $$$a$$$ в нули.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 100\,000$$$): количество элементов массиве.</p><p>Во второй строке записаны $$$n$$$ элементов массива $$$a$$$, разделенные пробелами: $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите шесть строк, описывающих три операции.</p><p>Для каждой операции, выведите две строки:</p><ul><p> </p><li> В первой строке выведите два числа $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n$$$): границы выбранного отрезка.<p> </p></li><li> Во второй строке выведите $$$r-l+1$$$ целых чисел $$$b_l, b_{l+1}, \dots, b_r$$$ ($$$-10^{18} \le b_i \le 10^{18}$$$): числа, которые нужно прибавить к $$$a_l, a_{l+1}, \ldots, a_r$$$, соответственно; $$$b_i$$$ должно делиться на $$$r - l + 1$$$.</li></ul> </div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 3 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 1
-1
3 4
4 2
2 4
-3 -6 -6</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:26</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a971e9c31616',t:'MTY5NjY2NjE2Ni4xMzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"] | ||
1397D | 1397 | D | ru | D. Каменная игра | <div class="problem-statement"><div class="header"><div class="title">D. Каменная игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>T играет в игру со своим другом HL.</p><p>Есть $$$n$$$ кучек с камнями, в $$$i$$$-й из них исходно содержится $$$a_i$$$ камней. </p><p>T и HL будут ходить чередуясь, и T ходит первым. В каждом ходу, игрок выбирает непустую кучу и удаляет из нее один камень. Однако, нельзя выбирать кучку, которая была выбрана на прошлом ходу (кучку которая была выбрана другим игроком, или если текущий ход это первый ход первого игрока, то можно выбрать любую кучу). Игрок, который не может выбрать кучу на своем ходу, проигрывает.</p><p>Считая, что оба игрока играют оптимально, для заданных стартовых конфигураций $$$t$$$ игр, определите победителя.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ $$$(1 \le t \le 100)$$$ — количество игр. Далее следуют описания игр, описание каждой игры состоит из двух строк:</p><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 100)$$$ — количество куч.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 100)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой игры, выведите в отдельной строке имя победителя, «<span class="tex-font-style-tt">T</span>» или «<span class="tex-font-style-tt">HL</span>» (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1
2
2
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
T
HL
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первой игре, T убирает один камень из единственной кучи. После этого, несмотря на то, что в куче еще остался $$$1$$$ камень, HL не можем сходить, из-за того что T использовал эту кучу на прошлом ходу. Таким образом, T побеждает.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="8ec9fb59f8792bd027bc94b059206518"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="86947c66c2e4266e165431a2ba9ba9adffb8005d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='8ec9fb59f8792bd027bc94b059206518'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1397%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='8ec9fb59f8792bd027bc94b059206518'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1397">Codeforces Round 666 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='8ec9fb59f8792bd027bc94b059206518'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1397/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди">
игры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8ec9fb59f8792bd027bc94b059206518'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712382"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8ec9fb59f8792bd027bc94b059206518'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712382"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11781" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11828" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1397">Задачи</a></li>
<li><a
href="/contest/1397/submit">Отослать</a></li>
<li><a
href="/contest/1397/my">Мои посылки</a></li>
<li><a
href="/contest/1397/status">Статус</a></li>
<li><a
href="/contest/1397/hacks">Взломы</a></li>
<li><a
href="/contest/1397/room/1">Комната</a></li>
<li><a
href="/contest/1397/standings">Положение</a></li>
<li><a
href="/contest/1397/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_1f6e730abcf7a19810e3a91650b4e5a448a98a6e">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Каменная игра</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>T играет в игру со своим другом HL.</p><p>Есть $$$n$$$ кучек с камнями, в $$$i$$$-й из них исходно содержится $$$a_i$$$ камней. </p><p>T и HL будут ходить чередуясь, и T ходит первым. В каждом ходу, игрок выбирает непустую кучу и удаляет из нее один камень. Однако, нельзя выбирать кучку, которая была выбрана на прошлом ходу (кучку которая была выбрана другим игроком, или если текущий ход это первый ход первого игрока, то можно выбрать любую кучу). Игрок, который не может выбрать кучу на своем ходу, проигрывает.</p><p>Считая, что оба игрока играют оптимально, для заданных стартовых конфигураций $$$t$$$ игр, определите победителя.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ $$$(1 \le t \le 100)$$$ — количество игр. Далее следуют описания игр, описание каждой игры состоит из двух строк:</p><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 100)$$$ — количество куч.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 100)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой игры, выведите в отдельной строке имя победителя, «<span class="tex-font-style-tt">T</span>» или «<span class="tex-font-style-tt">HL</span>» (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1
2
2
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
T
HL
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первой игре, T убирает один камень из единственной кучи. После этого, несмотря на то, что в куче еще остался $$$1$$$ камень, HL не можем сходить, из-за того что T использовал эту кучу на прошлом ходу. Таким образом, T побеждает.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:27</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a97a0af99d9c',t:'MTY5NjY2NjE2Ny40NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u0433\u0440\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1800"] | ||
1397E | 1397 | E | ru | E. Monster Invaders | <div class="problem-statement"><div class="header"><div class="title">E. Monster Invaders</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ziota нашел игру, которая назыается «Monster Invaders».</p><p>Аналогично другим RPG стрелялкам, в «Monster Invaders» требуется уничтожать монстров и боссов с помощью оружия.</p><p>Для простоты, мы рассмотрим только два вида монстров и три вида оружия.</p><p>А именно, два вида монстров это: </p><ul> <li> обычный монстр с $$$1$$$ hp. </li><li> босс с $$$2$$$ hp. </li></ul><p>И три вида оружия: </p><ul> <li> Пистолет, наносит $$$1$$$ hp урона одному монстру, время перезарядки равно $$$r_1$$$ </li><li> Лазерная пушка, наносит $$$1$$$ hp урона всем монстрам в данном уровне (включая босса), время перезарядки равно $$$r_2$$$ </li><li> AWP, мгновенно убивает любого монстра, время перезарядки равно $$$r_3$$$ </li></ul><p><span class="tex-font-style-bf">Исходно оружия незаряжены, и Ziota не может перезаряжать несколько оружий одновременно.</span></p><p>Этапы в игре могут быть описаны массивом $$$a_1, a_2, \ldots, a_n$$$, в котором <span class="tex-font-style-bf">$$$i$$$-й этап содержит $$$a_i$$$ обычных монстров и одного босса</span>. Из-за натуры игры, <span class="tex-font-style-bf">Ziota не может использовать пистолет (оружие первого типа) или AWP (оружие третьего типа) чтобы выстрелить в босса, до того как будут убиты все $$$a_i$$$ обычных монстров</span>.</p><p>Если Ziota ранит босса, но не убивает его полностью, <span class="tex-font-style-bf">он обязан уйти с текущего этапа на любой соседний этап</span> (соседние к этапу $$$i$$$ $$$(1 < i < n)$$$ это этапы $$$i - 1$$$ и $$$i + 1$$$, единственный сосед этапа $$$1$$$ это этап $$$2$$$, единственный этап соседний к этапу $$$n$$$ это $$$n - 1$$$). Ziota также может уйти в любом соседний уровень в любой момент времени. <span class="tex-font-style-bf">Каждый переход между соседними уровнями выполняется с помощью портала, с временем телепортации $$$d$$$.</span></p><p>Чтобы не повредить пространственно-временной континуум внутри игры, <span class="tex-font-style-bf">запрещено перезаряжаться или стрелять в монстров во время телепортации. </span></p><p>Ziota начинает игру на этапе 1. Его задача довольно проста, убить всех монстров на всех этапах. Он хочет узнать минимальное время, которое ему нужно, чтобы этого добиться (вы можете считать, что выстрел в монстров происходит мгновенно и у него есть бесконечное количество патронов для каждого оружия). Пожалуйста, помогите ему найти это значение.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны пять целых чисел, разделенных пробелами: $$$n$$$ $$$(2 \le n \le 10^6)$$$ — количество этапов, $$$r_1, r_2, r_3$$$ $$$(1 \le r_1 \le r_2 \le r_3 \le 10^9)$$$ — времена перезарядки трех оружий, $$$d$$$ $$$(1 \le d \le 10^9)$$$ — время перехода между соседними уровнями.</p><p>Во второй строке записаны $$$n$$$ разделенных пробелами целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6, 1 \le i \le n)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, минимальное время, которое требуется для прохождения игры.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 1 3 4 3
3 2 5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
34</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 2 4 4 1
4 5 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
31</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, оптимальная стратегия это:</p><ul> <li> Используйте пистолет чтобы убить трех обычных монстров и AWP, чтобы убить босса (Итоговое время равно $$$1\cdot3+4=7$$$) </li><li> Переместитесь на этап два (Итоговое время $$$7+3=10$$$) </li><li> Используйте пистолет дважды и AWP чтобы убить босса (Итоговое время $$$10+1\cdot2+4=16$$$) </li><li> Переместитесь на этап три (Итоговое время $$$16+3=19$$$) </li><li> Используйте лазерную пушку, теперь мы обязаны переместиться на этап два или четыре, мы движемся на этап четыре (Итоговое время $$$19+3+3=25$$$) </li><li> Используйте пистолет один раз, используйте AWP, чтобы убить босса (Итоговое время $$$25+1\cdot1+4=30$$$) </li><li> Двигайтесь обратно на этап три (Итоговое время $$$30+3=33$$$) </li><li> Убейте босса на третьем этапе пистолетом (Итоговое время $$$33+1=34$$$) </li></ul><p>Обратите внимание, что здесь мы останавливаемся не на этапе $$$n$$$, а когда все боссы убиты.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="7234c03d1f97753be5f0cf31ffba6a2d"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="86947c66c2e4266e165431a2ba9ba9adffb8005d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='7234c03d1f97753be5f0cf31ffba6a2d'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1397%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='7234c03d1f97753be5f0cf31ffba6a2d'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1397">Codeforces Round 666 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='7234c03d1f97753be5f0cf31ffba6a2d'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1397/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7234c03d1f97753be5f0cf31ffba6a2d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="712383"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7234c03d1f97753be5f0cf31ffba6a2d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="712383"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82050" title="Codeforces Round #666" target="_blank">Codeforces Round #666 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11781" resourceName="Codeforces Round #666"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82142" title="Codeforces Round #666 — Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11828" resourceName="Codeforces Round #666 — Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1397">Задачи</a></li>
<li><a
href="/contest/1397/submit">Отослать</a></li>
<li><a
href="/contest/1397/my">Мои посылки</a></li>
<li><a
href="/contest/1397/status">Статус</a></li>
<li><a
href="/contest/1397/hacks">Взломы</a></li>
<li><a
href="/contest/1397/room/1">Комната</a></li>
<li><a
href="/contest/1397/standings">Положение</a></li>
<li><a
href="/contest/1397/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_558e171b8b204809da8170d04efca18a2a9519cd">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Monster Invaders</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Ziota нашел игру, которая назыается «Monster Invaders».</p><p>Аналогично другим RPG стрелялкам, в «Monster Invaders» требуется уничтожать монстров и боссов с помощью оружия.</p><p>Для простоты, мы рассмотрим только два вида монстров и три вида оружия.</p><p>А именно, два вида монстров это: </p><ul> <li> обычный монстр с $$$1$$$ hp. </li><li> босс с $$$2$$$ hp. </li></ul><p>И три вида оружия: </p><ul> <li> Пистолет, наносит $$$1$$$ hp урона одному монстру, время перезарядки равно $$$r_1$$$ </li><li> Лазерная пушка, наносит $$$1$$$ hp урона всем монстрам в данном уровне (включая босса), время перезарядки равно $$$r_2$$$ </li><li> AWP, мгновенно убивает любого монстра, время перезарядки равно $$$r_3$$$ </li></ul><p><span class="tex-font-style-bf">Исходно оружия незаряжены, и Ziota не может перезаряжать несколько оружий одновременно.</span></p><p>Этапы в игре могут быть описаны массивом $$$a_1, a_2, \ldots, a_n$$$, в котором <span class="tex-font-style-bf">$$$i$$$-й этап содержит $$$a_i$$$ обычных монстров и одного босса</span>. Из-за натуры игры, <span class="tex-font-style-bf">Ziota не может использовать пистолет (оружие первого типа) или AWP (оружие третьего типа) чтобы выстрелить в босса, до того как будут убиты все $$$a_i$$$ обычных монстров</span>.</p><p>Если Ziota ранит босса, но не убивает его полностью, <span class="tex-font-style-bf">он обязан уйти с текущего этапа на любой соседний этап</span> (соседние к этапу $$$i$$$ $$$(1 < i < n)$$$ это этапы $$$i - 1$$$ и $$$i + 1$$$, единственный сосед этапа $$$1$$$ это этап $$$2$$$, единственный этап соседний к этапу $$$n$$$ это $$$n - 1$$$). Ziota также может уйти в любом соседний уровень в любой момент времени. <span class="tex-font-style-bf">Каждый переход между соседними уровнями выполняется с помощью портала, с временем телепортации $$$d$$$.</span></p><p>Чтобы не повредить пространственно-временной континуум внутри игры, <span class="tex-font-style-bf">запрещено перезаряжаться или стрелять в монстров во время телепортации. </span></p><p>Ziota начинает игру на этапе 1. Его задача довольно проста, убить всех монстров на всех этапах. Он хочет узнать минимальное время, которое ему нужно, чтобы этого добиться (вы можете считать, что выстрел в монстров происходит мгновенно и у него есть бесконечное количество патронов для каждого оружия). Пожалуйста, помогите ему найти это значение.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны пять целых чисел, разделенных пробелами: $$$n$$$ $$$(2 \le n \le 10^6)$$$ — количество этапов, $$$r_1, r_2, r_3$$$ $$$(1 \le r_1 \le r_2 \le r_3 \le 10^9)$$$ — времена перезарядки трех оружий, $$$d$$$ $$$(1 \le d \le 10^9)$$$ — время перехода между соседними уровнями.</p><p>Во второй строке записаны $$$n$$$ разделенных пробелами целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^6, 1 \le i \le n)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, минимальное время, которое требуется для прохождения игры.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 1 3 4 3
3 2 5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
34</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 2 4 4 1
4 5 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
31</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, оптимальная стратегия это:</p><ul> <li> Используйте пистолет чтобы убить трех обычных монстров и AWP, чтобы убить босса (Итоговое время равно $$$1\cdot3+4=7$$$) </li><li> Переместитесь на этап два (Итоговое время $$$7+3=10$$$) </li><li> Используйте пистолет дважды и AWP чтобы убить босса (Итоговое время $$$10+1\cdot2+4=16$$$) </li><li> Переместитесь на этап три (Итоговое время $$$16+3=19$$$) </li><li> Используйте лазерную пушку, теперь мы обязаны переместиться на этап два или четыре, мы движемся на этап четыре (Итоговое время $$$19+3+3=25$$$) </li><li> Используйте пистолет один раз, используйте AWP, чтобы убить босса (Итоговое время $$$25+1\cdot1+4=30$$$) </li><li> Двигайтесь обратно на этап три (Итоговое время $$$30+3=33$$$) </li><li> Убейте босса на третьем этапе пистолетом (Итоговое время $$$33+1=34$$$) </li></ul><p>Обратите внимание, что здесь мы останавливаемся не на этапе $$$n$$$, а когда все боссы убиты.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:28</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9822adf4985',t:'MTY5NjY2NjE2OC43NDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*2300"] | ||
1398A | 1398 | A | ru | A. Плохой треугольник | <div class="problem-statement"><div class="header"><div class="title">A. Плохой треугольник</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a_1, a_2, \dots , a_n$$$, отсортированный в порядке неубывания ($$$a_i \le a_{i + 1})$$$. </p><p>Найдите три индекса $$$i$$$, $$$j$$$, $$$k$$$, таких что $$$1 \le i < j < k \le n$$$ и <span class="tex-font-style-bf">невозможно</span> создать невырожденный треугольник (треугольник с ненулевой площадью) со сторонами $$$a_i$$$, $$$a_j$$$ и $$$a_k$$$ (например, возможно создать невырожденный треугольник со сторонами $$$3$$$, $$$4$$$ и $$$5$$$, но невозможно со сторонами $$$3$$$, $$$4$$$ и $$$7$$$). Или определите, что не существует таких три индекса.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно число $$$n$$$ ($$$3 \le n \le 5 \cdot 10^4$$$) — длина массива $$$a$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$; $$$a_{i - 1} \le a_i$$$) — массив $$$a$$$.</p><p>Гарантируется, что сумма всех $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ в отдельной строке.</p><p>Если существует тройка индексов $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$), такая что <span class="tex-font-style-bf">невозможно</span> создать невырожденный треугольник (треугольник с ненулевой площадью) со сторонами $$$a_i$$$, $$$a_j$$$ и $$$a_k$$$, выведите эти три индекса в порядке возрастания. Если существует несколько ответов, выведите любой из них.</p><p>Иначе выведите <span class="tex-font-style-tt">-1</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
7
4 6 11 11 15 18 20
4
10 10 10 11
3
1 1 1000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 6
-1
1 2 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных невозможно составить невырожденный треугольник со стронами $$$6$$$, $$$11$$$ и $$$18$$$. Обратите внимание, что это не единственный правильный ответ.</p><p>Во втором наборе входных данных вы всегда можете составить невырожденный треугольник.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="0220704291c95b1afa642a048642eed8"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="c6889f6e71c8e2115cd1aaac7ac10e576255ebde"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='0220704291c95b1afa642a048642eed8'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1398%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='0220704291c95b1afa642a048642eed8'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1398">Educational Codeforces Round 93 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='0220704291c95b1afa642a048642eed8'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1398/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Геометрия">
геометрия
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0220704291c95b1afa642a048642eed8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="699501"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0220704291c95b1afa642a048642eed8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="699501"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81410" title="Educational Codeforces Round 93 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11612:11613" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81506" title="Разбор Educational Codeforces Round 93" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11665:11666" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1398">Задачи</a></li>
<li><a
href="/contest/1398/submit">Отослать</a></li>
<li><a
href="/contest/1398/my">Мои посылки</a></li>
<li><a
href="/contest/1398/status">Статус</a></li>
<li><a
href="/contest/1398/hacks">Взломы</a></li>
<li><a
href="/contest/1398/standings">Положение</a></li>
<li><a
href="/contest/1398/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_977cfd2144680b62877618febd64eaac565b2f48">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Плохой треугольник</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a_1, a_2, \dots , a_n$$$, отсортированный в порядке неубывания ($$$a_i \le a_{i + 1})$$$. </p><p>Найдите три индекса $$$i$$$, $$$j$$$, $$$k$$$, таких что $$$1 \le i < j < k \le n$$$ и <span class="tex-font-style-bf">невозможно</span> создать невырожденный треугольник (треугольник с ненулевой площадью) со сторонами $$$a_i$$$, $$$a_j$$$ и $$$a_k$$$ (например, возможно создать невырожденный треугольник со сторонами $$$3$$$, $$$4$$$ и $$$5$$$, но невозможно со сторонами $$$3$$$, $$$4$$$ и $$$7$$$). Или определите, что не существует таких три индекса.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно число $$$n$$$ ($$$3 \le n \le 5 \cdot 10^4$$$) — длина массива $$$a$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$; $$$a_{i - 1} \le a_i$$$) — массив $$$a$$$.</p><p>Гарантируется, что сумма всех $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ в отдельной строке.</p><p>Если существует тройка индексов $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$), такая что <span class="tex-font-style-bf">невозможно</span> создать невырожденный треугольник (треугольник с ненулевой площадью) со сторонами $$$a_i$$$, $$$a_j$$$ и $$$a_k$$$, выведите эти три индекса в порядке возрастания. Если существует несколько ответов, выведите любой из них.</p><p>Иначе выведите <span class="tex-font-style-tt">-1</span>.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
7
4 6 11 11 15 18 20
4
10 10 10 11
3
1 1 1000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 6
-1
1 2 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных невозможно составить невырожденный треугольник со стронами $$$6$$$, $$$11$$$ и $$$18$$$. Обратите внимание, что это не единственный правильный ответ.</p><p>Во втором наборе входных данных вы всегда можете составить невырожденный треугольник.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:30</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a98a383a9d86',t:'MTY5NjY2NjE3MC4xODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"] | ||
1398B | 1398 | B | ru | B. Игра с удалением подстрок | <div class="problem-statement"><div class="header"><div class="title">B. Игра с удалением подстрок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в игру. У них есть бинарная строка $$$s$$$ (каждый символ бинарной строки — либо $$$0$$$, либо $$$1$$$). Алиса ходит первой, потом Боб, потом снова Алиса, и так далее.</p><p>В свой ход игрок должен выбрать несколько (не менее одного) <span class="tex-font-style-bf">последовательных одинаковых символов</span> в $$$s$$$ и удалить их.</p><p>Например, если текущая строка — $$$10110$$$, существует $$$6$$$ возможных ходов (удаляемые символы выделены жирным):</p><ol> <li> $$$\textbf{1}0110 \to 0110$$$; </li><li> $$$1\textbf{0}110 \to 1110$$$; </li><li> $$$10\textbf{1}10 \to 1010$$$; </li><li> $$$101\textbf{1}0 \to 1010$$$; </li><li> $$$10\textbf{11}0 \to 100$$$; </li><li> $$$1011\textbf{0} \to 1011$$$. </li></ol><p>После удаления символов те символы, которые стояли слева и справа от удаленного блока, становятся последовательными. Т. е. следующая последовательность операций возможна: $$$10\textbf{11}0 \to 1\textbf{00} \to 1$$$.</p><p>Игра заканчивается, когда строка становится пустой. Счет каждого игрока равен <span class="tex-font-style-bf">кол-ву символов $$$1$$$, которые он удалил</span>.</p><p>Каждый игрок хочет набрать максимально возможное количество очков. Посчитайте, сколько очков наберет Алиса.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$T$$$ ($$$1 \le T \le 500$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит одну бинарную строку $$$s$$$ ($$$1 \le |s| \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите ответ на него — счет Алисы в конце игры (количество символов $$$1$$$, которые она удалит).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
01111001
0000
111111
101010101
011011110111
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
0
6
3
6
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вопросы по поводу оптимальной стратегии будут игнорироваться.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="218a0dd69de981398cba708c26bd5a19"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="c6889f6e71c8e2115cd1aaac7ac10e576255ebde"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='218a0dd69de981398cba708c26bd5a19'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1398%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='218a0dd69de981398cba708c26bd5a19'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1398">Educational Codeforces Round 93 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='218a0dd69de981398cba708c26bd5a19'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1398/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди">
игры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='218a0dd69de981398cba708c26bd5a19'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="699502"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='218a0dd69de981398cba708c26bd5a19'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="699502"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81410" title="Educational Codeforces Round 93 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11612:11613" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81506" title="Разбор Educational Codeforces Round 93" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11665:11666" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1398">Задачи</a></li>
<li><a
href="/contest/1398/submit">Отослать</a></li>
<li><a
href="/contest/1398/my">Мои посылки</a></li>
<li><a
href="/contest/1398/status">Статус</a></li>
<li><a
href="/contest/1398/hacks">Взломы</a></li>
<li><a
href="/contest/1398/standings">Положение</a></li>
<li><a
href="/contest/1398/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_71221a19fef057d2e24a728b4161361b32cc38ed">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Игра с удалением подстрок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в игру. У них есть бинарная строка $$$s$$$ (каждый символ бинарной строки — либо $$$0$$$, либо $$$1$$$). Алиса ходит первой, потом Боб, потом снова Алиса, и так далее.</p><p>В свой ход игрок должен выбрать несколько (не менее одного) <span class="tex-font-style-bf">последовательных одинаковых символов</span> в $$$s$$$ и удалить их.</p><p>Например, если текущая строка — $$$10110$$$, существует $$$6$$$ возможных ходов (удаляемые символы выделены жирным):</p><ol> <li> $$$\textbf{1}0110 \to 0110$$$; </li><li> $$$1\textbf{0}110 \to 1110$$$; </li><li> $$$10\textbf{1}10 \to 1010$$$; </li><li> $$$101\textbf{1}0 \to 1010$$$; </li><li> $$$10\textbf{11}0 \to 100$$$; </li><li> $$$1011\textbf{0} \to 1011$$$. </li></ol><p>После удаления символов те символы, которые стояли слева и справа от удаленного блока, становятся последовательными. Т. е. следующая последовательность операций возможна: $$$10\textbf{11}0 \to 1\textbf{00} \to 1$$$.</p><p>Игра заканчивается, когда строка становится пустой. Счет каждого игрока равен <span class="tex-font-style-bf">кол-ву символов $$$1$$$, которые он удалил</span>.</p><p>Каждый игрок хочет набрать максимально возможное количество очков. Посчитайте, сколько очков наберет Алиса.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$T$$$ ($$$1 \le T \le 500$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит одну бинарную строку $$$s$$$ ($$$1 \le |s| \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите ответ на него — счет Алисы в конце игры (количество символов $$$1$$$, которые она удалит).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
01111001
0000
111111
101010101
011011110111
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
0
6
3
6
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вопросы по поводу оптимальной стратегии будут игнорироваться.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:31</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9934a067b83',t:'MTY5NjY2NjE3MS40OTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u0433\u0440\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*800"] | ||
1398C | 1398 | C | ru | C. Хорошие подотрезки | <div class="problem-statement"><div class="header"><div class="title">C. Хорошие подотрезки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a_1, a_2, \dots , a_n$$$, состоящий из чисел от $$$0$$$ до $$$9$$$. Подотрезок этого массива $$$a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$$$ хороший, если сумма чисел на этом подотрезке равна длине этого подотрезка ($$$\sum\limits_{i=l}^{r} a_i = r - l + 1$$$).</p><p>Например, если $$$a = [1, 2, 0]$$$, то есть $$$3$$$ хороших подотрезка: $$$a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$$$ и $$$a_{1 \dots 3} = [1, 2, 0]$$$.</p><p>Посчитайте количество хороших подотрезков массива $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — длина массива $$$a$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ десятичных цифр, где $$$i$$$-я цифра равна значению $$$a_i$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ — количество хороших подотрезков массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
3
120
5
11011
6
600005
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
6
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор входных данных рассмотрен в условии.</p><p>Во втором наборе входных данных есть $$$6$$$ хороших подотрезков: $$$a_{1 \dots 1}$$$, $$$a_{2 \dots 2}$$$, $$$a_{1 \dots 2}$$$, $$$a_{4 \dots 4}$$$, $$$a_{5 \dots 5}$$$ и $$$a_{4 \dots 5}$$$. </p><p>В третьем наборе входных данных есть только один хороший подотрезок: $$$a_{2 \dots 6}$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="add0db511e44ddf47651657e1fb6cee0"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="c6889f6e71c8e2115cd1aaac7ac10e576255ebde"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='add0db511e44ddf47651657e1fb6cee0'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1398%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='add0db511e44ddf47651657e1fb6cee0'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1398">Educational Codeforces Round 93 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='add0db511e44ddf47651657e1fb6cee0'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1398/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='add0db511e44ddf47651657e1fb6cee0'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="699503"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='add0db511e44ddf47651657e1fb6cee0'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="699503"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81410" title="Educational Codeforces Round 93 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11612:11613" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81506" title="Разбор Educational Codeforces Round 93" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11665:11666" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1398">Задачи</a></li>
<li><a
href="/contest/1398/submit">Отослать</a></li>
<li><a
href="/contest/1398/my">Мои посылки</a></li>
<li><a
href="/contest/1398/status">Статус</a></li>
<li><a
href="/contest/1398/hacks">Взломы</a></li>
<li><a
href="/contest/1398/standings">Положение</a></li>
<li><a
href="/contest/1398/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_8e935ad4d487ecf4ac10a7723fd023b32d32360d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Хорошие подотрезки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a_1, a_2, \dots , a_n$$$, состоящий из чисел от $$$0$$$ до $$$9$$$. Подотрезок этого массива $$$a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$$$ хороший, если сумма чисел на этом подотрезке равна длине этого подотрезка ($$$\sum\limits_{i=l}^{r} a_i = r - l + 1$$$).</p><p>Например, если $$$a = [1, 2, 0]$$$, то есть $$$3$$$ хороших подотрезка: $$$a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$$$ и $$$a_{1 \dots 3} = [1, 2, 0]$$$.</p><p>Посчитайте количество хороших подотрезков массива $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — длина массива $$$a$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ десятичных цифр, где $$$i$$$-я цифра равна значению $$$a_i$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ — количество хороших подотрезков массива $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
3
120
5
11011
6
600005
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
6
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор входных данных рассмотрен в условии.</p><p>Во втором наборе входных данных есть $$$6$$$ хороших подотрезков: $$$a_{1 \dots 1}$$$, $$$a_{2 \dots 2}$$$, $$$a_{1 \dots 2}$$$, $$$a_{4 \dots 4}$$$, $$$a_{5 \dots 5}$$$ и $$$a_{4 \dots 5}$$$. </p><p>В третьем наборе входных данных есть только один хороший подотрезок: $$$a_{2 \dots 6}$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:32</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a99b78771672',t:'MTY5NjY2NjE3Mi43NjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1600"] | ||
1398D | 1398 | D | ru | D. Цветные прямоугольники | <div class="problem-statement"><div class="header"><div class="title">D. Цветные прямоугольники</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Даны три мультимножества пар цветных палок: </p><ul> <li> $$$R$$$ пар красных палок, у первой пары длины равны $$$r_1$$$, у второй пары длины равны $$$r_2$$$, $$$\dots$$$, у $$$R$$$-й пары длины равны $$$r_R$$$; </li><li> $$$G$$$ пар зеленых палок, у первой пары длины равны $$$g_1$$$, у второй пары длины равны $$$g_2$$$, $$$\dots$$$, у $$$G$$$-й пары длины равны $$$g_G$$$; </li><li> $$$B$$$ пар синих палок, у первой пары длины равны $$$b_1$$$, у второй пары длины равны $$$b_2$$$, $$$\dots$$$, у $$$B$$$-й пары длины равны $$$b_B$$$. </li></ul><p>Вы собираете прямоугольники из этих пар палок следующим образом: </p><ol> <li> взять пару палок одного цвета; </li><li> взять пару палок другого цвета, отличного от первого; </li><li> прибавить площадь полученного прямоугольника к суммарной площади. </li></ol><p>В итоге получатся такие прямоугольники, что противоположные стороны у них одного цвета, а соседние стороны различных цветов.</p><p>Каждая пара палок может быть использована не более одного раза, некоторые пары можно не использовать. Не разрешается разбивать пару палок на отдельные палки.</p><p>Какую максимальную суммарную площадь можно получить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — количество пар красных палок, количество пар зеленых палок и количество пар синих палок.</p><p>Во второй строке записаны $$$R$$$ целых чисел $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — длины палок в каждой паре красных палок.</p><p>В третьей строке записаны $$$G$$$ целых чисел $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — длины палок в каждой паре зеленых палок.</p><p>В четвертой строке записаны $$$B$$$ целых чисел $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — длины палок в каждой паре синих палок.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите максимально возможную суммарную площадь построенных прямоугольников.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1 1 1
3
5
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
20
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 1 3
9 5
1
2 8 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
99
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 1 1
11 7 20 15 19 14 2 4 13 14
8
11
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
372
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно построить один из следующих прямоугольников: красный и зеленый со сторонами $$$3$$$ и $$$5$$$, красный и синий со сторонами $$$3$$$ и $$$4$$$ и зеленый и синий со сторонами $$$5$$$ и $$$4$$$. Лучшая площадь из них равна $$$4 \times 5 = 20$$$.</p><p>Во втором примере лучшие прямоугольники: красный/синий $$$9 \times 8$$$, красный/синий $$$5 \times 5$$$, зеленый/синий $$$2 \times 1$$$. Суммарная площадь равна $$$72 + 25 + 2 = 99$$$.</p><p>В третьем примере лучшие прямоугольники: красный/зеленый $$$19 \times 8$$$ и красный/синий $$$20 \times 11$$$. Суммарная площадь равна $$$152 + 220 = 372$$$. Обратите внимание, что больше прямоугольников нельзя построить, потому что не разрешается иметь обе взятые пары одного цвета.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="a9f526c6ba462579c36311fd96cf6038"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="c6889f6e71c8e2115cd1aaac7ac10e576255ebde"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='a9f526c6ba462579c36311fd96cf6038'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1398%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='a9f526c6ba462579c36311fd96cf6038'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1398">Educational Codeforces Round 93 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='a9f526c6ba462579c36311fd96cf6038'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1398/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a9f526c6ba462579c36311fd96cf6038'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="699504"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a9f526c6ba462579c36311fd96cf6038'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="699504"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81410" title="Educational Codeforces Round 93 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11612:11613" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81506" title="Разбор Educational Codeforces Round 93" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11665:11666" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1398">Задачи</a></li>
<li><a
href="/contest/1398/submit">Отослать</a></li>
<li><a
href="/contest/1398/my">Мои посылки</a></li>
<li><a
href="/contest/1398/status">Статус</a></li>
<li><a
href="/contest/1398/hacks">Взломы</a></li>
<li><a
href="/contest/1398/standings">Положение</a></li>
<li><a
href="/contest/1398/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_d6ed7c575d34df8d94ac3083f4eb96c68a3d7bcd">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Цветные прямоугольники</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Даны три мультимножества пар цветных палок: </p><ul> <li> $$$R$$$ пар красных палок, у первой пары длины равны $$$r_1$$$, у второй пары длины равны $$$r_2$$$, $$$\dots$$$, у $$$R$$$-й пары длины равны $$$r_R$$$; </li><li> $$$G$$$ пар зеленых палок, у первой пары длины равны $$$g_1$$$, у второй пары длины равны $$$g_2$$$, $$$\dots$$$, у $$$G$$$-й пары длины равны $$$g_G$$$; </li><li> $$$B$$$ пар синих палок, у первой пары длины равны $$$b_1$$$, у второй пары длины равны $$$b_2$$$, $$$\dots$$$, у $$$B$$$-й пары длины равны $$$b_B$$$. </li></ul><p>Вы собираете прямоугольники из этих пар палок следующим образом: </p><ol> <li> взять пару палок одного цвета; </li><li> взять пару палок другого цвета, отличного от первого; </li><li> прибавить площадь полученного прямоугольника к суммарной площади. </li></ol><p>В итоге получатся такие прямоугольники, что противоположные стороны у них одного цвета, а соседние стороны различных цветов.</p><p>Каждая пара палок может быть использована не более одного раза, некоторые пары можно не использовать. Не разрешается разбивать пару палок на отдельные палки.</p><p>Какую максимальную суммарную площадь можно получить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — количество пар красных палок, количество пар зеленых палок и количество пар синих палок.</p><p>Во второй строке записаны $$$R$$$ целых чисел $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — длины палок в каждой паре красных палок.</p><p>В третьей строке записаны $$$G$$$ целых чисел $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — длины палок в каждой паре зеленых палок.</p><p>В четвертой строке записаны $$$B$$$ целых чисел $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — длины палок в каждой паре синих палок.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите максимально возможную суммарную площадь построенных прямоугольников.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1 1 1
3
5
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
20
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 1 3
9 5
1
2 8 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
99
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 1 1
11 7 20 15 19 14 2 4 13 14
8
11
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
372
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно построить один из следующих прямоугольников: красный и зеленый со сторонами $$$3$$$ и $$$5$$$, красный и синий со сторонами $$$3$$$ и $$$4$$$ и зеленый и синий со сторонами $$$5$$$ и $$$4$$$. Лучшая площадь из них равна $$$4 \times 5 = 20$$$.</p><p>Во втором примере лучшие прямоугольники: красный/синий $$$9 \times 8$$$, красный/синий $$$5 \times 5$$$, зеленый/синий $$$2 \times 1$$$. Суммарная площадь равна $$$72 + 25 + 2 = 99$$$.</p><p>В третьем примере лучшие прямоугольники: красный/зеленый $$$19 \times 8$$$ и красный/синий $$$20 \times 11$$$. Суммарная площадь равна $$$152 + 220 = 372$$$. Обратите внимание, что больше прямоугольников нельзя построить, потому что не разрешается иметь обе взятые пары одного цвета.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:34</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9a37a1a9daa',t:'MTY5NjY2NjE3NC4xMDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"] | ||
1398E | 1398 | E | ru | E. Два типа заклинаний | <div class="problem-statement"><div class="header"><div class="title">E. Два типа заклинаний</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в компьютерную игру (да, опять). В этой игре он сражается с монстрами при помощи заклинаний.</p><p>Есть два типа заклинаний: <span class="tex-font-style-it">огненный шар</span> силы $$$x$$$ наносит $$$x$$$ урона монстру, а <span class="tex-font-style-it">молния</span> силы $$$y$$$ наносит $$$y$$$ урона монстру и <span class="tex-font-style-bf">удваивает</span> урон следующего заклинания. Каждое заклинание может быть использовано <span class="tex-font-style-bf">только один раз</span>, но Поликарп может применять их в любом порядке.</p><p>Например, предположим, что Поликарп знает три заклинания: огненный шар силы $$$5$$$, молнию силы $$$1$$$ и молнию силы $$$8$$$. Всего есть $$$6$$$ способов выбрать порядок заклинаний:</p><ul> <li> первое, второе, третье. В таком случае вы нанесете $$$5 + 1 + 2 \cdot 8 = 22$$$ урона; </li><li> первое, третье, второе. В таком случае вы нанесете $$$5 + 8 + 2 \cdot 1 = 15$$$ урона; </li><li> второе, первое, третье. В таком случае вы нанесете $$$1 + 2 \cdot 5 + 8 = 19$$$ урона; </li><li> второе, третье, первое. В таком случае вы нанесете $$$1 + 2 \cdot 8 + 2 \cdot 5 = 27$$$ урона; </li><li> третье, первое, второе. В таком случае вы нанесете $$$8 + 2 \cdot 5 + 1 = 19$$$ урона; </li><li> третье, второе, первое. В таком случае вы нанесете $$$8 + 2 \cdot 1 + 2 \cdot 5 = 20$$$ урона. </li></ul><p>Изначально Поликарп знает $$$0$$$ заклинаний. Его набор заклинаний меняется $$$n$$$ раз, каждый раз он либо учит новое заклинание, либо забывает старое. После каждого изменения выведите максимально количество урона, которое можно нанести при помощи имеющихся заклинаний.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество заклинаний в наборе.</p><p>Каждая из следующих $$$n$$$ строк содержит два числа $$$tp$$$ и $$$d$$$ ($$$0 \le tp_i \le 1$$$; $$$-10^9 \le d \le 10^9$$$; $$$d_i \neq 0$$$) — описание изменений. Если $$$tp_i$$$ равно $$$0$$$, Поликарп учит (или забывает) огненный шар, иначе он учит (или забывает) молнию.</p><p>Если $$$d_i > 0$$$, то Поликарп учит заклинание силы $$$d_i$$$. Иначе, Поликарп забывает заклинание силы $$$-d_i$$$, и гарантируется, что он знал это заклинание до этого.</p><p>Гарантируется, что после каждого изменения все силы заклинаний различны (Поликарп не может знать одновременно два заклинания одинаковой силы).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>После каждого изменения выведите максимально количество урона, которое можно нанести при помощи имеющихся заклинаний.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
1 5
0 10
1 -5
0 5
1 11
0 -10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
25
10
15
36
21
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="99eb755e27335c7bd628d115b8b21b86"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="c6889f6e71c8e2115cd1aaac7ac10e576255ebde"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='99eb755e27335c7bd628d115b8b21b86'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1398%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='99eb755e27335c7bd628d115b8b21b86'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1398">Educational Codeforces Round 93 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='99eb755e27335c7bd628d115b8b21b86'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1398/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='99eb755e27335c7bd628d115b8b21b86'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="699505"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='99eb755e27335c7bd628d115b8b21b86'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="699505"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81410" title="Educational Codeforces Round 93 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11612:11613" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81506" title="Разбор Educational Codeforces Round 93" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11665:11666" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1398">Задачи</a></li>
<li><a
href="/contest/1398/submit">Отослать</a></li>
<li><a
href="/contest/1398/my">Мои посылки</a></li>
<li><a
href="/contest/1398/status">Статус</a></li>
<li><a
href="/contest/1398/hacks">Взломы</a></li>
<li><a
href="/contest/1398/standings">Положение</a></li>
<li><a
href="/contest/1398/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_09baf265e14d23ac6f7433f2c6ae7376bdf7597d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Два типа заклинаний</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в компьютерную игру (да, опять). В этой игре он сражается с монстрами при помощи заклинаний.</p><p>Есть два типа заклинаний: <span class="tex-font-style-it">огненный шар</span> силы $$$x$$$ наносит $$$x$$$ урона монстру, а <span class="tex-font-style-it">молния</span> силы $$$y$$$ наносит $$$y$$$ урона монстру и <span class="tex-font-style-bf">удваивает</span> урон следующего заклинания. Каждое заклинание может быть использовано <span class="tex-font-style-bf">только один раз</span>, но Поликарп может применять их в любом порядке.</p><p>Например, предположим, что Поликарп знает три заклинания: огненный шар силы $$$5$$$, молнию силы $$$1$$$ и молнию силы $$$8$$$. Всего есть $$$6$$$ способов выбрать порядок заклинаний:</p><ul> <li> первое, второе, третье. В таком случае вы нанесете $$$5 + 1 + 2 \cdot 8 = 22$$$ урона; </li><li> первое, третье, второе. В таком случае вы нанесете $$$5 + 8 + 2 \cdot 1 = 15$$$ урона; </li><li> второе, первое, третье. В таком случае вы нанесете $$$1 + 2 \cdot 5 + 8 = 19$$$ урона; </li><li> второе, третье, первое. В таком случае вы нанесете $$$1 + 2 \cdot 8 + 2 \cdot 5 = 27$$$ урона; </li><li> третье, первое, второе. В таком случае вы нанесете $$$8 + 2 \cdot 5 + 1 = 19$$$ урона; </li><li> третье, второе, первое. В таком случае вы нанесете $$$8 + 2 \cdot 1 + 2 \cdot 5 = 20$$$ урона. </li></ul><p>Изначально Поликарп знает $$$0$$$ заклинаний. Его набор заклинаний меняется $$$n$$$ раз, каждый раз он либо учит новое заклинание, либо забывает старое. После каждого изменения выведите максимально количество урона, которое можно нанести при помощи имеющихся заклинаний.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество заклинаний в наборе.</p><p>Каждая из следующих $$$n$$$ строк содержит два числа $$$tp$$$ и $$$d$$$ ($$$0 \le tp_i \le 1$$$; $$$-10^9 \le d \le 10^9$$$; $$$d_i \neq 0$$$) — описание изменений. Если $$$tp_i$$$ равно $$$0$$$, Поликарп учит (или забывает) огненный шар, иначе он учит (или забывает) молнию.</p><p>Если $$$d_i > 0$$$, то Поликарп учит заклинание силы $$$d_i$$$. Иначе, Поликарп забывает заклинание силы $$$-d_i$$$, и гарантируется, что он знал это заклинание до этого.</p><p>Гарантируется, что после каждого изменения все силы заклинаний различны (Поликарп не может знать одновременно два заклинания одинаковой силы).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>После каждого изменения выведите максимально количество урона, которое можно нанести при помощи имеющихся заклинаний.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
1 5
0 10
1 -5
0 5
1 11
0 -10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
25
10
15
36
21
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:35</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9abfdf003eb',t:'MTY5NjY2NjE3NS42MjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"] | ||
1398F | 1398 | F | ru | F. Спорные раунды | <div class="problem-statement"><div class="header"><div class="title">F. Спорные раунды</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в игру. Игра состоит из нескольких сетов, и каждый сет состоит из нескольких раундов. Каждый раунд выиграл либо Боб, либо Алиса, и сет считается завершенным, когда один из игроков выиграл $$$x$$$ раундов подряд. Например, если Боб выиграл пять раундов подряд и $$$x = 2$$$, то завершилось два сета.</p><p>Вы знаете, что Алиса и Боб уже сыграли $$$n$$$ раундов и вы знаете результаты нескольких раундов. Для каждого $$$x$$$ от $$$1$$$ до $$$n$$$, посчитайте максимальное количество сетов, которое могло быть завершено, если сет считается завершенным, когда один из игроков выиграл $$$x$$$ раундов подряд. Если последний сет не завершен — то учитывать его не нужно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — количество раундов.</p><p>Вторая строка содержит строку $$$s$$$ длины $$$n$$$ — описание раундов. Если $$$i$$$-й элемент строки равен <span class="tex-font-style-tt">0</span>, то Алиса выиграла $$$i$$$-й раунд; если равен <span class="tex-font-style-tt">1</span> — то Боб выиграл $$$i$$$-й раунд, а если равен <span class="tex-font-style-tt">?</span> — то вы не знаете, кто выиграл $$$i$$$-й раунд.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$n$$$ чисел. $$$i$$$-е должно быть равно максимальному количество сетов, которое могло быть завершено, если сет считается завершенным когда один из игроков выиграл $$$i$$$ раундов подряд.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
11?000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6 3 2 1 0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
01?01
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5 1 0 0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
12
???1??????1?
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12 6 4 3 2 2 1 1 1 1 1 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый набор входных данных:</p><ul> <li> если $$$x = 1$$$ и $$$s = 110000$$$ или $$$s = 111000$$$ то есть шесть завершенных сетов; </li><li> если $$$x = 2$$$ и $$$s = 110000$$$ то есть три завершенных сета; </li><li> если $$$x = 3$$$ и $$$s = 111000$$$ то есть два завершенных сета; </li><li> если $$$x = 4$$$ и $$$s = 110000$$$ то есть один завершенный сет; </li><li> если $$$x = 5$$$ то завершенных сетов нет; </li><li> если $$$x = 6$$$ то завершенных сетов нет. </li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="350c56bd75fb39c2c5db12c62a5db30f"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - F - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="c6889f6e71c8e2115cd1aaac7ac10e576255ebde"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='350c56bd75fb39c2c5db12c62a5db30f'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1398%2Fproblem%2FF%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='350c56bd75fb39c2c5db12c62a5db30f'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1398">Educational Codeforces Round 93 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='350c56bd75fb39c2c5db12c62a5db30f'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1398/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='350c56bd75fb39c2c5db12c62a5db30f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="699506"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='350c56bd75fb39c2c5db12c62a5db30f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="699506"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81410" title="Educational Codeforces Round 93 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11612:11613" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81506" title="Разбор Educational Codeforces Round 93" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11665:11666" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1398">Задачи</a></li>
<li><a
href="/contest/1398/submit">Отослать</a></li>
<li><a
href="/contest/1398/my">Мои посылки</a></li>
<li><a
href="/contest/1398/status">Статус</a></li>
<li><a
href="/contest/1398/hacks">Взломы</a></li>
<li><a
href="/contest/1398/standings">Положение</a></li>
<li><a
href="/contest/1398/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="F" data-uuid="ps_0380adde24a2a5d0f77eae5192075d1e8e18e01c">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Спорные раунды</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в игру. Игра состоит из нескольких сетов, и каждый сет состоит из нескольких раундов. Каждый раунд выиграл либо Боб, либо Алиса, и сет считается завершенным, когда один из игроков выиграл $$$x$$$ раундов подряд. Например, если Боб выиграл пять раундов подряд и $$$x = 2$$$, то завершилось два сета.</p><p>Вы знаете, что Алиса и Боб уже сыграли $$$n$$$ раундов и вы знаете результаты нескольких раундов. Для каждого $$$x$$$ от $$$1$$$ до $$$n$$$, посчитайте максимальное количество сетов, которое могло быть завершено, если сет считается завершенным, когда один из игроков выиграл $$$x$$$ раундов подряд. Если последний сет не завершен — то учитывать его не нужно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^6$$$) — количество раундов.</p><p>Вторая строка содержит строку $$$s$$$ длины $$$n$$$ — описание раундов. Если $$$i$$$-й элемент строки равен <span class="tex-font-style-tt">0</span>, то Алиса выиграла $$$i$$$-й раунд; если равен <span class="tex-font-style-tt">1</span> — то Боб выиграл $$$i$$$-й раунд, а если равен <span class="tex-font-style-tt">?</span> — то вы не знаете, кто выиграл $$$i$$$-й раунд.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$n$$$ чисел. $$$i$$$-е должно быть равно максимальному количество сетов, которое могло быть завершено, если сет считается завершенным когда один из игроков выиграл $$$i$$$ раундов подряд.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
11?000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6 3 2 1 0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
01?01
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5 1 0 0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
12
???1??????1?
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12 6 4 3 2 2 1 1 1 1 1 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый набор входных данных:</p><ul> <li> если $$$x = 1$$$ и $$$s = 110000$$$ или $$$s = 111000$$$ то есть шесть завершенных сетов; </li><li> если $$$x = 2$$$ и $$$s = 110000$$$ то есть три завершенных сета; </li><li> если $$$x = 3$$$ и $$$s = 111000$$$ то есть два завершенных сета; </li><li> если $$$x = 4$$$ и $$$s = 110000$$$ то есть один завершенный сет; </li><li> если $$$x = 5$$$ то завершенных сетов нет; </li><li> если $$$x = 6$$$ то завершенных сетов нет. </li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:36</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9b548e49d87',t:'MTY5NjY2NjE3Ny4wMTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2500"] | ||
1398G | 1398 | G | ru | G. Соревнования по бегу | <div class="problem-statement"><div class="header"><div class="title">G. Соревнования по бегу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Скоро начинаются соревнования по бегу. Стадион, на котором планируется их проводить, может быть представлен несколькими отрезками на координатной плоскости:</p><ul> <li> два горизонтальных отрезка: один соединяет точки $$$(0, 0)$$$ и $$$(x, 0)$$$, другой соединяет точки $$$(0, y)$$$ и $$$(x, y)$$$; </li><li> $$$n + 1$$$ вертикальный отрезок, пронумерованные от $$$0$$$ до $$$n$$$. $$$i$$$-й отрезок соединяет точки $$$(a_i, 0)$$$ и $$$(a_i, y)$$$; $$$0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x$$$. </li></ul><p>Например, на данной картинке изображен стадион с $$$x = 10$$$, $$$y = 5$$$, $$$n = 3$$$ и $$$a = [0, 3, 5, 10]$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8fb878ad4c8c901fac995b7f3944fbbd9249bfd0.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Назовем <span class="tex-font-style-it">кругом</span> такой маршрут, который проходит по отрезкам, начинается и заканчивается в одно точке и никогда не пересекается сам с собой (единственные две совпадающие точки круга — это стартовая и финишная). Длина круга — это суммарное расстояние, пройденное по нему. Например, красный путь на картинке, обозначающей стадион — это круг длиной $$$24$$$.</p><p>Соревнование пройдет в $$$q$$$ этапов. На $$$i$$$-м этапе длина круга равна $$$l_i$$$, поэтому организаторам предстоит найти круг для каждого этапа такой, что его длина является <span class="tex-font-style-bf">делителем $$$l_i$$$</span>. Организаторы не хотят выбирать слишком маленькие круги, поэтому на каждом этапе требуется найти максимальный (по длине) подходящий круг.</p><p>Помогите организаторам вычислить максимально возможные длины кругов для всех этапов. Другими словами, для каждого $$$l_i$$$ найдите максимальное целое число $$$L$$$ такое, что $$$l_i \bmod L = 0$$$, и существует круг с длиной <span class="tex-font-style-bf">ровно</span> $$$L$$$.</p><p>Если невозможно выбрать такой круг, то выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$x$$$ и $$$y$$$ ($$$1 \le n, x, y \le 2 \cdot 10^5$$$, $$$n \le x$$$).</p><p>Во второй строке записано $$$n + 1$$$ целое число $$$a_0$$$, $$$a_1$$$, ..., $$$a_n$$$ ($$$0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x$$$).</p><p>В третьей строке записано одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — количество этапов.</p><p>В четвертой строке записаны $$$q$$$ <span class="tex-font-style-bf">четных</span> целых чисел $$$l_1$$$, $$$l_2$$$, ..., $$$l_q$$$ ($$$4 \le l_i \le 10^6$$$) — длины этапов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел. $$$i$$$-е число должно быть равно максимально возможной длине круга для $$$i$$$-го этапа, или $$$-1$$$, если невозможно выбрать круг для данного этапа.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 10 5
0 3 5 10
6
24 30 14 16 18 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
24 30 14 16 -1 -1 </pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="5ff2496e90c117ad1cf9bef169bc759c"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - G - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="c6889f6e71c8e2115cd1aaac7ac10e576255ebde"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - G - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='5ff2496e90c117ad1cf9bef169bc759c'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1398%2Fproblem%2FG%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='5ff2496e90c117ad1cf9bef169bc759c'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1398">Educational Codeforces Round 93 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='5ff2496e90c117ad1cf9bef169bc759c'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1398/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Битовые маски">
битмаски
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье">
бпф
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5ff2496e90c117ad1cf9bef169bc759c'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="699507"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5ff2496e90c117ad1cf9bef169bc759c'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="699507"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81410" title="Educational Codeforces Round 93 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11612:11613" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81506" title="Разбор Educational Codeforces Round 93" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11665:11666" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1398">Задачи</a></li>
<li><a
href="/contest/1398/submit">Отослать</a></li>
<li><a
href="/contest/1398/my">Мои посылки</a></li>
<li><a
href="/contest/1398/status">Статус</a></li>
<li><a
href="/contest/1398/hacks">Взломы</a></li>
<li><a
href="/contest/1398/standings">Положение</a></li>
<li><a
href="/contest/1398/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="G" data-uuid="ps_c706d8fb89bc90e73569401ec1bb4d27c531b3e9">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Соревнования по бегу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Скоро начинаются соревнования по бегу. Стадион, на котором планируется их проводить, может быть представлен несколькими отрезками на координатной плоскости:</p><ul> <li> два горизонтальных отрезка: один соединяет точки $$$(0, 0)$$$ и $$$(x, 0)$$$, другой соединяет точки $$$(0, y)$$$ и $$$(x, y)$$$; </li><li> $$$n + 1$$$ вертикальный отрезок, пронумерованные от $$$0$$$ до $$$n$$$. $$$i$$$-й отрезок соединяет точки $$$(a_i, 0)$$$ и $$$(a_i, y)$$$; $$$0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x$$$. </li></ul><p>Например, на данной картинке изображен стадион с $$$x = 10$$$, $$$y = 5$$$, $$$n = 3$$$ и $$$a = [0, 3, 5, 10]$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8fb878ad4c8c901fac995b7f3944fbbd9249bfd0.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Назовем <span class="tex-font-style-it">кругом</span> такой маршрут, который проходит по отрезкам, начинается и заканчивается в одно точке и никогда не пересекается сам с собой (единственные две совпадающие точки круга — это стартовая и финишная). Длина круга — это суммарное расстояние, пройденное по нему. Например, красный путь на картинке, обозначающей стадион — это круг длиной $$$24$$$.</p><p>Соревнование пройдет в $$$q$$$ этапов. На $$$i$$$-м этапе длина круга равна $$$l_i$$$, поэтому организаторам предстоит найти круг для каждого этапа такой, что его длина является <span class="tex-font-style-bf">делителем $$$l_i$$$</span>. Организаторы не хотят выбирать слишком маленькие круги, поэтому на каждом этапе требуется найти максимальный (по длине) подходящий круг.</p><p>Помогите организаторам вычислить максимально возможные длины кругов для всех этапов. Другими словами, для каждого $$$l_i$$$ найдите максимальное целое число $$$L$$$ такое, что $$$l_i \bmod L = 0$$$, и существует круг с длиной <span class="tex-font-style-bf">ровно</span> $$$L$$$.</p><p>Если невозможно выбрать такой круг, то выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$x$$$ и $$$y$$$ ($$$1 \le n, x, y \le 2 \cdot 10^5$$$, $$$n \le x$$$).</p><p>Во второй строке записано $$$n + 1$$$ целое число $$$a_0$$$, $$$a_1$$$, ..., $$$a_n$$$ ($$$0 = a_0 < a_1 < a_2 < \dots < a_{n - 1} < a_n = x$$$).</p><p>В третьей строке записано одно целое число $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — количество этапов.</p><p>В четвертой строке записаны $$$q$$$ <span class="tex-font-style-bf">четных</span> целых чисел $$$l_1$$$, $$$l_2$$$, ..., $$$l_q$$$ ($$$4 \le l_i \le 10^6$$$) — длины этапов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ целых чисел. $$$i$$$-е число должно быть равно максимально возможной длине круга для $$$i$$$-го этапа, или $$$-1$$$, если невозможно выбрать круг для данного этапа.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 10 5
0 3 5 10
6
24 30 14 16 18 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
24 30 14 16 -1 -1 </pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=G]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:38</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9be2f267b73',t:'MTY5NjY2NjE3OC40NjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0411\u044b\u0441\u0442\u0440\u043e\u0435 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0424\u0443\u0440\u044c\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0431\u043f\u0444", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2600"] | ||
1399A | 1399 | A | ru | A. Удалить наименьшее | <div class="problem-statement"><div class="header"><div class="title">A. Удалить наименьшее</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$, состоящий из $$$n$$$ положительных (больших нуля) целых чисел.</p><p>За один ход вы можете выбрать два индекса $$$i$$$ и $$$j$$$ ($$$i \ne j$$$) таких, что абсолютная разность между $$$a_i$$$ и $$$a_j$$$ не превосходит единицу ($$$|a_i - a_j| \le 1$$$), и удалить наименьший из этих двух элементов. Если два элемента равны, вы можете удалить любой из них (но только один).</p><p>Ваша задача — определить, возможно ли получить массив, состоящий <span class="tex-font-style-bf">только из одного элемента</span>, применив несколько (возможно, ноль) таких ходов, или нет.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 50$$$) — длину $$$a$$$. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), где $$$a_i$$$ — $$$i$$$-й элемент $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: «<span class="tex-font-style-tt">YES</span>», если возможно получить массив, состоящий <span class="tex-font-style-bf">только из одного элемента</span>, применив несколько (возможно, ноль) ходов, описанных в условии задачи, или «<span class="tex-font-style-tt">NO</span>» в обратном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
3
1 2 2
4
5 5 5 5
3
1 2 4
4
1 3 4 4
1
100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
NO
NO
YES
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера мы можем применить следующую последовательность ходов:</p><ul> <li> выбрать $$$i=1$$$ и $$$j=3$$$, а затем удалить $$$a_i$$$ (таким образом, $$$a$$$ превратится в $$$[2; 2]$$$); </li><li> выбрать $$$i=1$$$ и $$$j=2$$$, а затем удалить $$$a_j$$$ (таким образом, $$$a$$$ превратится в $$$[2]$$$). </li></ul><p>Во втором наборе тестовых данных примера мы можем выбирать любые возможные $$$i$$$ и $$$j$$$ в течение любого хода и удалять любой элемент из пары.</p><p>В третьем наборе тестовых данных примера не существует способа избавиться от $$$2$$$ и $$$4$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="e9985a4402eac722594176ac7608ba75"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8bd3b097330f547caf8a7ddf861f45406ad15a1b"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='e9985a4402eac722594176ac7608ba75'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1399%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='e9985a4402eac722594176ac7608ba75'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1399">Codeforces Round 661 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='e9985a4402eac722594176ac7608ba75'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1399/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e9985a4402eac722594176ac7608ba75'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="691716"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e9985a4402eac722594176ac7608ba75'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="691716"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81018" title="Codeforces Round #661 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11535:11536" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81082" title="81082" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11545:11546" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1399">Задачи</a></li>
<li><a
href="/contest/1399/submit">Отослать</a></li>
<li><a
href="/contest/1399/my">Мои посылки</a></li>
<li><a
href="/contest/1399/status">Статус</a></li>
<li><a
href="/contest/1399/hacks">Взломы</a></li>
<li><a
href="/contest/1399/standings">Положение</a></li>
<li><a
href="/contest/1399/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_e2078822c556c6c5e1d9aa9bb0404165e7017036">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Удалить наименьшее</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$, состоящий из $$$n$$$ положительных (больших нуля) целых чисел.</p><p>За один ход вы можете выбрать два индекса $$$i$$$ и $$$j$$$ ($$$i \ne j$$$) таких, что абсолютная разность между $$$a_i$$$ и $$$a_j$$$ не превосходит единицу ($$$|a_i - a_j| \le 1$$$), и удалить наименьший из этих двух элементов. Если два элемента равны, вы можете удалить любой из них (но только один).</p><p>Ваша задача — определить, возможно ли получить массив, состоящий <span class="tex-font-style-bf">только из одного элемента</span>, применив несколько (возможно, ноль) таких ходов, или нет.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 50$$$) — длину $$$a$$$. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), где $$$a_i$$$ — $$$i$$$-й элемент $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: «<span class="tex-font-style-tt">YES</span>», если возможно получить массив, состоящий <span class="tex-font-style-bf">только из одного элемента</span>, применив несколько (возможно, ноль) ходов, описанных в условии задачи, или «<span class="tex-font-style-tt">NO</span>» в обратном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
3
1 2 2
4
5 5 5 5
3
1 2 4
4
1 3 4 4
1
100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
NO
NO
YES
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера мы можем применить следующую последовательность ходов:</p><ul> <li> выбрать $$$i=1$$$ и $$$j=3$$$, а затем удалить $$$a_i$$$ (таким образом, $$$a$$$ превратится в $$$[2; 2]$$$); </li><li> выбрать $$$i=1$$$ и $$$j=2$$$, а затем удалить $$$a_j$$$ (таким образом, $$$a$$$ превратится в $$$[2]$$$). </li></ul><p>Во втором наборе тестовых данных примера мы можем выбирать любые возможные $$$i$$$ и $$$j$$$ в течение любого хода и удалять любой элемент из пары.</p><p>В третьем наборе тестовых данных примера не существует способа избавиться от $$$2$$$ и $$$4$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:39</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9c70a1415ee',t:'MTY5NjY2NjE3OS44NzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*800"] | ||
1399B | 1399 | B | ru | B. Уравнивание подарков | <div class="problem-statement"><div class="header"><div class="title">B. Уравнивание подарков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть $$$n$$$ подарков, и вы хотите подарить все эти подарки детям. Конечно же, вам не хочется кого-то обидеть, поэтому все подарки должны быть равны между собой. $$$i$$$-й подарок состоит из $$$a_i$$$ конфет и $$$b_i$$$ апельсинов.</p><p>За один ход вы можете выбрать некоторый подарок $$$1 \le i \le n$$$ и совершить одно из следующих действий:</p><ul> <li> съесть ровно <span class="tex-font-style-bf">одну конфету</span> из этого подарка (уменьшить $$$a_i$$$ на один); </li><li> съесть ровно <span class="tex-font-style-bf">один апельсин</span> из этого подарка (уменьшить $$$b_i$$$ на один); </li><li> съесть ровно <span class="tex-font-style-bf">одну конфету</span> и ровно <span class="tex-font-style-bf">один апельсин</span> из этого подарка (уменьшить и $$$a_i$$$, и $$$b_i$$$ на один). </li></ul><p>Разумеется, вы не можете съесть конфету или апельсин, если их нет в подарке (поэтому ни $$$a_i$$$, ни $$$b_i$$$ не могут стать меньше нуля).</p><p>Как было сказано выше, все подарки должны быть равны. Это означает, что после некоторой последовательности ходов должны быть выполнены следующие два условия: $$$a_1 = a_2 = \dots = a_n$$$ и $$$b_1 = b_2 = \dots = b_n$$$ (и равенство $$$a_i$$$ и $$$b_i$$$ <span class="tex-font-style-bf">не является необходимым</span>).</p><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое, чтобы уравнять все заданные подарки.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 50$$$) — количество подарков. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), где $$$a_i$$$ — количество конфет в $$$i$$$-м подарке. Третья строка набора тестовых данных содержит $$$n$$$ целых чисел $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), где $$$b_i$$$ — количество апельсинов в $$$i$$$-м подарке.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число: <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое, чтобы уравнять все заданные подарки.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
3
3 5 6
3 2 3
5
1 2 3 4 5
5 4 3 2 1
3
1 1 1
2 2 2
6
1 1000000000 1000000000 1000000000 1000000000 1000000000
1 1 1 1 1 1
3
10 12 8
7 5 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
16
0
4999999995
7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера мы можем выполнить следующую последовательность ходов:</p><ul> <li> выбрать первый подарок и съесть один апельсин из него, таким образом $$$a = [3, 5, 6]$$$ и $$$b = [2, 2, 3]$$$; </li><li> выбрать второй подарок и съесть одну конфету из него, таким образом $$$a = [3, 4, 6]$$$ и $$$b = [2, 2, 3]$$$; </li><li> выбрать второй подарок и съесть одну конфету из него, таким образом $$$a = [3, 3, 6]$$$ и $$$b = [2, 2, 3]$$$; </li><li> выбрать третий подарок и съесть одну конфету и один апельсин из него, таким образом $$$a = [3, 3, 5]$$$ и $$$b = [2, 2, 2]$$$; </li><li> выбрать третий подарок и съесть одну конфету из него, таким образом $$$a = [3, 3, 4]$$$ и $$$b = [2, 2, 2]$$$; </li><li> выбрать третий подарок и съесть одну конфету из него, таким образом $$$a = [3, 3, 3]$$$ и $$$b = [2, 2, 2]$$$. </li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="bc6dfc78c952167416df0ed04e297c09"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8bd3b097330f547caf8a7ddf861f45406ad15a1b"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='bc6dfc78c952167416df0ed04e297c09'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1399%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='bc6dfc78c952167416df0ed04e297c09'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1399">Codeforces Round 661 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='bc6dfc78c952167416df0ed04e297c09'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1399/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bc6dfc78c952167416df0ed04e297c09'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="691717"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bc6dfc78c952167416df0ed04e297c09'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="691717"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81018" title="Codeforces Round #661 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11535:11536" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81082" title="81082" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11545:11546" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1399">Задачи</a></li>
<li><a
href="/contest/1399/submit">Отослать</a></li>
<li><a
href="/contest/1399/my">Мои посылки</a></li>
<li><a
href="/contest/1399/status">Статус</a></li>
<li><a
href="/contest/1399/hacks">Взломы</a></li>
<li><a
href="/contest/1399/standings">Положение</a></li>
<li><a
href="/contest/1399/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_bc499fff910f19acd20c700d73ab1bd56c038672">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Уравнивание подарков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть $$$n$$$ подарков, и вы хотите подарить все эти подарки детям. Конечно же, вам не хочется кого-то обидеть, поэтому все подарки должны быть равны между собой. $$$i$$$-й подарок состоит из $$$a_i$$$ конфет и $$$b_i$$$ апельсинов.</p><p>За один ход вы можете выбрать некоторый подарок $$$1 \le i \le n$$$ и совершить одно из следующих действий:</p><ul> <li> съесть ровно <span class="tex-font-style-bf">одну конфету</span> из этого подарка (уменьшить $$$a_i$$$ на один); </li><li> съесть ровно <span class="tex-font-style-bf">один апельсин</span> из этого подарка (уменьшить $$$b_i$$$ на один); </li><li> съесть ровно <span class="tex-font-style-bf">одну конфету</span> и ровно <span class="tex-font-style-bf">один апельсин</span> из этого подарка (уменьшить и $$$a_i$$$, и $$$b_i$$$ на один). </li></ul><p>Разумеется, вы не можете съесть конфету или апельсин, если их нет в подарке (поэтому ни $$$a_i$$$, ни $$$b_i$$$ не могут стать меньше нуля).</p><p>Как было сказано выше, все подарки должны быть равны. Это означает, что после некоторой последовательности ходов должны быть выполнены следующие два условия: $$$a_1 = a_2 = \dots = a_n$$$ и $$$b_1 = b_2 = \dots = b_n$$$ (и равенство $$$a_i$$$ и $$$b_i$$$ <span class="tex-font-style-bf">не является необходимым</span>).</p><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое, чтобы уравнять все заданные подарки.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 50$$$) — количество подарков. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), где $$$a_i$$$ — количество конфет в $$$i$$$-м подарке. Третья строка набора тестовых данных содержит $$$n$$$ целых чисел $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), где $$$b_i$$$ — количество апельсинов в $$$i$$$-м подарке.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число: <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое, чтобы уравнять все заданные подарки.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
3
3 5 6
3 2 3
5
1 2 3 4 5
5 4 3 2 1
3
1 1 1
2 2 2
6
1 1000000000 1000000000 1000000000 1000000000 1000000000
1 1 1 1 1 1
3
10 12 8
7 5 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
16
0
4999999995
7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера мы можем выполнить следующую последовательность ходов:</p><ul> <li> выбрать первый подарок и съесть один апельсин из него, таким образом $$$a = [3, 5, 6]$$$ и $$$b = [2, 2, 3]$$$; </li><li> выбрать второй подарок и съесть одну конфету из него, таким образом $$$a = [3, 4, 6]$$$ и $$$b = [2, 2, 3]$$$; </li><li> выбрать второй подарок и съесть одну конфету из него, таким образом $$$a = [3, 3, 6]$$$ и $$$b = [2, 2, 3]$$$; </li><li> выбрать третий подарок и съесть одну конфету и один апельсин из него, таким образом $$$a = [3, 3, 5]$$$ и $$$b = [2, 2, 2]$$$; </li><li> выбрать третий подарок и съесть одну конфету из него, таким образом $$$a = [3, 3, 4]$$$ и $$$b = [2, 2, 2]$$$; </li><li> выбрать третий подарок и съесть одну конфету из него, таким образом $$$a = [3, 3, 3]$$$ и $$$b = [2, 2, 2]$$$. </li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:41</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9cffe4716f4',t:'MTY5NjY2NjE4MS4yNTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*800"] | ||
1399C | 1399 | C | ru | C. Лодочное соревнование | <div class="problem-statement"><div class="header"><div class="title">C. Лодочное соревнование</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть $$$n$$$ людей, желающих принять участие в лодочном соревновании. Вес $$$i$$$-го участника равен $$$w_i$$$. Принять участие могут только команды, состоящие из <span class="tex-font-style-bf">двух</span> человек. Как организатор вы считаете честным допустить к соревнованию только команды <span class="tex-font-style-bf">с одинаковым суммарным весом</span>.</p><p>Таким образом, для $$$k$$$ команд $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\dots$$$, $$$(a_k, b_k)$$$, где $$$a_i$$$ — вес первого участника $$$i$$$-й команды, а $$$b_i$$$ — вес второго участника $$$i$$$-й команды, должно выполняться условие $$$a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$$$, где $$$s$$$ — суммарный вес для <span class="tex-font-style-bf">каждой</span> команды.</p><p>Ваша задача — выбрать такое число $$$s$$$, что количество команд, которые могут быть созданы, <span class="tex-font-style-bf">максимально</span> возможное. Обратите внимание: каждый участник может состоять <span class="tex-font-style-bf">не более чем в одной</span> команде.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 50$$$) — количество участников. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le n$$$), где $$$w_i$$$ — вес $$$i$$$-го участника.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число $$$k$$$: <span class="tex-font-style-bf">максимальное</span> число команд, которые могут быть составлены при суммарном весе участников в команде, равном $$$s$$$, если выбирать $$$s$$$ оптимально.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
5
1 2 3 4 5
8
6 6 6 6 6 6 8 8
8
1 2 2 1 2 1 1 2
3
1 3 3
6
1 1 3 4 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
4
1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=6$$$. Тогда первая лодка будет использоваться участниками $$$1$$$ и $$$5$$$, а вторая лодка — участниками $$$2$$$ и $$$4$$$ (индексы совпадают с весами).</p><p>Во втором наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=12$$$. Тогда первые $$$6$$$ участников смогут образовать $$$3$$$ пары.</p><p>В третьем наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=3$$$. Ответ равен $$$4$$$, потому что у нас есть $$$4$$$ участника с весом $$$1$$$ и $$$4$$$ участника с весом $$$2$$$.</p><p>В четвертом наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=4$$$ или $$$s=6$$$.</p><p>В пятом наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=3$$$. Заметьте, что участник с весом $$$3$$$ не может использовать лодку, потому что для него в списке нет подходящей пары.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="cff197ec297bd8ebe50849cffed7bd1d"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8bd3b097330f547caf8a7ddf861f45406ad15a1b"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='cff197ec297bd8ebe50849cffed7bd1d'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1399%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='cff197ec297bd8ebe50849cffed7bd1d'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1399">Codeforces Round 661 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='cff197ec297bd8ebe50849cffed7bd1d'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1399/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cff197ec297bd8ebe50849cffed7bd1d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="691718"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cff197ec297bd8ebe50849cffed7bd1d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="691718"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81018" title="Codeforces Round #661 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11535:11536" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81082" title="81082" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11545:11546" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1399">Задачи</a></li>
<li><a
href="/contest/1399/submit">Отослать</a></li>
<li><a
href="/contest/1399/my">Мои посылки</a></li>
<li><a
href="/contest/1399/status">Статус</a></li>
<li><a
href="/contest/1399/hacks">Взломы</a></li>
<li><a
href="/contest/1399/standings">Положение</a></li>
<li><a
href="/contest/1399/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_449de66927cf7ab21832eba73b59f9a7bfc9866a">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Лодочное соревнование</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть $$$n$$$ людей, желающих принять участие в лодочном соревновании. Вес $$$i$$$-го участника равен $$$w_i$$$. Принять участие могут только команды, состоящие из <span class="tex-font-style-bf">двух</span> человек. Как организатор вы считаете честным допустить к соревнованию только команды <span class="tex-font-style-bf">с одинаковым суммарным весом</span>.</p><p>Таким образом, для $$$k$$$ команд $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\dots$$$, $$$(a_k, b_k)$$$, где $$$a_i$$$ — вес первого участника $$$i$$$-й команды, а $$$b_i$$$ — вес второго участника $$$i$$$-й команды, должно выполняться условие $$$a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$$$, где $$$s$$$ — суммарный вес для <span class="tex-font-style-bf">каждой</span> команды.</p><p>Ваша задача — выбрать такое число $$$s$$$, что количество команд, которые могут быть созданы, <span class="tex-font-style-bf">максимально</span> возможное. Обратите внимание: каждый участник может состоять <span class="tex-font-style-bf">не более чем в одной</span> команде.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 50$$$) — количество участников. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le n$$$), где $$$w_i$$$ — вес $$$i$$$-го участника.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число $$$k$$$: <span class="tex-font-style-bf">максимальное</span> число команд, которые могут быть составлены при суммарном весе участников в команде, равном $$$s$$$, если выбирать $$$s$$$ оптимально.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
5
1 2 3 4 5
8
6 6 6 6 6 6 8 8
8
1 2 2 1 2 1 1 2
3
1 3 3
6
1 1 3 4 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
4
1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=6$$$. Тогда первая лодка будет использоваться участниками $$$1$$$ и $$$5$$$, а вторая лодка — участниками $$$2$$$ и $$$4$$$ (индексы совпадают с весами).</p><p>Во втором наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=12$$$. Тогда первые $$$6$$$ участников смогут образовать $$$3$$$ пары.</p><p>В третьем наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=3$$$. Ответ равен $$$4$$$, потому что у нас есть $$$4$$$ участника с весом $$$1$$$ и $$$4$$$ участника с весом $$$2$$$.</p><p>В четвертом наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=4$$$ или $$$s=6$$$.</p><p>В пятом наборе тестовых данных примера мы можем достичь оптимального ответа для $$$s=3$$$. Заметьте, что участник с весом $$$3$$$ не может использовать лодку, потому что для него в списке нет подходящей пары.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:42</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9d8897875bb',t:'MTY5NjY2NjE4Mi43NjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1200"] | ||
1399D | 1399 | D | ru | D. Из бинарной строки в подпоследовательности | <div class="problem-statement"><div class="header"><div class="title">D. Из бинарной строки в подпоследовательности</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана бинарная строка $$$s$$$, состоящая из $$$n$$$ нулей или единиц.</p><p>Ваша задача – разделить заданную строку на <span class="tex-font-style-bf">минимальное</span> число <span class="tex-font-style-bf">подпоследовательностей</span> таким образом, что <span class="tex-font-style-it">каждый символ</span> строки принадлежит ровно <span class="tex-font-style-it">одной подпоследовательности</span> и каждая подпоследовательность выглядит подобно «<span class="tex-font-style-tt">010101 ...</span>» или «<span class="tex-font-style-tt">101010 ...</span>» (т.е. подпоследовательность не должна содержать два соседних нуля или единицы).</p><p>Напомним, что подпоследовательность — это последовательность, которая может быть получена путем удаления из заданной последовательности с помощью удаления нуля или более элементов без изменения порядка остальных элементов. Например, подпоследовательностями «<span class="tex-font-style-tt">1011101</span>» являются «<span class="tex-font-style-tt">0</span>», «<span class="tex-font-style-tt">1</span>», «<span class="tex-font-style-tt">11111</span>», «<span class="tex-font-style-tt">0111</span>», «<span class="tex-font-style-tt">101</span>», «<span class="tex-font-style-tt">1001</span>», но не «<span class="tex-font-style-tt">000</span>», «<span class="tex-font-style-tt">101010</span>» и «<span class="tex-font-style-tt">11100</span>».</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длину $$$s$$$. Вторая строка набора тестовых данных содержит $$$n$$$ символов '<span class="tex-font-style-tt">0</span>' и '<span class="tex-font-style-tt">1</span>' — строку $$$s$$$.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: первой строкой выведите одно целое число $$$k$$$ ($$$1 \le k \le n$$$) — минимальное количество подпоследовательностей, на которые вы можете разделить строку $$$s$$$. Второй строкой выведите $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — номер подпоследовательности, к которой принадлежит $$$i$$$-й символ строки $$$s$$$.</p><p>Если существует несколько ответов, вы можете вывести любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4
0011
6
111111
5
10101
8
01010000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="6a14922b30c2669207489232a8a3ee91"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8bd3b097330f547caf8a7ddf861f45406ad15a1b"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='6a14922b30c2669207489232a8a3ee91'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1399%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='6a14922b30c2669207489232a8a3ee91'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1399">Codeforces Round 661 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='6a14922b30c2669207489232a8a3ee91'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1399/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6a14922b30c2669207489232a8a3ee91'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="691719"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6a14922b30c2669207489232a8a3ee91'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="691719"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81018" title="Codeforces Round #661 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11535:11536" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81082" title="81082" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11545:11546" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1399">Задачи</a></li>
<li><a
href="/contest/1399/submit">Отослать</a></li>
<li><a
href="/contest/1399/my">Мои посылки</a></li>
<li><a
href="/contest/1399/status">Статус</a></li>
<li><a
href="/contest/1399/hacks">Взломы</a></li>
<li><a
href="/contest/1399/standings">Положение</a></li>
<li><a
href="/contest/1399/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_36daadd233784d3d121972649d256211c5deb985">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Из бинарной строки в подпоследовательности</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана бинарная строка $$$s$$$, состоящая из $$$n$$$ нулей или единиц.</p><p>Ваша задача – разделить заданную строку на <span class="tex-font-style-bf">минимальное</span> число <span class="tex-font-style-bf">подпоследовательностей</span> таким образом, что <span class="tex-font-style-it">каждый символ</span> строки принадлежит ровно <span class="tex-font-style-it">одной подпоследовательности</span> и каждая подпоследовательность выглядит подобно «<span class="tex-font-style-tt">010101 ...</span>» или «<span class="tex-font-style-tt">101010 ...</span>» (т.е. подпоследовательность не должна содержать два соседних нуля или единицы).</p><p>Напомним, что подпоследовательность — это последовательность, которая может быть получена путем удаления из заданной последовательности с помощью удаления нуля или более элементов без изменения порядка остальных элементов. Например, подпоследовательностями «<span class="tex-font-style-tt">1011101</span>» являются «<span class="tex-font-style-tt">0</span>», «<span class="tex-font-style-tt">1</span>», «<span class="tex-font-style-tt">11111</span>», «<span class="tex-font-style-tt">0111</span>», «<span class="tex-font-style-tt">101</span>», «<span class="tex-font-style-tt">1001</span>», но не «<span class="tex-font-style-tt">000</span>», «<span class="tex-font-style-tt">101010</span>» и «<span class="tex-font-style-tt">11100</span>».</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длину $$$s$$$. Вторая строка набора тестовых данных содержит $$$n$$$ символов '<span class="tex-font-style-tt">0</span>' и '<span class="tex-font-style-tt">1</span>' — строку $$$s$$$.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: первой строкой выведите одно целое число $$$k$$$ ($$$1 \le k \le n$$$) — минимальное количество подпоследовательностей, на которые вы можете разделить строку $$$s$$$. Второй строкой выведите $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), где $$$a_i$$$ — номер подпоследовательности, к которой принадлежит $$$i$$$-й символ строки $$$s$$$.</p><p>Если существует несколько ответов, вы можете вывести любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4
0011
6
111111
5
10101
8
01010000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
1 2 2 1
6
1 2 3 4 5 6
1
1 1 1 1 1
4
1 1 1 1 1 2 3 4
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:44</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9e22e9d9d90',t:'MTY5NjY2NjE4NC4xMjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1500"] | ||
1399E1 | 1399 | E1 | ru | E1. Деление весов (простая версия) | <div class="problem-statement"><div class="header"><div class="title">E1. Деление весов (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Простая и сложная версии на самом деле являются разными задачами, поэтому прочитайте условия обеих задач внимательно</span>.</p><p>Вам задано взвешенное корневое дерево, вершина $$$1$$$ — корень этого дерева.</p><p>Дерево — это связный граф без циклов. У корневого дерева есть специальная вершина, называемая корнем. Предком вершины $$$v$$$ называется последняя отличная от $$$v$$$ вершина на пути от корня к вершине $$$v$$$. Потомками вершины $$$v$$$ называются все вершины, для которых $$$v$$$ является предком. Вершина называется листом, если у нее нет потомков. Взвешенное дерево — это такое дерево, в котором у каждого ребра есть некоторый вес.</p><p>Вес пути — это сумма весов всех ребер на этом пути. Вес пути от вершины до самой себя равен $$$0$$$.</p><p>Вы можете совершить последовательность из нуля или более ходов. В течение одного хода вы можете выбрать ребро и поделить его вес на $$$2$$$ с округлением вниз. Более формально, в течение одного хода вы выбираете какое-то ребро $$$i$$$ и делите его вес на $$$2$$$ с округлением вниз ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).</p><p>Ваша задача — найти минимальное количество <span class="tex-font-style-bf">ходов</span>, необходимых для того, чтобы сделать <span class="tex-font-style-bf">сумму весов путей</span> от корня до каждого листа не превосходящей $$$S$$$. Другими словами, если $$$w(i, j)$$$ — это вес пути от вершины $$$i$$$ до вершины $$$j$$$, то вам необходимо сделать $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, где $$$leaves$$$ — это список всех листьев.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — количество вершин в дереве и максимально возможная сумма весов, которую вы можете получить. Следующая $$$n-1$$$ строка описывает ребра дерева. Ребро $$$i$$$ описывается тремя целыми числами $$$v_i$$$, $$$u_i$$$ и $$$w_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6$$$), где $$$v_i$$$ и $$$u_i$$$ — вершины, которые соединены ребром $$$i$$$, а $$$w_i$$$ — вес этого ребра.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$10^5$$$ ($$$\sum n \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: минимальное количество <span class="tex-font-style-bf">ходов</span>, необходимое, чтобы сделать сумму весов путей от корня до каждого листа не превосходящей $$$S$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
3 20
2 1 8
3 1 7
5 50
1 3 100
1 5 10
2 3 123
5 4 55
2 100
1 2 409
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
8
3
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="5324b43745552e8497f5f7b4d89e1520"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E1 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8bd3b097330f547caf8a7ddf861f45406ad15a1b"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E1 - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='5324b43745552e8497f5f7b4d89e1520'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1399%2Fproblem%2FE1%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='5324b43745552e8497f5f7b4d89e1520'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1399">Codeforces Round 661 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='5324b43745552e8497f5f7b4d89e1520'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1399/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2000
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5324b43745552e8497f5f7b4d89e1520'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="691720"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5324b43745552e8497f5f7b4d89e1520'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="691720"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81018" title="Codeforces Round #661 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11535:11536" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81082" title="81082" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11545:11546" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1399">Задачи</a></li>
<li><a
href="/contest/1399/submit">Отослать</a></li>
<li><a
href="/contest/1399/my">Мои посылки</a></li>
<li><a
href="/contest/1399/status">Статус</a></li>
<li><a
href="/contest/1399/hacks">Взломы</a></li>
<li><a
href="/contest/1399/standings">Положение</a></li>
<li><a
href="/contest/1399/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E1" data-uuid="ps_26bb475bcdc726ed91037b941d5ff044051a9b67">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E1. Деление весов (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Простая и сложная версии на самом деле являются разными задачами, поэтому прочитайте условия обеих задач внимательно</span>.</p><p>Вам задано взвешенное корневое дерево, вершина $$$1$$$ — корень этого дерева.</p><p>Дерево — это связный граф без циклов. У корневого дерева есть специальная вершина, называемая корнем. Предком вершины $$$v$$$ называется последняя отличная от $$$v$$$ вершина на пути от корня к вершине $$$v$$$. Потомками вершины $$$v$$$ называются все вершины, для которых $$$v$$$ является предком. Вершина называется листом, если у нее нет потомков. Взвешенное дерево — это такое дерево, в котором у каждого ребра есть некоторый вес.</p><p>Вес пути — это сумма весов всех ребер на этом пути. Вес пути от вершины до самой себя равен $$$0$$$.</p><p>Вы можете совершить последовательность из нуля или более ходов. В течение одного хода вы можете выбрать ребро и поделить его вес на $$$2$$$ с округлением вниз. Более формально, в течение одного хода вы выбираете какое-то ребро $$$i$$$ и делите его вес на $$$2$$$ с округлением вниз ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).</p><p>Ваша задача — найти минимальное количество <span class="tex-font-style-bf">ходов</span>, необходимых для того, чтобы сделать <span class="tex-font-style-bf">сумму весов путей</span> от корня до каждого листа не превосходящей $$$S$$$. Другими словами, если $$$w(i, j)$$$ — это вес пути от вершины $$$i$$$ до вершины $$$j$$$, то вам необходимо сделать $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, где $$$leaves$$$ — это список всех листьев.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — количество вершин в дереве и максимально возможная сумма весов, которую вы можете получить. Следующая $$$n-1$$$ строка описывает ребра дерева. Ребро $$$i$$$ описывается тремя целыми числами $$$v_i$$$, $$$u_i$$$ и $$$w_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6$$$), где $$$v_i$$$ и $$$u_i$$$ — вершины, которые соединены ребром $$$i$$$, а $$$w_i$$$ — вес этого ребра.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$10^5$$$ ($$$\sum n \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: минимальное количество <span class="tex-font-style-bf">ходов</span>, необходимое, чтобы сделать сумму весов путей от корня до каждого листа не превосходящей $$$S$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
3 20
2 1 8
3 1 7
5 50
1 3 100
1 5 10
2 3 123
5 4 55
2 100
1 2 409
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
8
3
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E1]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:45</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9ea7eb79d70',t:'MTY5NjY2NjE4NS40OTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2000"] | ||
1399E2 | 1399 | E2 | ru | E2. Деление весов (сложная версия) | <div class="problem-statement"><div class="header"><div class="title">E2. Деление весов (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Простая и сложная версии на самом деле являются разными задачами, поэтому прочитайте условия обеих задач внимательно</span>.</p><p>Вам задано взвешенное корневое дерево, вершина $$$1$$$ — корень этого дерева. <span class="tex-font-style-bf">Также каждое ребро имеет свою собственную стоимость</span>.</p><p>Дерево — это связный граф без циклов. У корневого дерева есть специальная вершина, называемая корнем. Предком вершины $$$v$$$ называется последняя отличная от $$$v$$$ вершина на пути от корня к вершине $$$v$$$. Потомками вершины $$$v$$$ называются все вершины, для которых $$$v$$$ является предком. Вершина называется листом, если у нее нет потомков. Взвешенное дерево — это такое дерево, в котором у каждого ребра есть некоторый вес.</p><p>Вес пути — это сумма весов всех ребер на этом пути. Вес пути от вершины до самой себя равен $$$0$$$.</p><p>Вы можете совершить последовательность из нуля или более ходов. В течение одного хода вы можете выбрать ребро и поделить его вес на $$$2$$$ с округлением вниз. Более формально, в течение одного хода вы выбираете какое-то ребро $$$i$$$ и делите его вес на $$$2$$$ с округлением вниз ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).</p><p>Каждое ребро $$$i$$$ имеет свою стоимость $$$c_i$$$, которая равна либо $$$1$$$, либо $$$2$$$ монетам. Каждый ход с ребром $$$i$$$ стоит $$$c_i$$$ монет.</p><p>Ваша задача — найти минимальную суммарную <span class="tex-font-style-bf">стоимость</span>, необходимую для того, чтобы сделать <span class="tex-font-style-bf">сумму весов путей</span> от корня до каждого листа не превосходящей $$$S$$$. Другими словами, если $$$w(i, j)$$$ — это вес пути от вершины $$$i$$$ до вершины $$$j$$$, то вам необходимо сделать $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, где $$$leaves$$$ — это список всех листьев.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — количество вершин в дереве и максимально возможная сумма весов, которую вы можете получить. Следующая $$$n-1$$$ строка описывает ребра дерева. Ребро $$$i$$$ описывается четырьмя целыми числами $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ и $$$c_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6; 1 \le c_i \le 2$$$), где $$$v_i$$$ и $$$u_i$$$ — вершины, которые соединены ребром $$$i$$$, $$$w_i$$$ — вес этого ребра, а $$$c_i$$$ — цена этого ребра.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$10^5$$$ ($$$\sum n \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: минимальную суммарную <span class="tex-font-style-bf">стоимость</span>, необходимую, чтобы сделать сумму весов путей от корня до каждого листа не превосходящей $$$S$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
11
6
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="0e935129de00c888badec009f55ed9cc"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E2 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8bd3b097330f547caf8a7ddf861f45406ad15a1b"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E2 - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='0e935129de00c888badec009f55ed9cc'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1399%2Fproblem%2FE2%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='0e935129de00c888badec009f55ed9cc'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1399">Codeforces Round 661 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='0e935129de00c888badec009f55ed9cc'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1399/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0e935129de00c888badec009f55ed9cc'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="691721"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0e935129de00c888badec009f55ed9cc'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="691721"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81018" title="Codeforces Round #661 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11535:11536" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81082" title="81082" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11545:11546" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1399">Задачи</a></li>
<li><a
href="/contest/1399/submit">Отослать</a></li>
<li><a
href="/contest/1399/my">Мои посылки</a></li>
<li><a
href="/contest/1399/status">Статус</a></li>
<li><a
href="/contest/1399/hacks">Взломы</a></li>
<li><a
href="/contest/1399/standings">Положение</a></li>
<li><a
href="/contest/1399/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E2" data-uuid="ps_8faf9529103330e25a88ac5b2718701883cfa651">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E2. Деление весов (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Простая и сложная версии на самом деле являются разными задачами, поэтому прочитайте условия обеих задач внимательно</span>.</p><p>Вам задано взвешенное корневое дерево, вершина $$$1$$$ — корень этого дерева. <span class="tex-font-style-bf">Также каждое ребро имеет свою собственную стоимость</span>.</p><p>Дерево — это связный граф без циклов. У корневого дерева есть специальная вершина, называемая корнем. Предком вершины $$$v$$$ называется последняя отличная от $$$v$$$ вершина на пути от корня к вершине $$$v$$$. Потомками вершины $$$v$$$ называются все вершины, для которых $$$v$$$ является предком. Вершина называется листом, если у нее нет потомков. Взвешенное дерево — это такое дерево, в котором у каждого ребра есть некоторый вес.</p><p>Вес пути — это сумма весов всех ребер на этом пути. Вес пути от вершины до самой себя равен $$$0$$$.</p><p>Вы можете совершить последовательность из нуля или более ходов. В течение одного хода вы можете выбрать ребро и поделить его вес на $$$2$$$ с округлением вниз. Более формально, в течение одного хода вы выбираете какое-то ребро $$$i$$$ и делите его вес на $$$2$$$ с округлением вниз ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).</p><p>Каждое ребро $$$i$$$ имеет свою стоимость $$$c_i$$$, которая равна либо $$$1$$$, либо $$$2$$$ монетам. Каждый ход с ребром $$$i$$$ стоит $$$c_i$$$ монет.</p><p>Ваша задача — найти минимальную суммарную <span class="tex-font-style-bf">стоимость</span>, необходимую для того, чтобы сделать <span class="tex-font-style-bf">сумму весов путей</span> от корня до каждого листа не превосходящей $$$S$$$. Другими словами, если $$$w(i, j)$$$ — это вес пути от вершины $$$i$$$ до вершины $$$j$$$, то вам необходимо сделать $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, где $$$leaves$$$ — это список всех листьев.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — количество вершин в дереве и максимально возможная сумма весов, которую вы можете получить. Следующая $$$n-1$$$ строка описывает ребра дерева. Ребро $$$i$$$ описывается четырьмя целыми числами $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ и $$$c_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6; 1 \le c_i \le 2$$$), где $$$v_i$$$ и $$$u_i$$$ — вершины, которые соединены ребром $$$i$$$, $$$w_i$$$ — вес этого ребра, а $$$c_i$$$ — цена этого ребра.</p><p>Гарантируется, что сумма всех $$$n$$$ не превосходит $$$10^5$$$ ($$$\sum n \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: минимальную суммарную <span class="tex-font-style-bf">стоимость</span>, необходимую, чтобы сделать сумму весов путей от корня до каждого листа не превосходящей $$$S$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
11
6
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E2]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:46</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9f31c8516f7',t:'MTY5NjY2NjE4Ni44MDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2200"] | ||
1399F | 1399 | F | ru | F. Очередное подмножество отрезков | <div class="problem-statement"><div class="header"><div class="title">F. Очередное подмножество отрезков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны $$$n$$$ отрезков на координатной оси $$$OX$$$. $$$i$$$-й отрезок имеет границы $$$[l_i; r_i]$$$. Все точки $$$x$$$, для которых выполняется условие $$$l_i \le x \le r_i$$$, принадлежат $$$i$$$-му отрезку.</p><p>Ваша задача — выбрать такое <span class="tex-font-style-bf">максимальное</span> по размеру (количеству отрезков) подмножество заданного множества отрезков, что каждая пара отрезков в этом подмножестве либо не пересекается либо же один из них лежит внутри другого.</p><p>Два отрезка $$$[l_i; r_i]$$$ и $$$[l_j; r_j]$$$ не пересекаются, если у них <span class="tex-font-style-bf">нет общих точек</span>. Например, отрезки $$$[1; 2]$$$ и $$$[3; 4]$$$, $$$[1; 3]$$$ и $$$[5; 5]$$$ не пересекаются, а отрезки $$$[1; 2]$$$ и $$$[2; 3]$$$, $$$[1; 2]$$$ и $$$[2; 2]$$$ пересекаются.</p><p>Отрезок $$$[l_i; r_i]$$$ лежит внутри отрезка $$$[l_j; r_j]$$$, если $$$l_j \le l_i$$$ и $$$r_i \le r_j$$$. Например, отрезки $$$[2; 2]$$$, $$$[2, 3]$$$, $$$[3; 4]$$$ и $$$[2; 4]$$$ лежат внутри отрезка $$$[2; 4]$$$, а $$$[2; 5]$$$ и $$$[1; 4]$$$ — нет.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 3000$$$) — количество отрезков. Следующие $$$n$$$ строк описывают отрезки. $$$i$$$-й отрезок задан двумя целыми числами $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le 2 \cdot 10^5$$$), где $$$l_i$$$ — левая граница $$$i$$$-го отрезка, а $$$r_i$$$ — правая граница $$$i$$$-го отрезка.</p><p>Дополнительное ограничение на входные данные: в заданном списке отрезков <span class="tex-font-style-bf">нет дубликатов</span>.</p><p>Гарантируется, что сумма $$$n$$$ не превосходит $$$3000$$$ ($$$\sum n \le 3000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ: <span class="tex-font-style-bf">максимально</span> возможный размер такого подмножества заданного множества отрезков, что каждая пара отрезков в этом подмножестве либо не пересекается, либо же один из них лежит внутри другого.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4
1 5
2 4
2 3
3 4
5
1 5
2 3
2 5
3 5
2 2
3
1 3
2 4
2 3
7
1 10
2 8
2 5
3 4
4 4
6 8
7 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
4
2
7
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="fb5b05189baf39f4842d2f2adeb1009a"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - F - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="8bd3b097330f547caf8a7ddf861f45406ad15a1b"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='fb5b05189baf39f4842d2f2adeb1009a'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1399%2Fproblem%2FF%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='fb5b05189baf39f4842d2f2adeb1009a'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1399">Codeforces Round 661 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='fb5b05189baf39f4842d2f2adeb1009a'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1399/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fb5b05189baf39f4842d2f2adeb1009a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="691722"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fb5b05189baf39f4842d2f2adeb1009a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="691722"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81018" title="Codeforces Round #661 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11535:11536" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81082" title="81082" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11545:11546" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1399">Задачи</a></li>
<li><a
href="/contest/1399/submit">Отослать</a></li>
<li><a
href="/contest/1399/my">Мои посылки</a></li>
<li><a
href="/contest/1399/status">Статус</a></li>
<li><a
href="/contest/1399/hacks">Взломы</a></li>
<li><a
href="/contest/1399/standings">Положение</a></li>
<li><a
href="/contest/1399/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="F" data-uuid="ps_c1769acb5dd2ac87ea4a61ca403c0ac6d37d8219">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Очередное подмножество отрезков</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны $$$n$$$ отрезков на координатной оси $$$OX$$$. $$$i$$$-й отрезок имеет границы $$$[l_i; r_i]$$$. Все точки $$$x$$$, для которых выполняется условие $$$l_i \le x \le r_i$$$, принадлежат $$$i$$$-му отрезку.</p><p>Ваша задача — выбрать такое <span class="tex-font-style-bf">максимальное</span> по размеру (количеству отрезков) подмножество заданного множества отрезков, что каждая пара отрезков в этом подмножестве либо не пересекается либо же один из них лежит внутри другого.</p><p>Два отрезка $$$[l_i; r_i]$$$ и $$$[l_j; r_j]$$$ не пересекаются, если у них <span class="tex-font-style-bf">нет общих точек</span>. Например, отрезки $$$[1; 2]$$$ и $$$[3; 4]$$$, $$$[1; 3]$$$ и $$$[5; 5]$$$ не пересекаются, а отрезки $$$[1; 2]$$$ и $$$[2; 3]$$$, $$$[1; 2]$$$ и $$$[2; 2]$$$ пересекаются.</p><p>Отрезок $$$[l_i; r_i]$$$ лежит внутри отрезка $$$[l_j; r_j]$$$, если $$$l_j \le l_i$$$ и $$$r_i \le r_j$$$. Например, отрезки $$$[2; 2]$$$, $$$[2, 3]$$$, $$$[3; 4]$$$ и $$$[2; 4]$$$ лежат внутри отрезка $$$[2; 4]$$$, а $$$[2; 5]$$$ и $$$[1; 4]$$$ — нет.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 3000$$$) — количество отрезков. Следующие $$$n$$$ строк описывают отрезки. $$$i$$$-й отрезок задан двумя целыми числами $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le 2 \cdot 10^5$$$), где $$$l_i$$$ — левая граница $$$i$$$-го отрезка, а $$$r_i$$$ — правая граница $$$i$$$-го отрезка.</p><p>Дополнительное ограничение на входные данные: в заданном списке отрезков <span class="tex-font-style-bf">нет дубликатов</span>.</p><p>Гарантируется, что сумма $$$n$$$ не превосходит $$$3000$$$ ($$$\sum n \le 3000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ: <span class="tex-font-style-bf">максимально</span> возможный размер такого подмножества заданного множества отрезков, что каждая пара отрезков в этом подмножестве либо не пересекается, либо же один из них лежит внутри другого.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4
1 5
2 4
2 3
3 4
5
1 5
2 3
2 5
3 5
2 2
3
1 3
2 4
2 3
7
1 10
2 8
2 5
3 4
4 4
6 8
7 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
4
2
7
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:48</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a9fb3a797b23',t:'MTY5NjY2NjE4OC4xMDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2300"] | ||
1400A | 1400 | A | ru | A. Похожие строки | <div class="problem-statement"><div class="header"><div class="title">A. Похожие строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Двоичная строка — это такая строка, каждый символ которой — либо <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>. Назовем две двоичные строки $$$a$$$ и $$$b$$$ одинаковой длины <span class="tex-font-style-it">похожими</span>, если хотя бы в одной позиции их символы совпадают (существует такое число $$$i$$$, что $$$a_i = b_i$$$). Например:</p><ul> <li> <span class="tex-font-style-tt">10010</span> и <span class="tex-font-style-tt">01111</span> <span class="tex-font-style-it">похожи</span> (у них один и тот же символ в позиции $$$4$$$); </li><li> <span class="tex-font-style-tt">10010</span> и <span class="tex-font-style-tt">11111</span> <span class="tex-font-style-it">похожи</span>; </li><li> <span class="tex-font-style-tt">111</span> и <span class="tex-font-style-tt">111</span> <span class="tex-font-style-it">похожи</span>; </li><li> <span class="tex-font-style-tt">0110</span> и <span class="tex-font-style-tt">1001</span> не являются <span class="tex-font-style-it">похожими</span>. </li></ul><p>Вам дано целое число $$$n$$$ и двоичная строка $$$s$$$, состоящая из $$$2n-1$$$ символов. Обозначим за $$$s[l..r]$$$ непрерывную подстроку $$$s$$$, начиная с $$$l$$$-го символа и заканчивая $$$r$$$-м символом (иными словами, $$$s[l..r] = s_l s_{l + 1} s_{l + 2} \dots s_r$$$).</p><p>Постройте двоичную строку $$$w$$$ длины $$$n$$$, <span class="tex-font-style-it">похожую</span> на <span class="tex-font-style-bf">все строки из этого списка</span>: $$$s[1..n]$$$, $$$s[2..n+1]$$$, $$$s[3..n+2]$$$, ..., $$$s[n..2n-1]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Первая строка набора входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 50$$$).</p><p>Вторая строка содержит двоичную строку $$$s$$$ длины $$$2n - 1$$$. Каждый символ $$$s_i$$$ — либо <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите удовлетворяющую условию двоичную строку $$$w$$$ длины $$$n$$$. Если существует несколько таких строк — выведите любую из них. Можно показать, что хотя бы одна такая строка $$$w$$$ всегда существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1
1
3
00000
4
1110000
2
101
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
000
1010
00
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение примера из условия (совпадающие символы в одинаковых позициях выделены жирным):</p><p>Первый набор входных данных: </p><ul> <li> $$$\mathbf{1}$$$ похожа на $$$s[1..1] = \mathbf{1}$$$. </li></ul><p>Второй набор входных данных: </p><ul> <li> $$$\mathbf{000}$$$ похожа на $$$s[1..3] = \mathbf{000}$$$; </li><li> $$$\mathbf{000}$$$ похожа на $$$s[2..4] = \mathbf{000}$$$; </li><li> $$$\mathbf{000}$$$ похожа на $$$s[3..5] = \mathbf{000}$$$. </li></ul><p>Третий набор входных данных: </p><ul> <li> $$$\mathbf{1}0\mathbf{10}$$$ похожа на $$$s[1..4] = \mathbf{1}1\mathbf{10}$$$; </li><li> $$$\mathbf{1}01\mathbf{0}$$$ похожа на $$$s[2..5] = \mathbf{1}10\mathbf{0}$$$; </li><li> $$$\mathbf{10}1\mathbf{0}$$$ похожа на $$$s[3..6] = \mathbf{10}0\mathbf{0}$$$; </li><li> $$$1\mathbf{0}1\mathbf{0}$$$ похожа на $$$s[4..7] = 0\mathbf{0}0\mathbf{0}$$$. </li></ul><p>Четвертый набор входных данных: </p><ul> <li> $$$0\mathbf{0}$$$ похожа на $$$s[1..2] = 1\mathbf{0}$$$; </li><li> $$$\mathbf{0}0$$$ похожа на $$$s[2..3] = \mathbf{0}1$$$. </li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="30f15844ca05e0263400f5aa90b512c7"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e407f362a6da0f68cca7e0f50d624e113a539a0d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='30f15844ca05e0263400f5aa90b512c7'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1400%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='30f15844ca05e0263400f5aa90b512c7'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1400">Educational Codeforces Round 94 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='30f15844ca05e0263400f5aa90b512c7'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1400/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='30f15844ca05e0263400f5aa90b512c7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="709183"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='30f15844ca05e0263400f5aa90b512c7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="709183"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81862" title="Educational Codeforces Round 94 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11742:11743" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81916" title="Unofficial Editorial for Educational Round 94 (Div. 2)" target="_blank">Разбор задач №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11751" resourceName="Unofficial Editorial for Educational Round 94 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81942" title="81942" target="_blank">Разбор задач №2</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11753:11754" resourceName="Разбор задач №2"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1400">Задачи</a></li>
<li><a
href="/contest/1400/submit">Отослать</a></li>
<li><a
href="/contest/1400/my">Мои посылки</a></li>
<li><a
href="/contest/1400/status">Статус</a></li>
<li><a
href="/contest/1400/hacks">Взломы</a></li>
<li><a
href="/contest/1400/standings">Положение</a></li>
<li><a
href="/contest/1400/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_915d6050e7ebf6a2a976607944ade227e98cfe47">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Похожие строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Двоичная строка — это такая строка, каждый символ которой — либо <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>. Назовем две двоичные строки $$$a$$$ и $$$b$$$ одинаковой длины <span class="tex-font-style-it">похожими</span>, если хотя бы в одной позиции их символы совпадают (существует такое число $$$i$$$, что $$$a_i = b_i$$$). Например:</p><ul> <li> <span class="tex-font-style-tt">10010</span> и <span class="tex-font-style-tt">01111</span> <span class="tex-font-style-it">похожи</span> (у них один и тот же символ в позиции $$$4$$$); </li><li> <span class="tex-font-style-tt">10010</span> и <span class="tex-font-style-tt">11111</span> <span class="tex-font-style-it">похожи</span>; </li><li> <span class="tex-font-style-tt">111</span> и <span class="tex-font-style-tt">111</span> <span class="tex-font-style-it">похожи</span>; </li><li> <span class="tex-font-style-tt">0110</span> и <span class="tex-font-style-tt">1001</span> не являются <span class="tex-font-style-it">похожими</span>. </li></ul><p>Вам дано целое число $$$n$$$ и двоичная строка $$$s$$$, состоящая из $$$2n-1$$$ символов. Обозначим за $$$s[l..r]$$$ непрерывную подстроку $$$s$$$, начиная с $$$l$$$-го символа и заканчивая $$$r$$$-м символом (иными словами, $$$s[l..r] = s_l s_{l + 1} s_{l + 2} \dots s_r$$$).</p><p>Постройте двоичную строку $$$w$$$ длины $$$n$$$, <span class="tex-font-style-it">похожую</span> на <span class="tex-font-style-bf">все строки из этого списка</span>: $$$s[1..n]$$$, $$$s[2..n+1]$$$, $$$s[3..n+2]$$$, ..., $$$s[n..2n-1]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Первая строка набора входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 50$$$).</p><p>Вторая строка содержит двоичную строку $$$s$$$ длины $$$2n - 1$$$. Каждый символ $$$s_i$$$ — либо <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите удовлетворяющую условию двоичную строку $$$w$$$ длины $$$n$$$. Если существует несколько таких строк — выведите любую из них. Можно показать, что хотя бы одна такая строка $$$w$$$ всегда существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1
1
3
00000
4
1110000
2
101
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
000
1010
00
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение примера из условия (совпадающие символы в одинаковых позициях выделены жирным):</p><p>Первый набор входных данных: </p><ul> <li> $$$\mathbf{1}$$$ похожа на $$$s[1..1] = \mathbf{1}$$$. </li></ul><p>Второй набор входных данных: </p><ul> <li> $$$\mathbf{000}$$$ похожа на $$$s[1..3] = \mathbf{000}$$$; </li><li> $$$\mathbf{000}$$$ похожа на $$$s[2..4] = \mathbf{000}$$$; </li><li> $$$\mathbf{000}$$$ похожа на $$$s[3..5] = \mathbf{000}$$$. </li></ul><p>Третий набор входных данных: </p><ul> <li> $$$\mathbf{1}0\mathbf{10}$$$ похожа на $$$s[1..4] = \mathbf{1}1\mathbf{10}$$$; </li><li> $$$\mathbf{1}01\mathbf{0}$$$ похожа на $$$s[2..5] = \mathbf{1}10\mathbf{0}$$$; </li><li> $$$\mathbf{10}1\mathbf{0}$$$ похожа на $$$s[3..6] = \mathbf{10}0\mathbf{0}$$$; </li><li> $$$1\mathbf{0}1\mathbf{0}$$$ похожа на $$$s[4..7] = 0\mathbf{0}0\mathbf{0}$$$. </li></ul><p>Четвертый набор входных данных: </p><ul> <li> $$$0\mathbf{0}$$$ похожа на $$$s[1..2] = 1\mathbf{0}$$$; </li><li> $$$\mathbf{0}0$$$ похожа на $$$s[2..3] = \mathbf{0}1$$$. </li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:49</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa03594b7593',t:'MTY5NjY2NjE4OS43NjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u043e\u043a\u0438", "*800"] | ||
1400B | 1400 | B | ru | B. Главный герой RPG | <div class="problem-statement"><div class="header"><div class="title">B. Главный герой RPG</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы играете в одну RPG из 2010-х. Вы планируете поднять свой уровень кузнечного дела, а потому вам нужно как можно больше ресурсов. Как же получить эти ресурсы? Конечно, украсть.</p><p>Вы решили ограбить городского кузнеца и взяли собой напарника. Вы можете переносить не более $$$p$$$ единиц, а ваш напарник — не более $$$f$$$ единиц.</p><p>В кузнечной лавке вы нашли $$$cnt_s$$$ мечей и $$$cnt_w$$$ боевых топоров. Каждый меч весит $$$s$$$ единиц, а каждый топор — $$$w$$$ единиц. Вам не важно, что брать, потому что и меч и топор переплавляются в один стальной слиток.</p><p>Какое максимальное количество оружия (мечей и топоров) вы со своим напарником сможете унести из лавки?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора данных заданы два целых числа $$$p$$$ и $$$f$$$ ($$$1 \le p, f \le 10^9$$$) — ваша грузоподъемность и грузоподъемность вашего напарника.</p><p>Во второй строке каждого набора заданы два целых числа $$$cnt_s$$$ и $$$cnt_w$$$ ($$$1 \le cnt_s, cnt_w \le 2 \cdot 10^5$$$) — количество мечей и боевых топоров в кузнечной лавке.</p><p>В третьей строке каждого набора заданы два целых числа $$$s$$$ и $$$w$$$ ($$$1 \le s, w \le 10^9$$$) — веса каждого меча и каждого топора.</p><p>Гарантируется, что суммарное количество мечей и суммарное количество топоров во всех наборах входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите максимальное количество оружия (мечей и топоров), которое вы со своим напарником сможете унести.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
11
20
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных: </p><ul> <li> вы можете взять $$$3$$$ меча и $$$3$$$ боевых топора: $$$3 \cdot 5 + 3 \cdot 6 = 33 \le 33$$$, </li><li> а ваш напарник — $$$3$$$ меча и $$$2$$$ топора: $$$3 \cdot 5 + 2 \cdot 6 = 27 \le 27$$$. </li></ul> $$$3 + 3 + 3 + 2 = 11$$$ единиц оружия в сумме.<p>Во втором наборе, вы можете взять все доступное оружие даже без помощи напарника, так как $$$5 \cdot 10 + 5 \cdot 10 \le 100$$$.</p><p>В третьем наборе, вы не можете взять ничего, но ваш напарник может взять $$$3$$$ топора: $$$3 \cdot 5 \le 19$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="a2a5782da9b0cea74ffd58e3262d6756"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e407f362a6da0f68cca7e0f50d624e113a539a0d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='a2a5782da9b0cea74ffd58e3262d6756'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1400%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='a2a5782da9b0cea74ffd58e3262d6756'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1400">Educational Codeforces Round 94 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='a2a5782da9b0cea74ffd58e3262d6756'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1400/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1700
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a2a5782da9b0cea74ffd58e3262d6756'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="709184"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a2a5782da9b0cea74ffd58e3262d6756'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="709184"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81862" title="Educational Codeforces Round 94 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11742:11743" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81916" title="Unofficial Editorial for Educational Round 94 (Div. 2)" target="_blank">Разбор задач №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11751" resourceName="Unofficial Editorial for Educational Round 94 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81942" title="81942" target="_blank">Разбор задач №2</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11753:11754" resourceName="Разбор задач №2"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1400">Задачи</a></li>
<li><a
href="/contest/1400/submit">Отослать</a></li>
<li><a
href="/contest/1400/my">Мои посылки</a></li>
<li><a
href="/contest/1400/status">Статус</a></li>
<li><a
href="/contest/1400/hacks">Взломы</a></li>
<li><a
href="/contest/1400/standings">Положение</a></li>
<li><a
href="/contest/1400/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_366328025f13ea784691badcdf3e4baacf30b27b">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Главный герой RPG</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы играете в одну RPG из 2010-х. Вы планируете поднять свой уровень кузнечного дела, а потому вам нужно как можно больше ресурсов. Как же получить эти ресурсы? Конечно, украсть.</p><p>Вы решили ограбить городского кузнеца и взяли собой напарника. Вы можете переносить не более $$$p$$$ единиц, а ваш напарник — не более $$$f$$$ единиц.</p><p>В кузнечной лавке вы нашли $$$cnt_s$$$ мечей и $$$cnt_w$$$ боевых топоров. Каждый меч весит $$$s$$$ единиц, а каждый топор — $$$w$$$ единиц. Вам не важно, что брать, потому что и меч и топор переплавляются в один стальной слиток.</p><p>Какое максимальное количество оружия (мечей и топоров) вы со своим напарником сможете унести из лавки?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора данных заданы два целых числа $$$p$$$ и $$$f$$$ ($$$1 \le p, f \le 10^9$$$) — ваша грузоподъемность и грузоподъемность вашего напарника.</p><p>Во второй строке каждого набора заданы два целых числа $$$cnt_s$$$ и $$$cnt_w$$$ ($$$1 \le cnt_s, cnt_w \le 2 \cdot 10^5$$$) — количество мечей и боевых топоров в кузнечной лавке.</p><p>В третьей строке каждого набора заданы два целых числа $$$s$$$ и $$$w$$$ ($$$1 \le s, w \le 10^9$$$) — веса каждого меча и каждого топора.</p><p>Гарантируется, что суммарное количество мечей и суммарное количество топоров во всех наборах входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите максимальное количество оружия (мечей и топоров), которое вы со своим напарником сможете унести.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
33 27
6 10
5 6
100 200
10 10
5 5
1 19
1 3
19 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
11
20
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных: </p><ul> <li> вы можете взять $$$3$$$ меча и $$$3$$$ боевых топора: $$$3 \cdot 5 + 3 \cdot 6 = 33 \le 33$$$, </li><li> а ваш напарник — $$$3$$$ меча и $$$2$$$ топора: $$$3 \cdot 5 + 2 \cdot 6 = 27 \le 27$$$. </li></ul> $$$3 + 3 + 3 + 2 = 11$$$ единиц оружия в сумме.<p>Во втором наборе, вы можете взять все доступное оружие даже без помощи напарника, так как $$$5 \cdot 10 + 5 \cdot 10 \le 100$$$.</p><p>В третьем наборе, вы не можете взять ничего, но ваш напарник может взять $$$3$$$ топора: $$$3 \cdot 5 \le 19$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:51</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa0dcfb44985',t:'MTY5NjY2NjE5MS4xMjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1700"] | ||
1400C | 1400 | C | ru | C. Восстановление бинарной строки | <div class="problem-statement"><div class="header"><div class="title">C. Восстановление бинарной строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим следующий процесс. У вас есть бинарная строка (строка, состоящая только из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>) $$$w$$$ длины $$$n$$$ и число $$$x$$$. Вы создаете новую бинарную строку $$$s$$$ длины $$$n$$$; $$$i$$$-й символ новой строки $$$s$$$ выбирается следующим образом:</p><ul> <li> если символ $$$w_{i-x}$$$ существует и равен <span class="tex-font-style-tt">1</span>, то $$$s_i$$$ равно <span class="tex-font-style-tt">1</span> (более формально, если $$$i > x$$$ и $$$w_{i-x} = $$$ <span class="tex-font-style-tt">1</span>, то $$$s_i = $$$ <span class="tex-font-style-tt">1</span>); </li><li> если символ $$$w_{i+x}$$$ существует и равен <span class="tex-font-style-tt">1</span>, то $$$s_i$$$ равно <span class="tex-font-style-tt">1</span> (более формально, если $$$i + x \le n$$$ и $$$w_{i+x} = $$$ <span class="tex-font-style-tt">1</span>, то $$$s_i = $$$ <span class="tex-font-style-tt">1</span>); </li><li> если оба описанных выше условия неверны, то $$$s_i$$$ равно <span class="tex-font-style-tt">0</span>. </li></ul><p>Вам заданы число $$$x$$$ и строка $$$s$$$. Восстановите изначальную строку $$$w$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит две строки. Первая строка содержит строку $$$s$$$ ($$$2 \le |s| \le 10^5$$$, каждый символ строки $$$s$$$ равен либо <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>). Вторая строка содержит целое число $$$x$$$ ($$$1 \le x \le |s| - 1$$$).</p><p>Суммарная длина всех длин строк $$$s$$$ во входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ:</p><ul> <li> если не существует строки $$$w$$$, которая может породить строку $$$s$$$, то выведите $$$-1$$$; </li><li> иначе, выведите бинарную строку $$$w$$$ состоящую из $$$|s|$$$ символов. Если возможных ответов несколько — вы можете вывести любой из них. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
101110
2
01
1
110
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
111011
10
-1
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="3cfb78419133e8d9c1fe1942fd795ca5"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e407f362a6da0f68cca7e0f50d624e113a539a0d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='3cfb78419133e8d9c1fe1942fd795ca5'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1400%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='3cfb78419133e8d9c1fe1942fd795ca5'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1400">Educational Codeforces Round 94 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='3cfb78419133e8d9c1fe1942fd795ca5'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1400/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="2-SAT (2-satisfiability)">
2-sat
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3cfb78419133e8d9c1fe1942fd795ca5'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="709185"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3cfb78419133e8d9c1fe1942fd795ca5'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="709185"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81862" title="Educational Codeforces Round 94 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11742:11743" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81916" title="Unofficial Editorial for Educational Round 94 (Div. 2)" target="_blank">Разбор задач №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11751" resourceName="Unofficial Editorial for Educational Round 94 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81942" title="81942" target="_blank">Разбор задач №2</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11753:11754" resourceName="Разбор задач №2"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1400">Задачи</a></li>
<li><a
href="/contest/1400/submit">Отослать</a></li>
<li><a
href="/contest/1400/my">Мои посылки</a></li>
<li><a
href="/contest/1400/status">Статус</a></li>
<li><a
href="/contest/1400/hacks">Взломы</a></li>
<li><a
href="/contest/1400/standings">Положение</a></li>
<li><a
href="/contest/1400/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_b66b29ab103b35ab7145e8e395e39c0cf80c686e">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Восстановление бинарной строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим следующий процесс. У вас есть бинарная строка (строка, состоящая только из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>) $$$w$$$ длины $$$n$$$ и число $$$x$$$. Вы создаете новую бинарную строку $$$s$$$ длины $$$n$$$; $$$i$$$-й символ новой строки $$$s$$$ выбирается следующим образом:</p><ul> <li> если символ $$$w_{i-x}$$$ существует и равен <span class="tex-font-style-tt">1</span>, то $$$s_i$$$ равно <span class="tex-font-style-tt">1</span> (более формально, если $$$i > x$$$ и $$$w_{i-x} = $$$ <span class="tex-font-style-tt">1</span>, то $$$s_i = $$$ <span class="tex-font-style-tt">1</span>); </li><li> если символ $$$w_{i+x}$$$ существует и равен <span class="tex-font-style-tt">1</span>, то $$$s_i$$$ равно <span class="tex-font-style-tt">1</span> (более формально, если $$$i + x \le n$$$ и $$$w_{i+x} = $$$ <span class="tex-font-style-tt">1</span>, то $$$s_i = $$$ <span class="tex-font-style-tt">1</span>); </li><li> если оба описанных выше условия неверны, то $$$s_i$$$ равно <span class="tex-font-style-tt">0</span>. </li></ul><p>Вам заданы число $$$x$$$ и строка $$$s$$$. Восстановите изначальную строку $$$w$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит две строки. Первая строка содержит строку $$$s$$$ ($$$2 \le |s| \le 10^5$$$, каждый символ строки $$$s$$$ равен либо <span class="tex-font-style-tt">0</span>, либо <span class="tex-font-style-tt">1</span>). Вторая строка содержит целое число $$$x$$$ ($$$1 \le x \le |s| - 1$$$).</p><p>Суммарная длина всех длин строк $$$s$$$ во входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ:</p><ul> <li> если не существует строки $$$w$$$, которая может породить строку $$$s$$$, то выведите $$$-1$$$; </li><li> иначе, выведите бинарную строку $$$w$$$ состоящую из $$$|s|$$$ символов. Если возможных ответов несколько — вы можете вывести любой из них. </li></ul></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
101110
2
01
1
110
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
111011
10
-1
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:52</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa163fcc7b47',t:'MTY5NjY2NjE5Mi40MTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["2-SAT (2-satisfiability)", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["2-sat", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1500"] | ||
1400D | 1400 | D | ru | D. Зигзаги | <div class="problem-statement"><div class="header"><div class="title">D. Зигзаги</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a_1, a_2 \dots a_n$$$. Посчитайте количество таких четверок $$$(i, j, k, l)$$$, что: </p><ul> <li> $$$1 \le i < j < k < l \le n$$$; </li><li> $$$a_i = a_k$$$ и $$$a_j = a_l$$$; </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных задано единственное целое число $$$n$$$ ($$$4 \le n \le 3000$$$) — размер массива $$$a$$$.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — сам массив $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ в одном тесте не превосходит $$$3000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите количество описанных четверок.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
5
2 2 2 2 2
6
1 3 3 1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, каждая четверка индексов $$$i < j < k < l$$$ подходит, а потому ответ — это количество четверок.</p><p>Во втором наборе, есть только $$$2$$$ подходящих четверки: </p><ul> <li> $$$(1, 2, 4, 6)$$$: $$$a_1 = a_4$$$ и $$$a_2 = a_6$$$; </li><li> $$$(1, 3, 4, 6)$$$: $$$a_1 = a_4$$$ и $$$a_3 = a_6$$$. </li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="76db69605468db1d9a88db065c9ce306"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e407f362a6da0f68cca7e0f50d624e113a539a0d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='76db69605468db1d9a88db065c9ce306'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1400%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='76db69605468db1d9a88db065c9ce306'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1400">Educational Codeforces Round 94 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='76db69605468db1d9a88db065c9ce306'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1400/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика">
комбинаторика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1900
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='76db69605468db1d9a88db065c9ce306'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="709186"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='76db69605468db1d9a88db065c9ce306'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="709186"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81862" title="Educational Codeforces Round 94 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11742:11743" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81916" title="Unofficial Editorial for Educational Round 94 (Div. 2)" target="_blank">Разбор задач №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11751" resourceName="Unofficial Editorial for Educational Round 94 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81942" title="81942" target="_blank">Разбор задач №2</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11753:11754" resourceName="Разбор задач №2"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1400">Задачи</a></li>
<li><a
href="/contest/1400/submit">Отослать</a></li>
<li><a
href="/contest/1400/my">Мои посылки</a></li>
<li><a
href="/contest/1400/status">Статус</a></li>
<li><a
href="/contest/1400/hacks">Взломы</a></li>
<li><a
href="/contest/1400/standings">Положение</a></li>
<li><a
href="/contest/1400/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_cbd25ea6b214572c198ccf02c9b005c95dd77105">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Зигзаги</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a_1, a_2 \dots a_n$$$. Посчитайте количество таких четверок $$$(i, j, k, l)$$$, что: </p><ul> <li> $$$1 \le i < j < k < l \le n$$$; </li><li> $$$a_i = a_k$$$ и $$$a_j = a_l$$$; </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора входных данных задано единственное целое число $$$n$$$ ($$$4 \le n \le 3000$$$) — размер массива $$$a$$$.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — сам массив $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ в одном тесте не превосходит $$$3000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите количество описанных четверок.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
5
2 2 2 2 2
6
1 3 3 1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, каждая четверка индексов $$$i < j < k < l$$$ подходит, а потому ответ — это количество четверок.</p><p>Во втором наборе, есть только $$$2$$$ подходящих четверки: </p><ul> <li> $$$(1, 2, 4, 6)$$$: $$$a_1 = a_4$$$ и $$$a_2 = a_6$$$; </li><li> $$$(1, 3, 4, 6)$$$: $$$a_1 = a_4$$$ и $$$a_3 = a_6$$$. </li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:53</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa1e498f16b3',t:'MTY5NjY2NjE5My44NDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1900"] | ||
1400E | 1400 | E | ru | E. Очистите мультимножество | <div class="problem-statement"><div class="header"><div class="title">E. Очистите мультимножество</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть мультимножество, содержащее несколько чисел. Изначально оно содержит $$$a_1$$$ элементов равных $$$1$$$, $$$a_2$$$ элементов равных $$$2$$$, ..., $$$a_n$$$ элементов равных $$$n$$$.</p><p>Вы можете применять два типа операций:</p><ul> <li> выбрать два числа $$$l$$$ и $$$r$$$ ($$$l \le r$$$), а затем удалить один элемент, равный $$$l$$$, один элемент, равный $$$l + 1$$$, ..., и один элемент, равный $$$r$$$ из мультимножества. Эта операция может быть применена, только если каждый элемент от $$$l$$$ до $$$r$$$ встречается хотя бы раз в мультимножестве; </li><li> выбрать два числа $$$i$$$ и $$$x$$$ ($$$x \ge 1$$$), а затем удалить $$$x$$$ элементов равных $$$i$$$ из мультимножества. Эта операция может быть применена, только если в мультимножестве есть как минимум $$$x$$$ элементов, равных $$$i$$$. </li></ul><p>За какое наименьшее количество операций можно удалить все элементы из мультимножества?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 5000$$$).</p><p>Вторая строка содержит $$$n$$$ чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — наименьшее количество операций, за которое можно удалить все элементы из мультимножества.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 4 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
1 0 1 0 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="bd84690742490ee9b1eab306028b893c"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e407f362a6da0f68cca7e0f50d624e113a539a0d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='bd84690742490ee9b1eab306028b893c'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1400%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='bd84690742490ee9b1eab306028b893c'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1400">Educational Codeforces Round 94 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='bd84690742490ee9b1eab306028b893c'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1400/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй">
разделяй и властвуй
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bd84690742490ee9b1eab306028b893c'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="709187"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bd84690742490ee9b1eab306028b893c'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="709187"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81862" title="Educational Codeforces Round 94 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11742:11743" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81916" title="Unofficial Editorial for Educational Round 94 (Div. 2)" target="_blank">Разбор задач №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11751" resourceName="Unofficial Editorial for Educational Round 94 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81942" title="81942" target="_blank">Разбор задач №2</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11753:11754" resourceName="Разбор задач №2"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1400">Задачи</a></li>
<li><a
href="/contest/1400/submit">Отослать</a></li>
<li><a
href="/contest/1400/my">Мои посылки</a></li>
<li><a
href="/contest/1400/status">Статус</a></li>
<li><a
href="/contest/1400/hacks">Взломы</a></li>
<li><a
href="/contest/1400/standings">Положение</a></li>
<li><a
href="/contest/1400/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_ee7601cc5c3694e890f60ed9e647df172592e85e">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Очистите мультимножество</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть мультимножество, содержащее несколько чисел. Изначально оно содержит $$$a_1$$$ элементов равных $$$1$$$, $$$a_2$$$ элементов равных $$$2$$$, ..., $$$a_n$$$ элементов равных $$$n$$$.</p><p>Вы можете применять два типа операций:</p><ul> <li> выбрать два числа $$$l$$$ и $$$r$$$ ($$$l \le r$$$), а затем удалить один элемент, равный $$$l$$$, один элемент, равный $$$l + 1$$$, ..., и один элемент, равный $$$r$$$ из мультимножества. Эта операция может быть применена, только если каждый элемент от $$$l$$$ до $$$r$$$ встречается хотя бы раз в мультимножестве; </li><li> выбрать два числа $$$i$$$ и $$$x$$$ ($$$x \ge 1$$$), а затем удалить $$$x$$$ элементов равных $$$i$$$ из мультимножества. Эта операция может быть применена, только если в мультимножестве есть как минимум $$$x$$$ элементов, равных $$$i$$$. </li></ul><p>За какое наименьшее количество операций можно удалить все элементы из мультимножества?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 5000$$$).</p><p>Вторая строка содержит $$$n$$$ чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — наименьшее количество операций, за которое можно удалить все элементы из мультимножества.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 4 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
1 0 1 0 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:55</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa2769e75aae',t:'MTY5NjY2NjE5NS40MDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"] | ||
1400F | 1400 | F | ru | F. x-простые подстроки | <div class="problem-statement"><div class="header"><div class="title">F. x-простые подстроки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дано целое число $$$x$$$ и строка $$$s$$$, состоящая из цифр от $$$1$$$ до $$$9$$$ включительно.</p><p>Подстрокой строки называется последовательная подпоследовательность этой строки.</p><p>Пусть $$$f(l, r)$$$ будет равно сумме цифр в подстроке $$$s[l..r]$$$.</p><p>Назовем подстроку $$$s[l_1..r_1]$$$ <span class="tex-font-style-it">$$$x$$$-простой</span>, если </p><ul> <li> $$$f(l_1, r_1) = x$$$; </li><li> не существует таких значений $$$l_2, r_2$$$, что <ul> <li> $$$l_1 \le l_2 \le r_2 \le r_1$$$; </li><li> $$$f(l_2, r_2) \neq x$$$; </li><li> $$$x$$$ делится на $$$f(l_2, r_2)$$$. </li></ul> </li></ul><p>Разрешено удалять любые символы из строки. Если вы удаляете символ, то две полученные части строки склеиваются, не меняя порядок.</p><p>Какое минимальное количество символов надо удалить из строки, чтобы она не содержала <span class="tex-font-style-it">$$$x$$$-простых</span> подстрок? Если <span class="tex-font-style-it">$$$x$$$-простых</span> подстрок нет в данной строке $$$s$$$, то выведите $$$0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записана строка $$$s$$$ ($$$1 \le |s| \le 1000$$$). $$$s$$$ содержит только цифры от $$$1$$$ до $$$9$$$ включительно.</p><p>Во второй строке записано одно целое число $$$x$$$ ($$$1 \le x \le 20$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное количество символов, которые надо удалить из строки, чтобы она не содержала <span class="tex-font-style-it">$$$x$$$-простых</span> подстрок? Если <span class="tex-font-style-it">$$$x$$$-простых</span> подстрок нет в данной строке $$$s$$$, то выведите $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
116285317
8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
314159265359
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
13
13
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3434343434
7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере в строке две $$$8$$$-простых подстроки «<span class="tex-font-style-tt">8</span>» и «<span class="tex-font-style-tt">53</span>». Можно удалить данные символы, чтобы избавиться от обеих: «<span class="tex-font-style-tt">1162<span class="tex-font-style-underline">85</span>317</span>». Полученная строка «<span class="tex-font-style-tt">1162317</span>» не содержит $$$8$$$-простых подстрок. Также можно удалить такие символы: «<span class="tex-font-style-tt">1162<span class="tex-font-style-underline">8</span>5<span class="tex-font-style-underline">3</span>17</span>».</p><p>Во втором примере необходимо просто удалить обе единицы.</p><p>В третьем примере нет $$$13$$$-простых подстрок. В нем вообще нет подстрок с суммой цифр равной $$$13$$$.</p><p>В четвертом примере в строке не должно быть ни «<span class="tex-font-style-tt">34</span>», ни «<span class="tex-font-style-tt">43</span>». Поэтому необходимо удалить либо все тройки, либо все четверки. Их по $$$5$$$ штук, поэтому можно удалить любые из них.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="158caccaa8216d5c8620585338f7aeea"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - F - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e407f362a6da0f68cca7e0f50d624e113a539a0d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='158caccaa8216d5c8620585338f7aeea'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1400%2Fproblem%2FF%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='158caccaa8216d5c8620585338f7aeea'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1400">Educational Codeforces Round 94 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='158caccaa8216d5c8620585338f7aeea'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1400/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Суффиксные массивы, деревья и автоматы">
строковые суфф. структуры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='158caccaa8216d5c8620585338f7aeea'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="709188"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='158caccaa8216d5c8620585338f7aeea'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="709188"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81862" title="Educational Codeforces Round 94 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11742:11743" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81916" title="Unofficial Editorial for Educational Round 94 (Div. 2)" target="_blank">Разбор задач №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11751" resourceName="Unofficial Editorial for Educational Round 94 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81942" title="81942" target="_blank">Разбор задач №2</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11753:11754" resourceName="Разбор задач №2"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1400">Задачи</a></li>
<li><a
href="/contest/1400/submit">Отослать</a></li>
<li><a
href="/contest/1400/my">Мои посылки</a></li>
<li><a
href="/contest/1400/status">Статус</a></li>
<li><a
href="/contest/1400/hacks">Взломы</a></li>
<li><a
href="/contest/1400/standings">Положение</a></li>
<li><a
href="/contest/1400/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="F" data-uuid="ps_9b2e00043cedcf433fd842e9d42032e0b46fec20">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. x-простые подстроки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дано целое число $$$x$$$ и строка $$$s$$$, состоящая из цифр от $$$1$$$ до $$$9$$$ включительно.</p><p>Подстрокой строки называется последовательная подпоследовательность этой строки.</p><p>Пусть $$$f(l, r)$$$ будет равно сумме цифр в подстроке $$$s[l..r]$$$.</p><p>Назовем подстроку $$$s[l_1..r_1]$$$ <span class="tex-font-style-it">$$$x$$$-простой</span>, если </p><ul> <li> $$$f(l_1, r_1) = x$$$; </li><li> не существует таких значений $$$l_2, r_2$$$, что <ul> <li> $$$l_1 \le l_2 \le r_2 \le r_1$$$; </li><li> $$$f(l_2, r_2) \neq x$$$; </li><li> $$$x$$$ делится на $$$f(l_2, r_2)$$$. </li></ul> </li></ul><p>Разрешено удалять любые символы из строки. Если вы удаляете символ, то две полученные части строки склеиваются, не меняя порядок.</p><p>Какое минимальное количество символов надо удалить из строки, чтобы она не содержала <span class="tex-font-style-it">$$$x$$$-простых</span> подстрок? Если <span class="tex-font-style-it">$$$x$$$-простых</span> подстрок нет в данной строке $$$s$$$, то выведите $$$0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записана строка $$$s$$$ ($$$1 \le |s| \le 1000$$$). $$$s$$$ содержит только цифры от $$$1$$$ до $$$9$$$ включительно.</p><p>Во второй строке записано одно целое число $$$x$$$ ($$$1 \le x \le 20$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное количество символов, которые надо удалить из строки, чтобы она не содержала <span class="tex-font-style-it">$$$x$$$-простых</span> подстрок? Если <span class="tex-font-style-it">$$$x$$$-простых</span> подстрок нет в данной строке $$$s$$$, то выведите $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
116285317
8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
314159265359
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
13
13
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3434343434
7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере в строке две $$$8$$$-простых подстроки «<span class="tex-font-style-tt">8</span>» и «<span class="tex-font-style-tt">53</span>». Можно удалить данные символы, чтобы избавиться от обеих: «<span class="tex-font-style-tt">1162<span class="tex-font-style-underline">85</span>317</span>». Полученная строка «<span class="tex-font-style-tt">1162317</span>» не содержит $$$8$$$-простых подстрок. Также можно удалить такие символы: «<span class="tex-font-style-tt">1162<span class="tex-font-style-underline">8</span>5<span class="tex-font-style-underline">3</span>17</span>».</p><p>Во втором примере необходимо просто удалить обе единицы.</p><p>В третьем примере нет $$$13$$$-простых подстрок. В нем вообще нет подстрок с суммой цифр равной $$$13$$$.</p><p>В четвертом примере в строке не должно быть ни «<span class="tex-font-style-tt">34</span>», ни «<span class="tex-font-style-tt">43</span>». Поэтому необходимо удалить либо все тройки, либо все четверки. Их по $$$5$$$ штук, поэтому можно удалить любые из них.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:57</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa30fb553aa1',t:'MTY5NjY2NjE5Ny4xOTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u044b, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u043e\u043a\u043e\u0432\u044b\u0435 \u0441\u0443\u0444\u0444. \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b", "*2800"] | ||
1400G | 1400 | G | ru | G. Наемники | <div class="problem-statement"><div class="header"><div class="title">G. Наемники</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в (очередную) стратегическую компьютерную игру. В этой игре он управляет армией наемников.</p><p>Поликарп хочет собрать свою армию для выполнения задания. Для найма доступны $$$n$$$ наемников, и армия Поликарпа должна состоять из некоторого подмножества множества доступных наемников.</p><p>$$$i$$$-го наемника можно выбрать только в том случае, если <span class="tex-font-style-bf">итоговое</span> количество выбранных наемников не менее $$$l_i$$$ (иначе этот наемник считает задание слишком опасным) и не более $$$r_i$$$ (он не хочет делить добычу со слишком большим количеством других наемников). Кроме того, $$$m$$$ пар наемников ненавидят друг друга, и из каждой такой пары можно взять на задание не более одного наемника. </p><p>Сколько <span class="tex-font-style-bf">непустых</span> подмножеств наемников Поликарп должен рассмотреть? Другими словами, посчитайте количество подмножеств наемников, которые не содержат пар наемников, ненавидящих друг друга, и размер которых принадлежит отрезку $$$[l_i, r_i]$$$ для каждого наемника из подмножества.</p><p>Ответ может быть очень большим, поэтому посчитайте его по модулю $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$0 \le m \le \min(20, \dfrac{n(n-1)}{2})$$$) — количество наемников и количество пар наемников, ненавидящих друг друга, соответственно.</p><p>Далее следуют $$$n$$$ строк, в $$$i$$$-й из которых заданы два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).</p><p>Далее следуют $$$m$$$ строк, в $$$i$$$-й из которых заданы два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i < b_i \le n$$$), обозначающих, что наемники $$$a_i$$$ и $$$b_i$$$ ненавидят друг друга. Все заданные пары различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество подмножеств, удовлетворяющих условию задачи, взятое по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 0
1 1
2 3
1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 1
1 1
2 3
1 3
2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="22d8e428e053ccf86362dd4ef26feefd"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - G - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e407f362a6da0f68cca7e0f50d624e113a539a0d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - G - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='22d8e428e053ccf86362dd4ef26feefd'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div style="padding:0.5em 0 0 2px;color:#00a651;">
<a href="/harbourspace"><img style="position:relative; bottom:6px;" src="//assets.codeforces.com/images/hsu.png"/></a>
</div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1400%2Fproblem%2FG%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='22d8e428e053ccf86362dd4ef26feefd'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1400">Educational Codeforces Round 94 (рейтинговый для Див. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='22d8e428e053ccf86362dd4ef26feefd'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1400/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Битовые маски">
битмаски
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика">
комбинаторика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств">
снм
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='22d8e428e053ccf86362dd4ef26feefd'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="709189"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='22d8e428e053ccf86362dd4ef26feefd'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="709189"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81862" title="Educational Codeforces Round 94 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11742:11743" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81916" title="Unofficial Editorial for Educational Round 94 (Div. 2)" target="_blank">Разбор задач №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11751" resourceName="Unofficial Editorial for Educational Round 94 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81942" title="81942" target="_blank">Разбор задач №2</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11753:11754" resourceName="Разбор задач №2"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1400">Задачи</a></li>
<li><a
href="/contest/1400/submit">Отослать</a></li>
<li><a
href="/contest/1400/my">Мои посылки</a></li>
<li><a
href="/contest/1400/status">Статус</a></li>
<li><a
href="/contest/1400/hacks">Взломы</a></li>
<li><a
href="/contest/1400/standings">Положение</a></li>
<li><a
href="/contest/1400/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="G" data-uuid="ps_332d1b34190122dc42174a47ad8f662b6765a00d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Наемники</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в (очередную) стратегическую компьютерную игру. В этой игре он управляет армией наемников.</p><p>Поликарп хочет собрать свою армию для выполнения задания. Для найма доступны $$$n$$$ наемников, и армия Поликарпа должна состоять из некоторого подмножества множества доступных наемников.</p><p>$$$i$$$-го наемника можно выбрать только в том случае, если <span class="tex-font-style-bf">итоговое</span> количество выбранных наемников не менее $$$l_i$$$ (иначе этот наемник считает задание слишком опасным) и не более $$$r_i$$$ (он не хочет делить добычу со слишком большим количеством других наемников). Кроме того, $$$m$$$ пар наемников ненавидят друг друга, и из каждой такой пары можно взять на задание не более одного наемника. </p><p>Сколько <span class="tex-font-style-bf">непустых</span> подмножеств наемников Поликарп должен рассмотреть? Другими словами, посчитайте количество подмножеств наемников, которые не содержат пар наемников, ненавидящих друг друга, и размер которых принадлежит отрезку $$$[l_i, r_i]$$$ для каждого наемника из подмножества.</p><p>Ответ может быть очень большим, поэтому посчитайте его по модулю $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 3 \cdot 10^5$$$, $$$0 \le m \le \min(20, \dfrac{n(n-1)}{2})$$$) — количество наемников и количество пар наемников, ненавидящих друг друга, соответственно.</p><p>Далее следуют $$$n$$$ строк, в $$$i$$$-й из которых заданы два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).</p><p>Далее следуют $$$m$$$ строк, в $$$i$$$-й из которых заданы два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i < b_i \le n$$$), обозначающих, что наемники $$$a_i$$$ и $$$b_i$$$ ненавидят друг друга. Все заданные пары различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество подмножеств, удовлетворяющих условию задачи, взятое по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 0
1 1
2 3
1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 1
1 1
2 3
1 3
2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=G]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:09:58</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa3c5daf78ff',t:'MTY5NjY2NjE5OC43NjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043d\u043c", "*2600"] | ||
1401A | 1401 | A | ru | A. Дистанция и ось | <div class="problem-statement"><div class="header"><div class="title">A. Дистанция и ось</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана точка $$$A$$$ с координатой $$$x = n$$$ на оси $$$OX$$$. Вам хотелось бы найти такую <span class="tex-font-style-it">целочисленную точку</span> $$$B$$$ (также на оси $$$OX$$$), что <span class="tex-font-style-it">модуль разности</span> между расстоянием от $$$O$$$ до $$$B$$$ и расстоянием от $$$A$$$ до $$$B$$$ равен $$$k$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4f63bd211e18b7371616a82218bed31ef22ade41.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Описание первого набора входных данных.</span> </center><p>Так как иногда невозможно найти такую точку $$$B$$$, вы можете за один шаг увеличить или уменьшить координату $$$A$$$ на $$$1$$$. Какое минимальное количество шагов необходимо сделать, чтобы такая точка $$$B$$$ существовала?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 6000$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора заданы два целых числа $$$n$$$ и $$$k$$$ ($$$0 \le n, k \le 10^6$$$) — первоначальная позиция точки $$$A$$$ и желаемый модуль разности.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите минимальное количество шагов, необходимых для существования точки $$$B$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
3
1000000
0
1
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных (изображение выше), если мы выберем координату $$$B$$$ как $$$2$$$, то модуль разности будет равен $$$|(2 - 0) - (4 - 2)| = 0$$$ и нам не нужно передвигать $$$A$$$. Поэтому ответ равен $$$0$$$.</p><p>Во втором наборе входных данных, мы можем увеличить координату $$$A$$$ на $$$3$$$ и выбрать координату $$$B$$$ как $$$0$$$ или $$$8$$$. Модуль разности в таком случае будет равен $$$|8 - 0| = 8$$$, то есть ответ равен $$$3$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a2a4dc378eafaf06d142097a1ccfebca6b493783.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="ec0238b2c31b4ccf820288d3c7579476"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="480ac616998a69d96ccc2a9ce3c755d389b9f229"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='ec0238b2c31b4ccf820288d3c7579476'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1401%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='ec0238b2c31b4ccf820288d3c7579476'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1401">Codeforces Round 665 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='ec0238b2c31b4ccf820288d3c7579476'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1401/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*900
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ec0238b2c31b4ccf820288d3c7579476'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="704913"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ec0238b2c31b4ccf820288d3c7579476'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="704913"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81697" title="Codeforces Round #665 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11733" resourceName="Codeforces Round #665 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81700" title="Codeforces Round #665 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11738" resourceName="Codeforces Round #665 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1401">Задачи</a></li>
<li><a
href="/contest/1401/submit">Отослать</a></li>
<li><a
href="/contest/1401/my">Мои посылки</a></li>
<li><a
href="/contest/1401/status">Статус</a></li>
<li><a
href="/contest/1401/hacks">Взломы</a></li>
<li><a
href="/contest/1401/room/1">Комната</a></li>
<li><a
href="/contest/1401/standings">Положение</a></li>
<li><a
href="/contest/1401/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_d5e71e806668b1a60c2a594e4afbba2ac34fcdec">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Дистанция и ось</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана точка $$$A$$$ с координатой $$$x = n$$$ на оси $$$OX$$$. Вам хотелось бы найти такую <span class="tex-font-style-it">целочисленную точку</span> $$$B$$$ (также на оси $$$OX$$$), что <span class="tex-font-style-it">модуль разности</span> между расстоянием от $$$O$$$ до $$$B$$$ и расстоянием от $$$A$$$ до $$$B$$$ равен $$$k$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4f63bd211e18b7371616a82218bed31ef22ade41.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Описание первого набора входных данных.</span> </center><p>Так как иногда невозможно найти такую точку $$$B$$$, вы можете за один шаг увеличить или уменьшить координату $$$A$$$ на $$$1$$$. Какое минимальное количество шагов необходимо сделать, чтобы такая точка $$$B$$$ существовала?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 6000$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора заданы два целых числа $$$n$$$ и $$$k$$$ ($$$0 \le n, k \le 10^6$$$) — первоначальная позиция точки $$$A$$$ и желаемый модуль разности.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите минимальное количество шагов, необходимых для существования точки $$$B$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
3
1000000
0
1
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных (изображение выше), если мы выберем координату $$$B$$$ как $$$2$$$, то модуль разности будет равен $$$|(2 - 0) - (4 - 2)| = 0$$$ и нам не нужно передвигать $$$A$$$. Поэтому ответ равен $$$0$$$.</p><p>Во втором наборе входных данных, мы можем увеличить координату $$$A$$$ на $$$3$$$ и выбрать координату $$$B$$$ как $$$0$$$ или $$$8$$$. Модуль разности в таком случае будет равен $$$|8 - 0| = 8$$$, то есть ответ равен $$$3$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a2a4dc378eafaf06d142097a1ccfebca6b493783.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:00</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa45ee560069',t:'MTY5NjY2NjIwMC4yNTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*900"] | ||
1401B | 1401 | B | ru | B. Троичная последовательность | <div class="problem-statement"><div class="header"><div class="title">B. Троичная последовательность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы две последовательности $$$a_1, a_2, \dots, a_n$$$ и $$$b_1, b_2, \dots, b_n$$$. Каждый элемент обеих последовательностей — это $$$0$$$, $$$1$$$ или $$$2$$$. Количество чисел $$$0$$$, $$$1$$$, $$$2$$$ в последовательности $$$a$$$ равно $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ соответственно, а количество чисел $$$0$$$, $$$1$$$, $$$2$$$ в последовательности $$$b$$$ равно $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ соответственно.</p><p>Вы можете переставить элементы в обеих последовательностях $$$a$$$ и $$$b$$$ как захотите. После этого, определим последовательность $$$c$$$ следующим образом:</p><p>$$$c_i = \begin{cases} a_i b_i & \mbox{если }a_i > b_i \\ 0 & \mbox{если }a_i = b_i \\ -a_i b_i & \mbox{если }a_i < b_i \end{cases}$$$</p><p>Вам нужно сделать $$$\sum_{i=1}^n c_i$$$ (сумму всех элементов последовательности $$$c$$$) как можно больше. Какую максимально возможную сумму можно получить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из двух строк. В первой строке каждого набора заданы три целых числа $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ ($$$0 \le x_1, y_1, z_1 \le 10^8$$$) — количество $$$0$$$-й, $$$1$$$-ц и $$$2$$$-к в последовательности $$$a$$$.</p><p>Во второй строке каждого набора заданы три целых числа $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ ($$$0 \le x_2, y_2, z_2 \le 10^8$$$; $$$x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$$$) — количество $$$0$$$-й, $$$1$$$-ц и $$$2$$$-к в последовательности $$$b$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите максимально возможную сумму последовательности $$$c$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
2 3 2
3 3 1
4 0 1
2 3 0
0 0 1
0 0 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
2
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, одно из оптимальнных решений следующее:</p><p>$$$a = \{2, 0, 1, 1, 0, 2, 1\}$$$</p><p>$$$b = \{1, 0, 1, 0, 2, 1, 0\}$$$</p><p>$$$c = \{2, 0, 0, 0, 0, 2, 0\}$$$</p><p>Во втором наборе, одно из оптимальных решений следующее:</p><p>$$$a = \{0, 2, 0, 0, 0\}$$$</p><p>$$$b = \{1, 1, 0, 1, 0\}$$$</p><p>$$$c = \{0, 2, 0, 0, 0\}$$$</p><p>В третьем наборе, единственное решение следующее:</p><p>$$$a = \{2\}$$$</p><p>$$$b = \{2\}$$$</p><p>$$$c = \{0\}$$$</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="7f6eab05ad4acb6b27c8cf7da0045b01"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="480ac616998a69d96ccc2a9ce3c755d389b9f229"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='7f6eab05ad4acb6b27c8cf7da0045b01'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1401%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='7f6eab05ad4acb6b27c8cf7da0045b01'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1401">Codeforces Round 665 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='7f6eab05ad4acb6b27c8cf7da0045b01'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1401/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1100
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7f6eab05ad4acb6b27c8cf7da0045b01'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="704914"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7f6eab05ad4acb6b27c8cf7da0045b01'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="704914"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81697" title="Codeforces Round #665 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11733" resourceName="Codeforces Round #665 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81700" title="Codeforces Round #665 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11738" resourceName="Codeforces Round #665 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1401">Задачи</a></li>
<li><a
href="/contest/1401/submit">Отослать</a></li>
<li><a
href="/contest/1401/my">Мои посылки</a></li>
<li><a
href="/contest/1401/status">Статус</a></li>
<li><a
href="/contest/1401/hacks">Взломы</a></li>
<li><a
href="/contest/1401/room/1">Комната</a></li>
<li><a
href="/contest/1401/standings">Положение</a></li>
<li><a
href="/contest/1401/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_8a2d404232bfc3865571db90b2499c5564415580">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Троичная последовательность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы две последовательности $$$a_1, a_2, \dots, a_n$$$ и $$$b_1, b_2, \dots, b_n$$$. Каждый элемент обеих последовательностей — это $$$0$$$, $$$1$$$ или $$$2$$$. Количество чисел $$$0$$$, $$$1$$$, $$$2$$$ в последовательности $$$a$$$ равно $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ соответственно, а количество чисел $$$0$$$, $$$1$$$, $$$2$$$ в последовательности $$$b$$$ равно $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ соответственно.</p><p>Вы можете переставить элементы в обеих последовательностях $$$a$$$ и $$$b$$$ как захотите. После этого, определим последовательность $$$c$$$ следующим образом:</p><p>$$$c_i = \begin{cases} a_i b_i & \mbox{если }a_i > b_i \\ 0 & \mbox{если }a_i = b_i \\ -a_i b_i & \mbox{если }a_i < b_i \end{cases}$$$</p><p>Вам нужно сделать $$$\sum_{i=1}^n c_i$$$ (сумму всех элементов последовательности $$$c$$$) как можно больше. Какую максимально возможную сумму можно получить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из двух строк. В первой строке каждого набора заданы три целых числа $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ ($$$0 \le x_1, y_1, z_1 \le 10^8$$$) — количество $$$0$$$-й, $$$1$$$-ц и $$$2$$$-к в последовательности $$$a$$$.</p><p>Во второй строке каждого набора заданы три целых числа $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ ($$$0 \le x_2, y_2, z_2 \le 10^8$$$; $$$x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$$$) — количество $$$0$$$-й, $$$1$$$-ц и $$$2$$$-к в последовательности $$$b$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите максимально возможную сумму последовательности $$$c$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
2 3 2
3 3 1
4 0 1
2 3 0
0 0 1
0 0 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
2
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, одно из оптимальнных решений следующее:</p><p>$$$a = \{2, 0, 1, 1, 0, 2, 1\}$$$</p><p>$$$b = \{1, 0, 1, 0, 2, 1, 0\}$$$</p><p>$$$c = \{2, 0, 0, 0, 0, 2, 0\}$$$</p><p>Во втором наборе, одно из оптимальных решений следующее:</p><p>$$$a = \{0, 2, 0, 0, 0\}$$$</p><p>$$$b = \{1, 1, 0, 1, 0\}$$$</p><p>$$$c = \{0, 2, 0, 0, 0\}$$$</p><p>В третьем наборе, единственное решение следующее:</p><p>$$$a = \{2\}$$$</p><p>$$$b = \{2\}$$$</p><p>$$$c = \{0\}$$$</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:01</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa4f79539d6f',t:'MTY5NjY2NjIwMS42OTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1100"] | ||
1401C | 1401 | C | ru | C. Просто массив | <div class="problem-statement"><div class="header"><div class="title">C. Просто массив</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a_1, a_2, \dots, a_n$$$, в котором все $$$a_i$$$ — целые и больше $$$0$$$.</p><p>За одну операцию вы можете выбрать две различные позиции $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$). Если $$$gcd(a_i, a_j)$$$ равен минимуму <span class="tex-font-style-bf">всего массива</span> $$$a$$$, то вы можете поменять местами $$$a_i$$$ и $$$a_j$$$. $$$gcd(x, y)$$$ означает <a href="https://ru.wikipedia.org/wiki/Наибольший_общий_делитель">наибольших общий делитель (НОД)</a> чисел $$$x$$$ и $$$y$$$.</p><p>Вам нужно сделать массив $$$a$$$ неубывающим, используя заданную операцию произвольное количество раз (возможно, ни разу). Определите, возможно ли это.</p><p>Массив $$$a$$$ — неубывающий, тогда и только тогда, когда $$$a_1 \le a_2 \le \ldots \le a_n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — длина массива $$$a$$$.</p><p>Во второй строке каждого набора заданы $$$n$$$ положительных целых чисел $$$a_1, a_2, \ldots a_n$$$ ($$$1 \le a_i \le 10^9$$$) — сам массив.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора, выведите «<span class="tex-font-style-tt">YES</span>», если возможно сделать массив $$$a$$$ неубывающим, используя описанную выше операцию, или «<span class="tex-font-style-tt">NO</span>» в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1
8
6
4 3 6 6 2 9
4
4 5 6 7
5
7 5 2 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и третьем наборах, массив уже неубывающий.</p><p>Во втором наборе, мы можем сначала свапнуть $$$a_1$$$ и $$$a_3$$$, а потом $$$a_1$$$ и $$$a_5$$$, и получим неубывающий массив.</p><p>В четвертом наборе, невозможно сделать массив неубывающим, используя заданную операцию.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="2ca5e425cf3f29b8b91c76f388ae383d"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="480ac616998a69d96ccc2a9ce3c755d389b9f229"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='2ca5e425cf3f29b8b91c76f388ae383d'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1401%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='2ca5e425cf3f29b8b91c76f388ae383d'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1401">Codeforces Round 665 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='2ca5e425cf3f29b8b91c76f388ae383d'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1401/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2ca5e425cf3f29b8b91c76f388ae383d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="704915"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2ca5e425cf3f29b8b91c76f388ae383d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="704915"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81697" title="Codeforces Round #665 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11733" resourceName="Codeforces Round #665 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81700" title="Codeforces Round #665 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11738" resourceName="Codeforces Round #665 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1401">Задачи</a></li>
<li><a
href="/contest/1401/submit">Отослать</a></li>
<li><a
href="/contest/1401/my">Мои посылки</a></li>
<li><a
href="/contest/1401/status">Статус</a></li>
<li><a
href="/contest/1401/hacks">Взломы</a></li>
<li><a
href="/contest/1401/room/1">Комната</a></li>
<li><a
href="/contest/1401/standings">Положение</a></li>
<li><a
href="/contest/1401/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_becd44ad252bad6b87d7d8884274f6219925e273">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Просто массив</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a_1, a_2, \dots, a_n$$$, в котором все $$$a_i$$$ — целые и больше $$$0$$$.</p><p>За одну операцию вы можете выбрать две различные позиции $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$). Если $$$gcd(a_i, a_j)$$$ равен минимуму <span class="tex-font-style-bf">всего массива</span> $$$a$$$, то вы можете поменять местами $$$a_i$$$ и $$$a_j$$$. $$$gcd(x, y)$$$ означает <a href="https://ru.wikipedia.org/wiki/Наибольший_общий_делитель">наибольших общий делитель (НОД)</a> чисел $$$x$$$ и $$$y$$$.</p><p>Вам нужно сделать массив $$$a$$$ неубывающим, используя заданную операцию произвольное количество раз (возможно, ни разу). Определите, возможно ли это.</p><p>Массив $$$a$$$ — неубывающий, тогда и только тогда, когда $$$a_1 \le a_2 \le \ldots \le a_n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — длина массива $$$a$$$.</p><p>Во второй строке каждого набора заданы $$$n$$$ положительных целых чисел $$$a_1, a_2, \ldots a_n$$$ ($$$1 \le a_i \le 10^9$$$) — сам массив.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора, выведите «<span class="tex-font-style-tt">YES</span>», если возможно сделать массив $$$a$$$ неубывающим, используя описанную выше операцию, или «<span class="tex-font-style-tt">NO</span>» в противном случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1
8
6
4 3 6 6 2 9
4
4 5 6 7
5
7 5 2 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и третьем наборах, массив уже неубывающий.</p><p>Во втором наборе, мы можем сначала свапнуть $$$a_1$$$ и $$$a_3$$$, а потом $$$a_1$$$ и $$$a_5$$$, и получим неубывающий массив.</p><p>В четвертом наборе, невозможно сделать массив неубывающим, используя заданную операцию.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:03</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa5878021622',t:'MTY5NjY2NjIwMy4wNzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1300"] | ||
1401D | 1401 | D | ru | D. Максимально распределенное дерево | <div class="problem-statement"><div class="header"><div class="title">D. Максимально распределенное дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано дерево, состоящее из $$$n$$$ вершин. Вы должны сопоставить каждому из $$$n-1$$$ ребер этого дерева целое число таким образом, чтобы выполнялись следующие условия: </p><ul> <li> каждое число должно быть целым и строго больше $$$0$$$; </li><li> произведение всех $$$n-1$$$ чисел должно быть равно $$$k$$$; </li><li> количество $$$1$$$-ц среди всех $$$n-1$$$ чисел должно быть минимально возможным. </li></ul><p>Назовем $$$f(u,v)$$$ сумму чисел на простом пути из вершины $$$u$$$ в вершину $$$v$$$. Также, назовем $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ как <span class="tex-font-style-it">индекс распределения</span> дерева.</p><p>Определите максимально возможный индекс распределения, который можно получить. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>В данной задаче, так как число $$$k$$$ может быть слишком большим, задана факторизация $$$k$$$ на простые числа.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — количество вершин в дереве.</p><p>В каждой из следующих $$$n-1$$$ строк заданы ребра: в $$$i$$$-й строке заданы два целых числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — номера вершин, соединенных $$$i$$$-м ребром.</p><p>В следующей строке задано одно число $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — количество простых в факторизации $$$k$$$.</p><p>В следующей строке заданы $$$m$$$ простых чисел $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i < 6 \cdot 10^4$$$) такие, что $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$, сумма $$$m$$$ по всем наборам не превосходит $$$6 \cdot 10^4$$$, и что заданные ребра в каждом наборе образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите максимально возможный индекс распределения. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
4
1 2
2 3
3 4
2
2 2
4
3 4
1 3
3 2
2
3 2
7
6 1
2 3
4 6
7 3
5 1
3 6
4
7 5 13 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
17
18
286
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, один из возможных ответов изображен на рисунке ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/548855972f7faf9a924af791112b586a9df294ee.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В данном случае, $$$f(1,2)=1$$$, $$$f(1,3)=3$$$, $$$f(1,4)=5$$$, $$$f(2,3)=2$$$, $$$f(2,4)=4$$$, $$$f(3,4)=2$$$, и сумма этих $$$6$$$ чисел равна $$$17$$$.</p><p>Во втором наборе входных данных, один из возможных ответов изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/312dfe6b8963b0f7d9d2a887e13609d94da80b38.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В этом случае, $$$f(1,2)=3$$$, $$$f(1,3)=1$$$, $$$f(1,4)=4$$$, $$$f(2,3)=2$$$, $$$f(2,4)=5$$$, $$$f(3,4)=3$$$, и сумма этих $$$6$$$ чисел равна $$$18$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="3eb16c6e26c32d1538772ae3c01dac01"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="480ac616998a69d96ccc2a9ce3c755d389b9f229"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='3eb16c6e26c32d1538772ae3c01dac01'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1401%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='3eb16c6e26c32d1538772ae3c01dac01'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1401">Codeforces Round 665 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='3eb16c6e26c32d1538772ae3c01dac01'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1401/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3eb16c6e26c32d1538772ae3c01dac01'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="704916"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3eb16c6e26c32d1538772ae3c01dac01'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="704916"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81697" title="Codeforces Round #665 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11733" resourceName="Codeforces Round #665 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81700" title="Codeforces Round #665 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11738" resourceName="Codeforces Round #665 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1401">Задачи</a></li>
<li><a
href="/contest/1401/submit">Отослать</a></li>
<li><a
href="/contest/1401/my">Мои посылки</a></li>
<li><a
href="/contest/1401/status">Статус</a></li>
<li><a
href="/contest/1401/hacks">Взломы</a></li>
<li><a
href="/contest/1401/room/1">Комната</a></li>
<li><a
href="/contest/1401/standings">Положение</a></li>
<li><a
href="/contest/1401/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_b41c1a1d52d1eb754ace967498ee13f05e650c55">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Максимально распределенное дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано дерево, состоящее из $$$n$$$ вершин. Вы должны сопоставить каждому из $$$n-1$$$ ребер этого дерева целое число таким образом, чтобы выполнялись следующие условия: </p><ul> <li> каждое число должно быть целым и строго больше $$$0$$$; </li><li> произведение всех $$$n-1$$$ чисел должно быть равно $$$k$$$; </li><li> количество $$$1$$$-ц среди всех $$$n-1$$$ чисел должно быть минимально возможным. </li></ul><p>Назовем $$$f(u,v)$$$ сумму чисел на простом пути из вершины $$$u$$$ в вершину $$$v$$$. Также, назовем $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ как <span class="tex-font-style-it">индекс распределения</span> дерева.</p><p>Определите максимально возможный индекс распределения, который можно получить. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>В данной задаче, так как число $$$k$$$ может быть слишком большим, задана факторизация $$$k$$$ на простые числа.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — количество вершин в дереве.</p><p>В каждой из следующих $$$n-1$$$ строк заданы ребра: в $$$i$$$-й строке заданы два целых числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — номера вершин, соединенных $$$i$$$-м ребром.</p><p>В следующей строке задано одно число $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — количество простых в факторизации $$$k$$$.</p><p>В следующей строке заданы $$$m$$$ простых чисел $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i < 6 \cdot 10^4$$$) такие, что $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$, сумма $$$m$$$ по всем наборам не превосходит $$$6 \cdot 10^4$$$, и что заданные ребра в каждом наборе образуют дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите максимально возможный индекс распределения. Так как ответ может быть слишком большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
4
1 2
2 3
3 4
2
2 2
4
3 4
1 3
3 2
2
3 2
7
6 1
2 3
4 6
7 3
5 1
3 6
4
7 5 13 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
17
18
286
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, один из возможных ответов изображен на рисунке ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/548855972f7faf9a924af791112b586a9df294ee.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В данном случае, $$$f(1,2)=1$$$, $$$f(1,3)=3$$$, $$$f(1,4)=5$$$, $$$f(2,3)=2$$$, $$$f(2,4)=4$$$, $$$f(3,4)=2$$$, и сумма этих $$$6$$$ чисел равна $$$17$$$.</p><p>Во втором наборе входных данных, один из возможных ответов изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/312dfe6b8963b0f7d9d2a887e13609d94da80b38.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В этом случае, $$$f(1,2)=3$$$, $$$f(1,3)=1$$$, $$$f(1,4)=4$$$, $$$f(2,3)=2$$$, $$$f(2,4)=5$$$, $$$f(3,4)=3$$$, и сумма этих $$$6$$$ чисел равна $$$18$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:04</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa60de977a75',t:'MTY5NjY2NjIwNC40MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1800"] | ||
1401E | 1401 | E | ru | E. Разбиваем квадрат | <div class="problem-statement"><div class="header"><div class="title">E. Разбиваем квадрат</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>384 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть квадрат размера $$$10^6 \times 10^6$$$ на координатной плоскости с вершинами в точках $$$(0, 0)$$$, $$$(0, 10^6)$$$, $$$(10^6, 0)$$$ и $$$(10^6, 10^6)$$$.</p><p>Вы собираетесь нарисовать несколько отрезков на плоскости. Все отрезки либо горизонтальные, либо вертикальные и <span class="tex-font-style-it">пересекаются хотя бы с одной стороной квадрата</span>.</p><p>Сейчас вас интересует: на какое количество частей разобьется данный квадрат после того, как будут нарисованы все отрезки. Напишите программу, подсчитывающую количество частей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$0 \le n, m \le 10^5$$$) — количество горизонтальных и вертикальных отрезков, соответственно.</p><p>В следующих $$$n$$$ строках заданы описания горизонтальных отрезков. В $$$i$$$-й строке заданы три целых числа $$$y_i$$$, $$$lx_i$$$ и $$$rx_i$$$ ($$$0 < y_i < 10^6$$$; $$$0 \le lx_i < rx_i \le 10^6$$$), означающих отрезок, соединяющий $$$(lx_i, y_i)$$$ и $$$(rx_i, y_i)$$$.</p><p>В следующих $$$m$$$ строках заданы описания вертикальных отрезков. В $$$i$$$-й строке заданы три целых числа $$$x_i$$$, $$$ly_i$$$ и $$$ry_i$$$ ($$$0 < x_i < 10^6$$$; $$$0 \le ly_i < ry_i \le 10^6$$$), означающих отрезок, соединяющий $$$(x_i, ly_i)$$$ и $$$(x_i, ry_i)$$$.</p><p>Гарантируется, что <span class="tex-font-style-bf">никакие два отрезка не лежат на одной прямой</span> и каждый отрезок пересекается хотя бы с одной стороной квадрата.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество частей, на которые разбивается квадрат после того, как нарисованы все отрезки.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пример выглядит следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4fb4163286ad6104b3533b82eea157163408ac4d.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="dab615aff487a4b4d5f4c68ef874f3ba"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="480ac616998a69d96ccc2a9ce3c755d389b9f229"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='dab615aff487a4b4d5f4c68ef874f3ba'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1401%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='dab615aff487a4b4d5f4c68ef874f3ba'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1401">Codeforces Round 665 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='dab615aff487a4b4d5f4c68ef874f3ba'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1401/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Геометрия">
геометрия
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dab615aff487a4b4d5f4c68ef874f3ba'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="704917"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dab615aff487a4b4d5f4c68ef874f3ba'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="704917"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81697" title="Codeforces Round #665 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11733" resourceName="Codeforces Round #665 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81700" title="Codeforces Round #665 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11738" resourceName="Codeforces Round #665 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1401">Задачи</a></li>
<li><a
href="/contest/1401/submit">Отослать</a></li>
<li><a
href="/contest/1401/my">Мои посылки</a></li>
<li><a
href="/contest/1401/status">Статус</a></li>
<li><a
href="/contest/1401/hacks">Взломы</a></li>
<li><a
href="/contest/1401/room/1">Комната</a></li>
<li><a
href="/contest/1401/standings">Положение</a></li>
<li><a
href="/contest/1401/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_517028d14e16f467549e38b4e50a7deb767498e8">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Разбиваем квадрат</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>384 мегабайта</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть квадрат размера $$$10^6 \times 10^6$$$ на координатной плоскости с вершинами в точках $$$(0, 0)$$$, $$$(0, 10^6)$$$, $$$(10^6, 0)$$$ и $$$(10^6, 10^6)$$$.</p><p>Вы собираетесь нарисовать несколько отрезков на плоскости. Все отрезки либо горизонтальные, либо вертикальные и <span class="tex-font-style-it">пересекаются хотя бы с одной стороной квадрата</span>.</p><p>Сейчас вас интересует: на какое количество частей разобьется данный квадрат после того, как будут нарисованы все отрезки. Напишите программу, подсчитывающую количество частей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$0 \le n, m \le 10^5$$$) — количество горизонтальных и вертикальных отрезков, соответственно.</p><p>В следующих $$$n$$$ строках заданы описания горизонтальных отрезков. В $$$i$$$-й строке заданы три целых числа $$$y_i$$$, $$$lx_i$$$ и $$$rx_i$$$ ($$$0 < y_i < 10^6$$$; $$$0 \le lx_i < rx_i \le 10^6$$$), означающих отрезок, соединяющий $$$(lx_i, y_i)$$$ и $$$(rx_i, y_i)$$$.</p><p>В следующих $$$m$$$ строках заданы описания вертикальных отрезков. В $$$i$$$-й строке заданы три целых числа $$$x_i$$$, $$$ly_i$$$ и $$$ry_i$$$ ($$$0 < x_i < 10^6$$$; $$$0 \le ly_i < ry_i \le 10^6$$$), означающих отрезок, соединяющий $$$(x_i, ly_i)$$$ и $$$(x_i, ry_i)$$$.</p><p>Гарантируется, что <span class="tex-font-style-bf">никакие два отрезка не лежат на одной прямой</span> и каждый отрезок пересекается хотя бы с одной стороной квадрата.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество частей, на которые разбивается квадрат после того, как нарисованы все отрезки.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 3
2 3 1000000
4 0 4
3 0 1000000
4 0 1
2 0 5
3 1 1000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пример выглядит следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/4fb4163286ad6104b3533b82eea157163408ac4d.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:05</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa6989f59da4',t:'MTY5NjY2NjIwNS44MDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"] | ||
1401F | 1401 | F | ru | F. Reverse и Swap | <div class="problem-statement"><div class="header"><div class="title">F. Reverse и Swap</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a$$$ длины $$$2^n$$$. Вам нужно обработать $$$q$$$ запросов к нему. Каждый запрос одного из следующих $$$4$$$ типов: </p><ol> <li> $$$Replace(x, k)$$$ — присвоить элементу $$$a_x$$$ значение $$$k$$$; </li><li> $$$Reverse(k)$$$ — развернуть каждый подмассив $$$[(i-1) \cdot 2^k+1, i \cdot 2^k]$$$ для всех $$$i$$$ ($$$i \ge 1$$$); </li><li> $$$Swap(k)$$$ — поменять местами подмассивы $$$[(2i-2) \cdot 2^k+1, (2i-1) \cdot 2^k]$$$ и $$$[(2i-1) \cdot 2^k+1, 2i \cdot 2^k]$$$ для всех $$$i$$$ ($$$i \ge 1$$$); </li><li> $$$Sum(l, r)$$$ — вывести сумму элементов подмассива $$$[l, r]$$$. </li></ol><p>Напишите программу, которая может достаточно быстро обрабатывать заданные запросы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$, $$$q$$$ ($$$0 \le n \le 18$$$; $$$1 \le q \le 10^5$$$) — длина массива $$$a$$$ и количество запросов.</p><p>Во второй строке заданы $$$2^n$$$ целых чисел $$$a_1, a_2, \ldots, a_{2^n}$$$ ($$$0 \le a_i \le 10^9$$$).</p><p>В следующих $$$q$$$ строках заданы запросы — по одному в строке. Каждый запрос одного из следующих $$$4$$$ типов: </p><ul> <li> «$$$1$$$ $$$x$$$ $$$k$$$» ($$$1 \le x \le 2^n$$$; $$$0 \le k \le 10^9$$$) — $$$Replace(x, k)$$$; </li><li> «$$$2$$$ $$$k$$$» ($$$0 \le k \le n$$$) — $$$Reverse(k)$$$; </li><li> «$$$3$$$ $$$k$$$» ($$$0 \le k < n$$$) — $$$Swap(k)$$$; </li><li> «$$$4$$$ $$$l$$$ $$$r$$$» ($$$1 \le l \le r \le 2^n$$$) — $$$Sum(l, r)$$$. </li></ul><p>Гарантируется, что в каждом тесте есть как минимум один запрос $$$Sum$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответы для каждого запроса $$$Sum$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2 3
7 4 9 9
1 2 8
3 1
4 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
24
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 8
7 0 8 8 7 1 5 2
4 3 7
2 1
3 2
4 1 6
2 3
1 5 16
4 8 8
3 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
29
22
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, первоначально, массив $$$a$$$ равен $$$\{7,4,9,9\}$$$.</p><p>После обработки первого запроса, массив $$$a$$$ становится $$$\{7,8,9,9\}$$$.</p><p>После обработки второго запроса, массив $$$a_i$$$ становится $$$\{9,9,7,8\}$$$.</p><p>Поэтому, ответ на третий запрос равен $$$9+7+8=24$$$.</p><p>Во втором примере, первоначально, массив $$$a$$$ равен $$$\{7,0,8,8,7,1,5,2\}$$$. Далее происходит следующее: </p><ol> <li> $$$Sum(3, 7)$$$ $$$\to$$$ $$$8 + 8 + 7 + 1 + 5 = 29$$$; </li><li> $$$Reverse(1)$$$ $$$\to$$$ $$$\{0,7,8,8,1,7,2,5\}$$$; </li><li> $$$Swap(2)$$$ $$$\to$$$ $$$\{1,7,2,5,0,7,8,8\}$$$; </li><li> $$$Sum(1, 6)$$$ $$$\to$$$ $$$1 + 7 + 2 + 5 + 0 + 7 = 22$$$; </li><li> $$$Reverse(3)$$$ $$$\to$$$ $$$\{8,8,7,0,5,2,7,1\}$$$; </li><li> $$$Replace(5, 16)$$$ $$$\to$$$ $$$\{8,8,7,0,16,2,7,1\}$$$; </li><li> $$$Sum(8, 8)$$$ $$$\to$$$ $$$1$$$; </li><li> $$$Swap(0)$$$ $$$\to$$$ $$$\{8,8,0,7,2,16,1,7\}$$$. </li></ol></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="d4bb27227c1e67e3a1338fa81e056d52"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - F - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="480ac616998a69d96ccc2a9ce3c755d389b9f229"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='d4bb27227c1e67e3a1338fa81e056d52'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1401%2Fproblem%2FF%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='d4bb27227c1e67e3a1338fa81e056d52'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1401">Codeforces Round 665 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='d4bb27227c1e67e3a1338fa81e056d52'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1401/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Битовые маски">
битмаски
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d4bb27227c1e67e3a1338fa81e056d52'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="704918"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d4bb27227c1e67e3a1338fa81e056d52'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="704918"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/81697" title="Codeforces Round #665 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11733" resourceName="Codeforces Round #665 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/81700" title="Codeforces Round #665 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11738" resourceName="Codeforces Round #665 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1401">Задачи</a></li>
<li><a
href="/contest/1401/submit">Отослать</a></li>
<li><a
href="/contest/1401/my">Мои посылки</a></li>
<li><a
href="/contest/1401/status">Статус</a></li>
<li><a
href="/contest/1401/hacks">Взломы</a></li>
<li><a
href="/contest/1401/room/1">Комната</a></li>
<li><a
href="/contest/1401/standings">Положение</a></li>
<li><a
href="/contest/1401/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="F" data-uuid="ps_010904edd481a7fa384835147d19443469251091">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Reverse и Swap</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задан массив $$$a$$$ длины $$$2^n$$$. Вам нужно обработать $$$q$$$ запросов к нему. Каждый запрос одного из следующих $$$4$$$ типов: </p><ol> <li> $$$Replace(x, k)$$$ — присвоить элементу $$$a_x$$$ значение $$$k$$$; </li><li> $$$Reverse(k)$$$ — развернуть каждый подмассив $$$[(i-1) \cdot 2^k+1, i \cdot 2^k]$$$ для всех $$$i$$$ ($$$i \ge 1$$$); </li><li> $$$Swap(k)$$$ — поменять местами подмассивы $$$[(2i-2) \cdot 2^k+1, (2i-1) \cdot 2^k]$$$ и $$$[(2i-1) \cdot 2^k+1, 2i \cdot 2^k]$$$ для всех $$$i$$$ ($$$i \ge 1$$$); </li><li> $$$Sum(l, r)$$$ — вывести сумму элементов подмассива $$$[l, r]$$$. </li></ol><p>Напишите программу, которая может достаточно быстро обрабатывать заданные запросы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$, $$$q$$$ ($$$0 \le n \le 18$$$; $$$1 \le q \le 10^5$$$) — длина массива $$$a$$$ и количество запросов.</p><p>Во второй строке заданы $$$2^n$$$ целых чисел $$$a_1, a_2, \ldots, a_{2^n}$$$ ($$$0 \le a_i \le 10^9$$$).</p><p>В следующих $$$q$$$ строках заданы запросы — по одному в строке. Каждый запрос одного из следующих $$$4$$$ типов: </p><ul> <li> «$$$1$$$ $$$x$$$ $$$k$$$» ($$$1 \le x \le 2^n$$$; $$$0 \le k \le 10^9$$$) — $$$Replace(x, k)$$$; </li><li> «$$$2$$$ $$$k$$$» ($$$0 \le k \le n$$$) — $$$Reverse(k)$$$; </li><li> «$$$3$$$ $$$k$$$» ($$$0 \le k < n$$$) — $$$Swap(k)$$$; </li><li> «$$$4$$$ $$$l$$$ $$$r$$$» ($$$1 \le l \le r \le 2^n$$$) — $$$Sum(l, r)$$$. </li></ul><p>Гарантируется, что в каждом тесте есть как минимум один запрос $$$Sum$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответы для каждого запроса $$$Sum$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2 3
7 4 9 9
1 2 8
3 1
4 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
24
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 8
7 0 8 8 7 1 5 2
4 3 7
2 1
3 2
4 1 6
2 3
1 5 16
4 8 8
3 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
29
22
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, первоначально, массив $$$a$$$ равен $$$\{7,4,9,9\}$$$.</p><p>После обработки первого запроса, массив $$$a$$$ становится $$$\{7,8,9,9\}$$$.</p><p>После обработки второго запроса, массив $$$a_i$$$ становится $$$\{9,9,7,8\}$$$.</p><p>Поэтому, ответ на третий запрос равен $$$9+7+8=24$$$.</p><p>Во втором примере, первоначально, массив $$$a$$$ равен $$$\{7,0,8,8,7,1,5,2\}$$$. Далее происходит следующее: </p><ol> <li> $$$Sum(3, 7)$$$ $$$\to$$$ $$$8 + 8 + 7 + 1 + 5 = 29$$$; </li><li> $$$Reverse(1)$$$ $$$\to$$$ $$$\{0,7,8,8,1,7,2,5\}$$$; </li><li> $$$Swap(2)$$$ $$$\to$$$ $$$\{1,7,2,5,0,7,8,8\}$$$; </li><li> $$$Sum(1, 6)$$$ $$$\to$$$ $$$1 + 7 + 2 + 5 + 0 + 7 = 22$$$; </li><li> $$$Reverse(3)$$$ $$$\to$$$ $$$\{8,8,7,0,5,2,7,1\}$$$; </li><li> $$$Replace(5, 16)$$$ $$$\to$$$ $$$\{8,8,7,0,16,2,7,1\}$$$; </li><li> $$$Sum(8, 8)$$$ $$$\to$$$ $$$1$$$; </li><li> $$$Swap(0)$$$ $$$\to$$$ $$$\{8,8,0,7,2,16,1,7\}$$$. </li></ol></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:07</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa720ba94981',t:'MTY5NjY2NjIwNy4xMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"] | ||
1404A | 1404 | A | ru | A. Сбалансированная бинарная строка | <div class="problem-statement"><div class="header"><div class="title">A. Сбалансированная бинарная строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Бинарная строка это строка, состоящая только из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Бинарная строка называется $$$k$$$-<span class="tex-font-style-bf">сбалансированной</span>, если каждая подстрока длины $$$k$$$ этой бинарной строки содержит равное количество символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> ($$$\frac{k}{2}$$$ каждого).</p><p>Вам дается целое число $$$k$$$ и строка $$$s$$$, состоящая только из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>. Вам необходимо определить, можно ли получить $$$k$$$-сбалансированную бинарную строку, заменив каждый символ <span class="tex-font-style-tt">?</span> в $$$s$$$ либо на <span class="tex-font-style-tt">0</span>, либо на <span class="tex-font-style-tt">1</span>.</p><p>Строка $$$a$$$ является подстрокой $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ чётное) — длина строки и параметр для сбалансированной бинарной строки.</p><p>Следующая строка содержит строку $$$s$$$ ($$$|s| = n$$$). При этом $$$s$$$ состоит только из <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите <span class="tex-font-style-tt">YES</span>, если мы можем заменить каждый <span class="tex-font-style-tt">?</span> в $$$s$$$ на <span class="tex-font-style-tt">0</span> или <span class="tex-font-style-tt">1</span> так, чтобы получившаяся бинарная строка была $$$k$$$-сбалансированной, или <span class="tex-font-style-tt">NO</span> если это невозможно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
NO
YES
YES
NO
NO
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных строка уже является $$$4$$$-сбалансированной бинарной строкой.</p><p>Во втором наборе входных данных строка может быть преобразована в <span class="tex-font-style-tt">101</span>.</p><p>В третьем наборе входных данных строку можно преобразовать в <span class="tex-font-style-tt">0110</span>.</p><p>В четвертом наборе входных данных строку можно преобразовать в <span class="tex-font-style-tt">1100110</span>.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="07a761466cca5f283e219d3277766771"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="4c11f76555014f7c04fcd69162b533b93fc6c347"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='07a761466cca5f283e219d3277766771'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1404%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='07a761466cca5f283e219d3277766771'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1404">Codeforces Round 668 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='07a761466cca5f283e219d3277766771'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1404/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='07a761466cca5f283e219d3277766771'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718461"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='07a761466cca5f283e219d3277766771'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718461"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11868" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11883" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1404">Задачи</a></li>
<li><a
href="/contest/1404/submit">Отослать</a></li>
<li><a
href="/contest/1404/my">Мои посылки</a></li>
<li><a
href="/contest/1404/status">Статус</a></li>
<li><a
href="/contest/1404/hacks">Взломы</a></li>
<li><a
href="/contest/1404/room/1">Комната</a></li>
<li><a
href="/contest/1404/standings">Положение</a></li>
<li><a
href="/contest/1404/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_326d503d77a1cacc4185d32e656cea6b9a68b205">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Сбалансированная бинарная строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Бинарная строка это строка, состоящая только из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Бинарная строка называется $$$k$$$-<span class="tex-font-style-bf">сбалансированной</span>, если каждая подстрока длины $$$k$$$ этой бинарной строки содержит равное количество символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> ($$$\frac{k}{2}$$$ каждого).</p><p>Вам дается целое число $$$k$$$ и строка $$$s$$$, состоящая только из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>. Вам необходимо определить, можно ли получить $$$k$$$-сбалансированную бинарную строку, заменив каждый символ <span class="tex-font-style-tt">?</span> в $$$s$$$ либо на <span class="tex-font-style-tt">0</span>, либо на <span class="tex-font-style-tt">1</span>.</p><p>Строка $$$a$$$ является подстрокой $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ чётное) — длина строки и параметр для сбалансированной бинарной строки.</p><p>Следующая строка содержит строку $$$s$$$ ($$$|s| = n$$$). При этом $$$s$$$ состоит только из <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите <span class="tex-font-style-tt">YES</span>, если мы можем заменить каждый <span class="tex-font-style-tt">?</span> в $$$s$$$ на <span class="tex-font-style-tt">0</span> или <span class="tex-font-style-tt">1</span> так, чтобы получившаяся бинарная строка была $$$k$$$-сбалансированной, или <span class="tex-font-style-tt">NO</span> если это невозможно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
NO
YES
YES
NO
NO
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных строка уже является $$$4$$$-сбалансированной бинарной строкой.</p><p>Во втором наборе входных данных строка может быть преобразована в <span class="tex-font-style-tt">101</span>.</p><p>В третьем наборе входных данных строку можно преобразовать в <span class="tex-font-style-tt">0110</span>.</p><p>В четвертом наборе входных данных строку можно преобразовать в <span class="tex-font-style-tt">1100110</span>.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:08</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa7a3bea16ab',t:'MTY5NjY2NjIwOC42MDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1500"] | ||
1404B | 1404 | B | ru | B. Догонялки на дереве | <div class="problem-statement"><div class="header"><div class="title">B. Догонялки на дереве</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в забавную игру — догонялки на дереве.</p><p>В эту игру играют на дереве из $$$n$$$ вершин, пронумерованных от $$$1$$$ до $$$n$$$. Напомним, что дерево на $$$n$$$ вершинах — это неориентированный, связный граф с $$$n-1$$$ ребрами.</p><p>Изначально Алиса располагается в вершине $$$a$$$, а Боб — в вершине $$$b$$$. Они ходят по очереди, и Алиса делает первый ход. За свой ход Алиса может перепрыгнуть в вершину с расстоянием <span class="tex-font-style-bf">не более</span> $$$da$$$ от текущей вершины. Боб же за свой ход может перепрыгнуть в вершину с расстоянием <span class="tex-font-style-bf">не более</span> $$$db$$$ от текущей вершины. Расстояние между двумя вершинами определяется как количество рёбер на уникальном простом пути между ними. В частности, любому из игроков разрешается остаться на одной и той же вершине в свой ход. Заметим, что при выполнении хода игрок занимает только начальную и конечную вершины своего хода, а не вершины между ними.</p><p>Если после не более чем $$$10^{100}$$$ ходов Алиса и Боб занимают одну и ту же вершину, то победителем объявляется Алиса. В противном случае побеждает Боб.</p><p>Определите победителя, если оба игрока играют оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит пять целых чисел $$$n,a,b,da,db$$$ ($$$2\le n\le 10^5$$$, $$$1\le a,b\le n$$$, $$$a\ne b$$$, $$$1\le da,db\le n-1$$$) — количество вершин, вершину Алисы, вершину Боба, максимальное расстояние прыжка Алисы и максимальное расстояние прыжка Боба, соответственно.</p><p>Следующие $$$n-1$$$ строк описывают ребра дерева. $$$i$$$-я из этих строк содержит два целых числа $$$u$$$, $$$v$$$ ($$$1\le u, v\le n, u\ne v$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$. Гарантируется, что данный граф является деревом.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую победителя игры: «<span class="tex-font-style-tt">Alice</span>» или «<span class="tex-font-style-tt">Bob</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Alice
Bob
Alice
Alice
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Алиса может выиграть, перейдя к вершине $$$1$$$. Тогда куда бы Боб не двигался дальше, Алиса сможет перейти к той же самой вершине на следующем шаге.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/205fb69920cc4da248aa83d83799f5bee152cc83.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором наборе входных данных у Боба есть следующая победная стратегия. Куда бы Алиса ни двигалась, Боб всегда будет двигаться к той из вершин $$$1$$$ или $$$6$$$, которая более удалена от Алисы.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e01029d970f0284101ce72c70949e9dd589efb53.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="6d7802d86d49d146bf65ef99602073ba"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="4c11f76555014f7c04fcd69162b533b93fc6c347"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='6d7802d86d49d146bf65ef99602073ba'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1404%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='6d7802d86d49d146bf65ef99602073ba'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1404">Codeforces Round 668 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='6d7802d86d49d146bf65ef99602073ba'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1404/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди">
игры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1900
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6d7802d86d49d146bf65ef99602073ba'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718462"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6d7802d86d49d146bf65ef99602073ba'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718462"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11868" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11883" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1404">Задачи</a></li>
<li><a
href="/contest/1404/submit">Отослать</a></li>
<li><a
href="/contest/1404/my">Мои посылки</a></li>
<li><a
href="/contest/1404/status">Статус</a></li>
<li><a
href="/contest/1404/hacks">Взломы</a></li>
<li><a
href="/contest/1404/room/1">Комната</a></li>
<li><a
href="/contest/1404/standings">Положение</a></li>
<li><a
href="/contest/1404/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_ffbc7401c71973398500b1e43c29a43989a97d73">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Догонялки на дереве</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в забавную игру — догонялки на дереве.</p><p>В эту игру играют на дереве из $$$n$$$ вершин, пронумерованных от $$$1$$$ до $$$n$$$. Напомним, что дерево на $$$n$$$ вершинах — это неориентированный, связный граф с $$$n-1$$$ ребрами.</p><p>Изначально Алиса располагается в вершине $$$a$$$, а Боб — в вершине $$$b$$$. Они ходят по очереди, и Алиса делает первый ход. За свой ход Алиса может перепрыгнуть в вершину с расстоянием <span class="tex-font-style-bf">не более</span> $$$da$$$ от текущей вершины. Боб же за свой ход может перепрыгнуть в вершину с расстоянием <span class="tex-font-style-bf">не более</span> $$$db$$$ от текущей вершины. Расстояние между двумя вершинами определяется как количество рёбер на уникальном простом пути между ними. В частности, любому из игроков разрешается остаться на одной и той же вершине в свой ход. Заметим, что при выполнении хода игрок занимает только начальную и конечную вершины своего хода, а не вершины между ними.</p><p>Если после не более чем $$$10^{100}$$$ ходов Алиса и Боб занимают одну и ту же вершину, то победителем объявляется Алиса. В противном случае побеждает Боб.</p><p>Определите победителя, если оба игрока играют оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит пять целых чисел $$$n,a,b,da,db$$$ ($$$2\le n\le 10^5$$$, $$$1\le a,b\le n$$$, $$$a\ne b$$$, $$$1\le da,db\le n-1$$$) — количество вершин, вершину Алисы, вершину Боба, максимальное расстояние прыжка Алисы и максимальное расстояние прыжка Боба, соответственно.</p><p>Следующие $$$n-1$$$ строк описывают ребра дерева. $$$i$$$-я из этих строк содержит два целых числа $$$u$$$, $$$v$$$ ($$$1\le u, v\le n, u\ne v$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$. Гарантируется, что данный граф является деревом.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую победителя игры: «<span class="tex-font-style-tt">Alice</span>» или «<span class="tex-font-style-tt">Bob</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Alice
Bob
Alice
Alice
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Алиса может выиграть, перейдя к вершине $$$1$$$. Тогда куда бы Боб не двигался дальше, Алиса сможет перейти к той же самой вершине на следующем шаге.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/205fb69920cc4da248aa83d83799f5bee152cc83.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором наборе входных данных у Боба есть следующая победная стратегия. Куда бы Алиса ни двигалась, Боб всегда будет двигаться к той из вершин $$$1$$$ или $$$6$$$, которая более удалена от Алисы.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e01029d970f0284101ce72c70949e9dd589efb53.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:09</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa839f309daa',t:'MTY5NjY2NjIwOS45MjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0438\u0433\u0440\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*1900"] | ||
1404C | 1404 | C | ru | C. Уничтожение фиксированных точек | <div class="problem-statement"><div class="header"><div class="title">C. Уничтожение фиксированных точек</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дан массив $$$a_1, \ldots, a_n$$$ из $$$n$$$ положительных целых чисел. За одну операцию можно выбрать индекс $$$i$$$, удовлетворяющий $$$a_i = i$$$, и удалить $$$a_i$$$ из массива (после удаления остальные части массива соединяются).</p><p>Вес $$$a$$$ определяется как максимальное количество элементов, которые можно удалить.</p><p>Вы должны ответить на $$$q$$$ независимых запросов $$$(x, y)$$$: после замены первых $$$x$$$ элементов $$$a$$$ и последних $$$y$$$ элементов $$$a$$$ на $$$n+1$$$ (делая их удаление невозможным), чему будет равен вес $$$a$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n, q \le 3 \cdot 10^5$$$) — длину массива и количество запросов.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$) — элементы массива.</p><p>$$$i$$$-я из следующих $$$q$$$ строк содержит два целых числа $$$x$$$ и $$$y$$$ ($$$x, y \ge 0$$$ и $$$x+y < n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк, $$$i$$$-я строка должна содержать единственное целое число — ответ на $$$i$$$-й запрос.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
11
6
1
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 2
1 4 1 2 4
0 0
1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение первого запроса:</p><p>После того, как первые $$$x = 3$$$ и последние $$$y = 1$$$ элементов стало невозможно удалить, $$$a$$$ становится равным $$$[\times, \times, \times, 9, 5, 4, 6, 5, 7, 8, 3, 11, \times]$$$ (для наглядности мы представляем $$$14$$$ как $$$\times$$$).</p><p>Вот стратегия, которая удаляет $$$5$$$ элементов (удаленный элемент окрашен в красный цвет):</p><ul> <li> $$$[\times, \times, \times, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, \color{red}{6}, 5, 7, 8, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, 7, \color{red}{8}, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, \color{red}{7}, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, 3, \times]$$$ (конечное состояние) </li></ul><p>Невозможно удалить более $$$5$$$ элементов, поэтому вес составляет $$$5$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="53bb72cb3eae67fe1106c075bc884cd8"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="4c11f76555014f7c04fcd69162b533b93fc6c347"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='53bb72cb3eae67fe1106c075bc884cd8'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1404%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='53bb72cb3eae67fe1106c075bc884cd8'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1404">Codeforces Round 668 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='53bb72cb3eae67fe1106c075bc884cd8'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1404/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='53bb72cb3eae67fe1106c075bc884cd8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718463"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='53bb72cb3eae67fe1106c075bc884cd8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718463"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11868" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11883" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1404">Задачи</a></li>
<li><a
href="/contest/1404/submit">Отослать</a></li>
<li><a
href="/contest/1404/my">Мои посылки</a></li>
<li><a
href="/contest/1404/status">Статус</a></li>
<li><a
href="/contest/1404/hacks">Взломы</a></li>
<li><a
href="/contest/1404/room/1">Комната</a></li>
<li><a
href="/contest/1404/standings">Положение</a></li>
<li><a
href="/contest/1404/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_474006b3cf25ae0e593a1aa14b79f3a74e34451c">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Уничтожение фиксированных точек</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дан массив $$$a_1, \ldots, a_n$$$ из $$$n$$$ положительных целых чисел. За одну операцию можно выбрать индекс $$$i$$$, удовлетворяющий $$$a_i = i$$$, и удалить $$$a_i$$$ из массива (после удаления остальные части массива соединяются).</p><p>Вес $$$a$$$ определяется как максимальное количество элементов, которые можно удалить.</p><p>Вы должны ответить на $$$q$$$ независимых запросов $$$(x, y)$$$: после замены первых $$$x$$$ элементов $$$a$$$ и последних $$$y$$$ элементов $$$a$$$ на $$$n+1$$$ (делая их удаление невозможным), чему будет равен вес $$$a$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n, q \le 3 \cdot 10^5$$$) — длину массива и количество запросов.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$) — элементы массива.</p><p>$$$i$$$-я из следующих $$$q$$$ строк содержит два целых числа $$$x$$$ и $$$y$$$ ($$$x, y \ge 0$$$ и $$$x+y < n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк, $$$i$$$-я строка должна содержать единственное целое число — ответ на $$$i$$$-й запрос.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
11
6
1
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 2
1 4 1 2 4
0 0
1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение первого запроса:</p><p>После того, как первые $$$x = 3$$$ и последние $$$y = 1$$$ элементов стало невозможно удалить, $$$a$$$ становится равным $$$[\times, \times, \times, 9, 5, 4, 6, 5, 7, 8, 3, 11, \times]$$$ (для наглядности мы представляем $$$14$$$ как $$$\times$$$).</p><p>Вот стратегия, которая удаляет $$$5$$$ элементов (удаленный элемент окрашен в красный цвет):</p><ul> <li> $$$[\times, \times, \times, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, \color{red}{6}, 5, 7, 8, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, 7, \color{red}{8}, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, \color{red}{7}, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, 3, \times]$$$ (конечное состояние) </li></ul><p>Невозможно удалить более $$$5$$$ элементов, поэтому вес составляет $$$5$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:11</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa8bbc607b2f',t:'MTY5NjY2NjIxMS4yNTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2300"] | ||
1404D | 1404 | D | ru | D. Игра Пар | <div class="problem-statement"><div class="header"><div class="title">D. Игра Пар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Дано целое число $$$n$$$. Два игрока, <span class="tex-font-style-tt">First</span> и <span class="tex-font-style-tt">Second</span> играют в следующую игру:</p><ol> <li> <span class="tex-font-style-tt">First</span> берет $$$2n$$$ целых чисел $$$1, 2, \dots, 2n$$$, и разбивает их на $$$n$$$ попарно непересекающихся пар по своему усмотрению.</li><li> Затем, <span class="tex-font-style-tt">Second</span> выбирает ровно одно число из каждой пары (тоже по своему усмотрению). </li></ol><p>Чтобы определить победителя игры, мы вычисляем сумму чисел, выбранных <span class="tex-font-style-tt">Second</span>. Если сумма всех этих чисел кратна $$$2n$$$, то выигрывает <span class="tex-font-style-tt">Second</span>. Иначе выигрывает <span class="tex-font-style-tt">First</span>.</p><p>Вам дано $$$n$$$. Выберите каким игроком вы будете играть и выиграйте игру.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Начните взаимодействие с чтения целого числа $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$).</p><p>После прочтения выведите единственную строку, содержащую либо <span class="tex-font-style-tt">First</span>, либо <span class="tex-font-style-tt">Second</span>, обозначающую, за кого вы хотите играть. Взаимодействие затем варьируется в зависимости от того, за кого вы решили играть.</p><p>Если вы выбрали <span class="tex-font-style-tt">First</span>, выведите единственную строку, содержащую $$$2n$$$ целых чисел $$$p_1, p_2, \dots, p_{2n}$$$, обозначающих, что число $$$i$$$ принадлежит к $$$p_i$$$-й паре для $$$1\le i \le 2n$$$. Таким образом, должно выполняться $$$1 \le p_i \le n$$$, а каждое число от $$$1$$$ до $$$n$$$ включительно должно встречаться ровно дважды.</p><p>Если вы выбрали игру <span class="tex-font-style-tt">Second</span>, то интерактор выведет $$$2n$$$ целых чисел $$$p_1, p_2, \dots, p_{2n}$$$, что означает, что число $$$i$$$ принадлежит к $$$p_i$$$-й паре. В ответ в единственной строке выведите $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$. Они должны содержать ровно по одному числу из каждой пары.</p><p>Независимо от того, какого игрока вы выбрали, интерактор прекратит работу, выведя единственное целое число: $$$0$$$, если ваш ответ на тестовый случай правильный (то есть вы играете за <span class="tex-font-style-tt">First</span> и он не может выбрать подходящие числа из ваших пар, или если вы играете за <span class="tex-font-style-tt">Second</span> и сумма выбранных вами чисел кратна $$$2n$$$), или $$$-1$$$, если он неправильный. Ваша программа должна завершиться сразу после прочтения этого числа.</p><p>Если в какой-то момент вы сделаете некорректное взаимодействие, то интерактор выведет $$$-1$$$ и завершит взаимодействие. Вы получите вердикт <span class="tex-font-style-bf">Неверный ответ</span>. Убедитесь в том, что вы немедленно прекращаете работу, чтобы избежать получения других вердиктов.</p><p>После вывода очередной строки не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p><span class="tex-font-style-bf">Формат взломов</span></p><p>Для взлома используйте следующий формат:</p><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$).</p><p>Вторая строка содержит $$$2n$$$ целых чисел $$$p_1, p_2, \dots, p_{2n}$$$, обозначающих, что число $$$i$$$ принадлежит к паре $$$p_i$$$-th, если взламываемое решение решает играть как <span class="tex-font-style-tt">Second</span>. Если взламываемое решение выбирает играть как <span class="tex-font-style-tt">First</span>, то эти пары не имеют значения, но $$$p_1, p_2, \dots, p_{2n}$$$ все равно должны формировать разбиение $$$1, 2, \dots, 2n$$$ на $$$n$$$ непересекающихся пар.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1 1 2 2
0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Second
1 3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
0</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
First
2 1 2 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$n = 2$$$, и вы решили играть как <span class="tex-font-style-tt">Second</span>. Интерактор выбирает пары $$$(1, 2)$$$ и $$$(3, 4)$$$, а вы отвечаете числами $$$1$$$ и $$$3$$$. Это правильный выбор, так как он содержит ровно одно число из каждой пары, а сумма $$$1 + 3 = 4$$$ делится на $$$4$$$.</p><p>Во втором примере снова $$$n = 2$$$, и вы играете как <span class="tex-font-style-tt">Первый</span>. Вы выбираете пары $$$(2, 4)$$$ и $$$(1, 3)$$$. Интерактор не может выбрать число из каждой пары так, чтобы их сумма делилась на $$$4$$$, поэтому ответ верен.</p><p>Обратите внимание, что примеры предназначены только для иллюстрации протокола взаимодействия и необязательно соответствуют поведению реального интерактора.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="92e0b3487ec999592803e617c11f65ba"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="4c11f76555014f7c04fcd69162b533b93fc6c347"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='92e0b3487ec999592803e617c11f65ba'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1404%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='92e0b3487ec999592803e617c11f65ba'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1404">Codeforces Round 668 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='92e0b3487ec999592803e617c11f65ba'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1404/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='92e0b3487ec999592803e617c11f65ba'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718464"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='92e0b3487ec999592803e617c11f65ba'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718464"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11868" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11883" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1404">Задачи</a></li>
<li><a
href="/contest/1404/submit">Отослать</a></li>
<li><a
href="/contest/1404/my">Мои посылки</a></li>
<li><a
href="/contest/1404/status">Статус</a></li>
<li><a
href="/contest/1404/hacks">Взломы</a></li>
<li><a
href="/contest/1404/room/1">Комната</a></li>
<li><a
href="/contest/1404/standings">Положение</a></li>
<li><a
href="/contest/1404/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_659e26072ae24b814e9c1fef42723d3389b0d8f4">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Игра Пар</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Дано целое число $$$n$$$. Два игрока, <span class="tex-font-style-tt">First</span> и <span class="tex-font-style-tt">Second</span> играют в следующую игру:</p><ol> <li> <span class="tex-font-style-tt">First</span> берет $$$2n$$$ целых чисел $$$1, 2, \dots, 2n$$$, и разбивает их на $$$n$$$ попарно непересекающихся пар по своему усмотрению.</li><li> Затем, <span class="tex-font-style-tt">Second</span> выбирает ровно одно число из каждой пары (тоже по своему усмотрению). </li></ol><p>Чтобы определить победителя игры, мы вычисляем сумму чисел, выбранных <span class="tex-font-style-tt">Second</span>. Если сумма всех этих чисел кратна $$$2n$$$, то выигрывает <span class="tex-font-style-tt">Second</span>. Иначе выигрывает <span class="tex-font-style-tt">First</span>.</p><p>Вам дано $$$n$$$. Выберите каким игроком вы будете играть и выиграйте игру.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Начните взаимодействие с чтения целого числа $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$).</p><p>После прочтения выведите единственную строку, содержащую либо <span class="tex-font-style-tt">First</span>, либо <span class="tex-font-style-tt">Second</span>, обозначающую, за кого вы хотите играть. Взаимодействие затем варьируется в зависимости от того, за кого вы решили играть.</p><p>Если вы выбрали <span class="tex-font-style-tt">First</span>, выведите единственную строку, содержащую $$$2n$$$ целых чисел $$$p_1, p_2, \dots, p_{2n}$$$, обозначающих, что число $$$i$$$ принадлежит к $$$p_i$$$-й паре для $$$1\le i \le 2n$$$. Таким образом, должно выполняться $$$1 \le p_i \le n$$$, а каждое число от $$$1$$$ до $$$n$$$ включительно должно встречаться ровно дважды.</p><p>Если вы выбрали игру <span class="tex-font-style-tt">Second</span>, то интерактор выведет $$$2n$$$ целых чисел $$$p_1, p_2, \dots, p_{2n}$$$, что означает, что число $$$i$$$ принадлежит к $$$p_i$$$-й паре. В ответ в единственной строке выведите $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$. Они должны содержать ровно по одному числу из каждой пары.</p><p>Независимо от того, какого игрока вы выбрали, интерактор прекратит работу, выведя единственное целое число: $$$0$$$, если ваш ответ на тестовый случай правильный (то есть вы играете за <span class="tex-font-style-tt">First</span> и он не может выбрать подходящие числа из ваших пар, или если вы играете за <span class="tex-font-style-tt">Second</span> и сумма выбранных вами чисел кратна $$$2n$$$), или $$$-1$$$, если он неправильный. Ваша программа должна завершиться сразу после прочтения этого числа.</p><p>Если в какой-то момент вы сделаете некорректное взаимодействие, то интерактор выведет $$$-1$$$ и завершит взаимодействие. Вы получите вердикт <span class="tex-font-style-bf">Неверный ответ</span>. Убедитесь в том, что вы немедленно прекращаете работу, чтобы избежать получения других вердиктов.</p><p>После вывода очередной строки не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p><span class="tex-font-style-bf">Формат взломов</span></p><p>Для взлома используйте следующий формат:</p><p>Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$).</p><p>Вторая строка содержит $$$2n$$$ целых чисел $$$p_1, p_2, \dots, p_{2n}$$$, обозначающих, что число $$$i$$$ принадлежит к паре $$$p_i$$$-th, если взламываемое решение решает играть как <span class="tex-font-style-tt">Second</span>. Если взламываемое решение выбирает играть как <span class="tex-font-style-tt">First</span>, то эти пары не имеют значения, но $$$p_1, p_2, \dots, p_{2n}$$$ все равно должны формировать разбиение $$$1, 2, \dots, 2n$$$ на $$$n$$$ непересекающихся пар.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1 1 2 2
0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Second
1 3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
0</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
First
2 1 2 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$n = 2$$$, и вы решили играть как <span class="tex-font-style-tt">Second</span>. Интерактор выбирает пары $$$(1, 2)$$$ и $$$(3, 4)$$$, а вы отвечаете числами $$$1$$$ и $$$3$$$. Это правильный выбор, так как он содержит ровно одно число из каждой пары, а сумма $$$1 + 3 = 4$$$ делится на $$$4$$$.</p><p>Во втором примере снова $$$n = 2$$$, и вы играете как <span class="tex-font-style-tt">Первый</span>. Вы выбираете пары $$$(2, 4)$$$ и $$$(1, 3)$$$. Интерактор не может выбрать число из каждой пары так, чтобы их сумма делилась на $$$4$$$, поэтому ответ верен.</p><p>Обратите внимание, что примеры предназначены только для иллюстрации протокола взаимодействия и необязательно соответствуют поведению реального интерактора.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:12</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa940aaa9d34',t:'MTY5NjY2NjIxMi42NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2800"] | ||
1404E | 1404 | E | ru | E. Кирпичи | <div class="problem-statement"><div class="header"><div class="title">E. Кирпичи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Кирпич — прямоугольник с целыми сторонами шириной $$$1$$$ или высотой $$$1$$$ (или и то и другое).</p><p>Дана сетка $$$n\times m$$$, и каждая ячейка окрашена в черный или белый цвет. Замощение — это способ поместить кирпичи на сетку так, чтобы каждая черная ячейка была покрыта <span class="tex-font-style-bf">ровно одним</span> кирпичом, а каждая белая ячейка не была покрыта кирпичом. Другими словами, кирпичи размещаются только в черных ячейках, покрывают все черные ячейки, и <span class="tex-font-style-bf">никакие два кирпича не перекрываются</span>.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a07ccbb78a16c001efa4372cf6a89d26d5c9e25b.png" style="max-width: 100.0%;max-height: 100.0%;"/> Пример замощения с первого примера с использованием $$$5$$$ кирпичей. Существует также замощение из $$$4$$$ кирпичей. </center><p>Какое минимальное количество кирпичей необходимо для замощения данной сетки?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$m$$$ ($$$1\le n, m\le 200$$$) — количество строк и столбцов соответственно.</p><p>Следующие $$$n$$$ строки описывают сетку. $$$i$$$-я строка содержит строку длиной $$$m$$$, где $$$j$$$-я строка обозначает цвет ячейки в строке $$$i$$$, столбец $$$j$$$. Черная ячейка обозначается символом «<span class="tex-font-style-tt">#</span>», а белая — символом «<span class="tex-font-style-tt">.</span>».</p><p>Гарантируется, что есть хотя бы одна черная ячейка.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальное количество требуемых кирпичей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 4
#.##
####
##..
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 6
######
##....
######
##...#
##...#
######
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 8
####..##
#..#.##.
#..#.###
####.#.#
....####
.###.###
###.#..#
########
###..###
.##.###.
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
18
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Сетка с первого примера может быть замощена $$$4$$$-мя кирпичами, размещенными вертикально.</p><p>Сетка с третьего примера может быть замощена такими $$$18$$$ кирпичами:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2f9cfaae850c09dc5b2f01db25c60970ed520e9b.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="47fb0068b95c5188681aaff97a46baed"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="4c11f76555014f7c04fcd69162b533b93fc6c347"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='47fb0068b95c5188681aaff97a46baed'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1404%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='47fb0068b95c5188681aaff97a46baed'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1404">Codeforces Round 668 (Div. 1)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='47fb0068b95c5188681aaff97a46baed'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1404/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Паросочетания, теорема Кёнига, вершинные и реберные покрытия в двудольных графах">
паросочетания
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Потоки в графах">
потоки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='47fb0068b95c5188681aaff97a46baed'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718465"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='47fb0068b95c5188681aaff97a46baed'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718465"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11868" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11883" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1404">Задачи</a></li>
<li><a
href="/contest/1404/submit">Отослать</a></li>
<li><a
href="/contest/1404/my">Мои посылки</a></li>
<li><a
href="/contest/1404/status">Статус</a></li>
<li><a
href="/contest/1404/hacks">Взломы</a></li>
<li><a
href="/contest/1404/room/1">Комната</a></li>
<li><a
href="/contest/1404/standings">Положение</a></li>
<li><a
href="/contest/1404/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_51e4974d33df51e52a32c61baebd9225c41e34bf">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Кирпичи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Кирпич — прямоугольник с целыми сторонами шириной $$$1$$$ или высотой $$$1$$$ (или и то и другое).</p><p>Дана сетка $$$n\times m$$$, и каждая ячейка окрашена в черный или белый цвет. Замощение — это способ поместить кирпичи на сетку так, чтобы каждая черная ячейка была покрыта <span class="tex-font-style-bf">ровно одним</span> кирпичом, а каждая белая ячейка не была покрыта кирпичом. Другими словами, кирпичи размещаются только в черных ячейках, покрывают все черные ячейки, и <span class="tex-font-style-bf">никакие два кирпича не перекрываются</span>.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a07ccbb78a16c001efa4372cf6a89d26d5c9e25b.png" style="max-width: 100.0%;max-height: 100.0%;" /> Пример замощения с первого примера с использованием $$$5$$$ кирпичей. Существует также замощение из $$$4$$$ кирпичей. </center><p>Какое минимальное количество кирпичей необходимо для замощения данной сетки?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$m$$$ ($$$1\le n, m\le 200$$$) — количество строк и столбцов соответственно.</p><p>Следующие $$$n$$$ строки описывают сетку. $$$i$$$-я строка содержит строку длиной $$$m$$$, где $$$j$$$-я строка обозначает цвет ячейки в строке $$$i$$$, столбец $$$j$$$. Черная ячейка обозначается символом «<span class="tex-font-style-tt">#</span>», а белая — символом «<span class="tex-font-style-tt">.</span>».</p><p>Гарантируется, что есть хотя бы одна черная ячейка.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальное количество требуемых кирпичей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 4
#.##
####
##..
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 6
######
##....
######
##...#
##...#
######
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 8
####..##
#..#.##.
#..#.###
####.#.#
....####
.###.###
###.#..#
########
###..###
.##.###.
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
18
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Сетка с первого примера может быть замощена $$$4$$$-мя кирпичами, размещенными вертикально.</p><p>Сетка с третьего примера может быть замощена такими $$$18$$$ кирпичами:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2f9cfaae850c09dc5b2f01db25c60970ed520e9b.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:13</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aa9cc9149d70',t:'MTY5NjY2NjIxMy45OTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u041f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f, \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u041a\u0451\u043d\u0438\u0433\u0430, \u0432\u0435\u0440\u0448\u0438\u043d\u043d\u044b\u0435 \u0438 \u0440\u0435\u0431\u0435\u0440\u043d\u044b\u0435 \u043f\u043e\u043a\u0440\u044b\u0442\u0438\u044f \u0432 \u0434\u0432\u0443\u0434\u043e\u043b\u044c\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u043f\u043e\u0442\u043e\u043a\u0438", "*2800"] | ||
1405A | 1405 | A | ru | A. Подделка перестановки | <div class="problem-statement"><div class="header"><div class="title">A. Подделка перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Перестановка длины $$$n$$$ — это массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$ в произвольном порядке. Например, $$$[2,3,1,5,4]$$$ — это перестановка, но $$$[1,2,2]$$$ — это не перестановка ($$$2$$$ встречается дважды в массиве), а $$$[1,3,4]$$$ также не является перестановкой ($$$n=3$$$, но в массиве встречается $$$4$$$).</p><p>Пусть $$$p$$$ — перестановка длины $$$n$$$. Определим <span class="tex-font-style-bf">подпись</span> $$$F(p)$$$ перестановки $$$p$$$ как отсортированный массив сумм соседних элементов $$$p$$$. Более формально,</p><p>$$$$$$F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).$$$$$$</p><p>Например, если $$$n=4$$$ и $$$p=[1,4,2,3],$$$ тогда подпись будет вычисляться следующим образом: $$$F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6]$$$.</p><p>Вам дана перестановка $$$p$$$ длины $$$n$$$. Ваша задача найти какую-то <span class="tex-font-style-bf">другую</span> перестановку $$$p'$$$ с такой же подписью. Обратите внимание, что перестановки $$$p$$$ и $$$p'$$$ обязаны различаться хотя бы в одной позиции, то есть должна существовать такая позиция $$$i$$$, что $$$p_i \ne p'_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 668$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2\le n\le 100$$$) — длину перестановки.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$p_1,\ldots,p_n$$$ ($$$1\le p_i\le n$$$). Гарантируется, что $$$p$$$ является перестановкой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите $$$n$$$ целых чисел $$$p'_1,\ldots, p'_n$$$ — перестановку, удовлетворяющую следующим условиям: $$$p'\ne p$$$ и $$$F(p')=F(p)$$$.</p><p>Можно доказать, что для любой перестановки, удовлетворяющей ограничениям из условия, существует ответ.</p><p>Если правильных ответов несколько, можно вывести любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
2
1 2
6
2 1 6 5 4 3
5
2 4 3 1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1
1 2 5 6 3 4
3 1 5 2 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$F(p)=\mathrm{sort}([1+2])=[3]$$$.</p><p>И $$$F(p')=\mathrm{sort}([2+1])=[3]$$$.</p><p>Во втором примере $$$F(p)=\mathrm{sort}([2+1,1+6,6+5,5+4,4+3])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$$$.</p><p>И $$$F(p')=\mathrm{sort}([1+2,2+5,5+6,6+3,3+4])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$$$.</p><p>В третьем примере $$$F(p)=\mathrm{sort}([2+4,4+3,3+1,1+5])=\mathrm{sort}([6,7,4,6])=[4,6,6,7]$$$.</p><p>И $$$F(p')=\mathrm{sort}([3+1,1+5,5+2,2+4])=\mathrm{sort}([4,6,7,6])=[4,6,6,7]$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="bf0e17031997c7238e13d31d062753a4"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fa1814eabd40b62c2428d7f73f5c0c1f9ed03946"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='bf0e17031997c7238e13d31d062753a4'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1405%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='bf0e17031997c7238e13d31d062753a4'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1405">Codeforces Round 668 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='bf0e17031997c7238e13d31d062753a4'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1405/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bf0e17031997c7238e13d31d062753a4'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718466"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bf0e17031997c7238e13d31d062753a4'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718466"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11869" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11884" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1405">Задачи</a></li>
<li><a
href="/contest/1405/submit">Отослать</a></li>
<li><a
href="/contest/1405/my">Мои посылки</a></li>
<li><a
href="/contest/1405/status">Статус</a></li>
<li><a
href="/contest/1405/hacks">Взломы</a></li>
<li><a
href="/contest/1405/room/1">Комната</a></li>
<li><a
href="/contest/1405/standings">Положение</a></li>
<li><a
href="/contest/1405/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_139a7632aee0dddd61cf38cc92df0f3a5db31ebd">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Подделка перестановки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Перестановка длины $$$n$$$ — это массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$ в произвольном порядке. Например, $$$[2,3,1,5,4]$$$ — это перестановка, но $$$[1,2,2]$$$ — это не перестановка ($$$2$$$ встречается дважды в массиве), а $$$[1,3,4]$$$ также не является перестановкой ($$$n=3$$$, но в массиве встречается $$$4$$$).</p><p>Пусть $$$p$$$ — перестановка длины $$$n$$$. Определим <span class="tex-font-style-bf">подпись</span> $$$F(p)$$$ перестановки $$$p$$$ как отсортированный массив сумм соседних элементов $$$p$$$. Более формально,</p><p>$$$$$$F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).$$$$$$</p><p>Например, если $$$n=4$$$ и $$$p=[1,4,2,3],$$$ тогда подпись будет вычисляться следующим образом: $$$F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6]$$$.</p><p>Вам дана перестановка $$$p$$$ длины $$$n$$$. Ваша задача найти какую-то <span class="tex-font-style-bf">другую</span> перестановку $$$p'$$$ с такой же подписью. Обратите внимание, что перестановки $$$p$$$ и $$$p'$$$ обязаны различаться хотя бы в одной позиции, то есть должна существовать такая позиция $$$i$$$, что $$$p_i \ne p'_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 668$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2\le n\le 100$$$) — длину перестановки.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$p_1,\ldots,p_n$$$ ($$$1\le p_i\le n$$$). Гарантируется, что $$$p$$$ является перестановкой.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите $$$n$$$ целых чисел $$$p'_1,\ldots, p'_n$$$ — перестановку, удовлетворяющую следующим условиям: $$$p'\ne p$$$ и $$$F(p')=F(p)$$$.</p><p>Можно доказать, что для любой перестановки, удовлетворяющей ограничениям из условия, существует ответ.</p><p>Если правильных ответов несколько, можно вывести любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
2
1 2
6
2 1 6 5 4 3
5
2 4 3 1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1
1 2 5 6 3 4
3 1 5 2 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$F(p)=\mathrm{sort}([1+2])=[3]$$$.</p><p>И $$$F(p')=\mathrm{sort}([2+1])=[3]$$$.</p><p>Во втором примере $$$F(p)=\mathrm{sort}([2+1,1+6,6+5,5+4,4+3])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$$$.</p><p>И $$$F(p')=\mathrm{sort}([1+2,2+5,5+6,6+3,3+4])=\mathrm{sort}([3,7,11,9,7])=[3,7,7,9,11]$$$.</p><p>В третьем примере $$$F(p)=\mathrm{sort}([2+4,4+3,3+1,1+5])=\mathrm{sort}([6,7,4,6])=[4,6,6,7]$$$.</p><p>И $$$F(p')=\mathrm{sort}([3+1,1+5,5+2,2+4])=\mathrm{sort}([4,6,7,6])=[4,6,6,7]$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:15</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aaa519fe1604',t:'MTY5NjY2NjIxNS4zNzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*800"] | ||
1405B | 1405 | B | ru | B. Уничтожение массива | <div class="problem-statement"><div class="header"><div class="title">B. Уничтожение массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел, таких, что $$$a_1 + a_2 + \cdots + a_n = 0$$$.</p><p>За одну операцию можно выбрать два <span class="tex-font-style-bf">различных</span> индекса $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$), уменьшить $$$a_i$$$ на единицу и увеличить $$$a_j$$$ на единицу. Если $$$i < j$$$, то эта операция бесплатная, в противном случае она стоит одну монету.</p><p>Какое минимальное количество монет нужно потратить, чтобы все элементы стали равны $$$0$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 5000$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество элементов.</p><p>Следующая строка содержит $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). При этом $$$\sum_{i=1}^n a_i = 0$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное количество монет, которое мы должны потратить, чтобы все элементы равнялись $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
4
-3 5 -3 1
2
1 -1
4
-3 2 -3 4
4
-1 1 1 -1
7
-5 7 -6 -4 17 -13 4
6
-1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000
1
0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
0
4
1
8
3000000000
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможная стратегия для первого набора входных данных: </p><ul> <li> Сделаем операцию $$$(i=2, j=3)$$$ три раза (бесплатно), $$$a = [-3, 2, 0, 1]$$$. </li><li> Сделаем операцию $$$(i=2, j=1)$$$ два раза (за две монеты), $$$a = [-1, 0, 0, 1]$$$. </li><li> Сделаем операцию $$$(i=4, j=1)$$$ один раз (за одну монету), $$$a = [0, 0, 0, 0]$$$. </li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="cf71efb10a7d944507a65a566aa2b4af"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fa1814eabd40b62c2428d7f73f5c0c1f9ed03946"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='cf71efb10a7d944507a65a566aa2b4af'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1405%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='cf71efb10a7d944507a65a566aa2b4af'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1405">Codeforces Round 668 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='cf71efb10a7d944507a65a566aa2b4af'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1405/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1000
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cf71efb10a7d944507a65a566aa2b4af'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718467"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='cf71efb10a7d944507a65a566aa2b4af'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718467"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11869" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11884" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1405">Задачи</a></li>
<li><a
href="/contest/1405/submit">Отослать</a></li>
<li><a
href="/contest/1405/my">Мои посылки</a></li>
<li><a
href="/contest/1405/status">Статус</a></li>
<li><a
href="/contest/1405/hacks">Взломы</a></li>
<li><a
href="/contest/1405/room/1">Комната</a></li>
<li><a
href="/contest/1405/standings">Положение</a></li>
<li><a
href="/contest/1405/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_b85fc965adb4cf6e238050361033e07a3c20928d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Уничтожение массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел, таких, что $$$a_1 + a_2 + \cdots + a_n = 0$$$.</p><p>За одну операцию можно выбрать два <span class="tex-font-style-bf">различных</span> индекса $$$i$$$ и $$$j$$$ ($$$1 \le i, j \le n$$$), уменьшить $$$a_i$$$ на единицу и увеличить $$$a_j$$$ на единицу. Если $$$i < j$$$, то эта операция бесплатная, в противном случае она стоит одну монету.</p><p>Какое минимальное количество монет нужно потратить, чтобы все элементы стали равны $$$0$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 5000$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество элементов.</p><p>Следующая строка содержит $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$). При этом $$$\sum_{i=1}^n a_i = 0$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное количество монет, которое мы должны потратить, чтобы все элементы равнялись $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
4
-3 5 -3 1
2
1 -1
4
-3 2 -3 4
4
-1 1 1 -1
7
-5 7 -6 -4 17 -13 4
6
-1000000000 -1000000000 -1000000000 1000000000 1000000000 1000000000
1
0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
0
4
1
8
3000000000
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможная стратегия для первого набора входных данных: </p><ul> <li> Сделаем операцию $$$(i=2, j=3)$$$ три раза (бесплатно), $$$a = [-3, 2, 0, 1]$$$. </li><li> Сделаем операцию $$$(i=2, j=1)$$$ два раза (за две монеты), $$$a = [-1, 0, 0, 1]$$$. </li><li> Сделаем операцию $$$(i=4, j=1)$$$ один раз (за одну монету), $$$a = [0, 0, 0, 0]$$$. </li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:16</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aaadc9477b5f',t:'MTY5NjY2NjIxNi43NDkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1000"] | ||
1405C | 1405 | C | ru | C. Сбалансированная бинарная строка | <div class="problem-statement"><div class="header"><div class="title">C. Сбалансированная бинарная строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Бинарная строка это строка, состоящая только из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Бинарная строка называется $$$k$$$-<span class="tex-font-style-bf">сбалансированной</span>, если каждая подстрока длины $$$k$$$ этой бинарной строки содержит равное количество символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> ($$$\frac{k}{2}$$$ каждого).</p><p>Вам дается целое число $$$k$$$ и строка $$$s$$$, состоящая только из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>. Вам необходимо определить, можно ли получить $$$k$$$-сбалансированную бинарную строку, заменив каждый символ <span class="tex-font-style-tt">?</span> в $$$s$$$ либо на <span class="tex-font-style-tt">0</span>, либо на <span class="tex-font-style-tt">1</span>.</p><p>Строка $$$a$$$ является подстрокой $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ чётное) — длина строки и параметр для сбалансированной бинарной строки.</p><p>Следующая строка содержит строку $$$s$$$ ($$$|s| = n$$$). При этом $$$s$$$ состоит только из <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите <span class="tex-font-style-tt">YES</span>, если мы можем заменить каждый <span class="tex-font-style-tt">?</span> в $$$s$$$ на <span class="tex-font-style-tt">0</span> или <span class="tex-font-style-tt">1</span> так, чтобы получившаяся бинарная строка была $$$k$$$-сбалансированной, или <span class="tex-font-style-tt">NO</span> если это невозможно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
NO
YES
YES
NO
NO
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных строка уже является $$$4$$$-сбалансированной бинарной строкой.</p><p>Во втором наборе входных данных строка может быть преобразована в <span class="tex-font-style-tt">101</span>.</p><p>В третьем наборе входных данных строку можно преобразовать в <span class="tex-font-style-tt">0110</span>.</p><p>В четвертом наборе входных данных строку можно преобразовать в <span class="tex-font-style-tt">1100110</span>.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="61d066d44618bc9c267a95c516d092db"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fa1814eabd40b62c2428d7f73f5c0c1f9ed03946"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='61d066d44618bc9c267a95c516d092db'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1405%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='61d066d44618bc9c267a95c516d092db'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1405">Codeforces Round 668 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='61d066d44618bc9c267a95c516d092db'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1405/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='61d066d44618bc9c267a95c516d092db'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718468"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='61d066d44618bc9c267a95c516d092db'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718468"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11869" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11884" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1405">Задачи</a></li>
<li><a
href="/contest/1405/submit">Отослать</a></li>
<li><a
href="/contest/1405/my">Мои посылки</a></li>
<li><a
href="/contest/1405/status">Статус</a></li>
<li><a
href="/contest/1405/hacks">Взломы</a></li>
<li><a
href="/contest/1405/room/1">Комната</a></li>
<li><a
href="/contest/1405/standings">Положение</a></li>
<li><a
href="/contest/1405/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_139d235934850e80e6e4ed9b58f880eaf8e5f5a2">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Сбалансированная бинарная строка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Бинарная строка это строка, состоящая только из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Бинарная строка называется $$$k$$$-<span class="tex-font-style-bf">сбалансированной</span>, если каждая подстрока длины $$$k$$$ этой бинарной строки содержит равное количество символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> ($$$\frac{k}{2}$$$ каждого).</p><p>Вам дается целое число $$$k$$$ и строка $$$s$$$, состоящая только из символов <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>. Вам необходимо определить, можно ли получить $$$k$$$-сбалансированную бинарную строку, заменив каждый символ <span class="tex-font-style-tt">?</span> в $$$s$$$ либо на <span class="tex-font-style-tt">0</span>, либо на <span class="tex-font-style-tt">1</span>.</p><p>Строка $$$a$$$ является подстрокой $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le k \le n \le 3 \cdot 10^5$$$, $$$k$$$ чётное) — длина строки и параметр для сбалансированной бинарной строки.</p><p>Следующая строка содержит строку $$$s$$$ ($$$|s| = n$$$). При этом $$$s$$$ состоит только из <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">1</span> и <span class="tex-font-style-tt">?</span>.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите <span class="tex-font-style-tt">YES</span>, если мы можем заменить каждый <span class="tex-font-style-tt">?</span> в $$$s$$$ на <span class="tex-font-style-tt">0</span> или <span class="tex-font-style-tt">1</span> так, чтобы получившаяся бинарная строка была $$$k$$$-сбалансированной, или <span class="tex-font-style-tt">NO</span> если это невозможно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
????
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
????00
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
NO
YES
YES
NO
NO
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных строка уже является $$$4$$$-сбалансированной бинарной строкой.</p><p>Во втором наборе входных данных строка может быть преобразована в <span class="tex-font-style-tt">101</span>.</p><p>В третьем наборе входных данных строку можно преобразовать в <span class="tex-font-style-tt">0110</span>.</p><p>В четвертом наборе входных данных строку можно преобразовать в <span class="tex-font-style-tt">1100110</span>.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:18</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aab6591175af',t:'MTY5NjY2NjIxOC4wNjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1500"] | ||
1405D | 1405 | D | ru | D. Догонялки на дереве | <div class="problem-statement"><div class="header"><div class="title">D. Догонялки на дереве</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в забавную игру — догонялки на дереве.</p><p>В эту игру играют на дереве из $$$n$$$ вершин, пронумерованных от $$$1$$$ до $$$n$$$. Напомним, что дерево на $$$n$$$ вершинах — это неориентированный, связный граф с $$$n-1$$$ ребрами.</p><p>Изначально Алиса располагается в вершине $$$a$$$, а Боб — в вершине $$$b$$$. Они ходят по очереди, и Алиса делает первый ход. За свой ход Алиса может перепрыгнуть в вершину с расстоянием <span class="tex-font-style-bf">не более</span> $$$da$$$ от текущей вершины. Боб же за свой ход может перепрыгнуть в вершину с расстоянием <span class="tex-font-style-bf">не более</span> $$$db$$$ от текущей вершины. Расстояние между двумя вершинами определяется как количество рёбер на уникальном простом пути между ними. В частности, любому из игроков разрешается остаться на одной и той же вершине в свой ход. Заметим, что при выполнении хода игрок занимает только начальную и конечную вершины своего хода, а не вершины между ними.</p><p>Если после не более чем $$$10^{100}$$$ ходов Алиса и Боб занимают одну и ту же вершину, то победителем объявляется Алиса. В противном случае побеждает Боб.</p><p>Определите победителя, если оба игрока играют оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит пять целых чисел $$$n,a,b,da,db$$$ ($$$2\le n\le 10^5$$$, $$$1\le a,b\le n$$$, $$$a\ne b$$$, $$$1\le da,db\le n-1$$$) — количество вершин, вершину Алисы, вершину Боба, максимальное расстояние прыжка Алисы и максимальное расстояние прыжка Боба, соответственно.</p><p>Следующие $$$n-1$$$ строк описывают ребра дерева. $$$i$$$-я из этих строк содержит два целых числа $$$u$$$, $$$v$$$ ($$$1\le u, v\le n, u\ne v$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$. Гарантируется, что данный граф является деревом.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую победителя игры: «<span class="tex-font-style-tt">Alice</span>» или «<span class="tex-font-style-tt">Bob</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Alice
Bob
Alice
Alice
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Алиса может выиграть, перейдя к вершине $$$1$$$. Тогда куда бы Боб не двигался дальше, Алиса сможет перейти к той же самой вершине на следующем шаге.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/205fb69920cc4da248aa83d83799f5bee152cc83.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором наборе входных данных у Боба есть следующая победная стратегия. Куда бы Алиса ни двигалась, Боб всегда будет двигаться к той из вершин $$$1$$$ или $$$6$$$, которая более удалена от Алисы.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e01029d970f0284101ce72c70949e9dd589efb53.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="da7ab934929a3c71bbc83649f7cd9934"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fa1814eabd40b62c2428d7f73f5c0c1f9ed03946"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='da7ab934929a3c71bbc83649f7cd9934'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1405%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='da7ab934929a3c71bbc83649f7cd9934'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1405">Codeforces Round 668 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='da7ab934929a3c71bbc83649f7cd9934'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1405/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди">
игры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1900
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='da7ab934929a3c71bbc83649f7cd9934'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718469"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='da7ab934929a3c71bbc83649f7cd9934'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718469"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11869" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11884" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1405">Задачи</a></li>
<li><a
href="/contest/1405/submit">Отослать</a></li>
<li><a
href="/contest/1405/my">Мои посылки</a></li>
<li><a
href="/contest/1405/status">Статус</a></li>
<li><a
href="/contest/1405/hacks">Взломы</a></li>
<li><a
href="/contest/1405/room/1">Комната</a></li>
<li><a
href="/contest/1405/standings">Положение</a></li>
<li><a
href="/contest/1405/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_834f6e76d91d68e3a0416ef081e954ddad11f108">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Догонялки на дереве</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в забавную игру — догонялки на дереве.</p><p>В эту игру играют на дереве из $$$n$$$ вершин, пронумерованных от $$$1$$$ до $$$n$$$. Напомним, что дерево на $$$n$$$ вершинах — это неориентированный, связный граф с $$$n-1$$$ ребрами.</p><p>Изначально Алиса располагается в вершине $$$a$$$, а Боб — в вершине $$$b$$$. Они ходят по очереди, и Алиса делает первый ход. За свой ход Алиса может перепрыгнуть в вершину с расстоянием <span class="tex-font-style-bf">не более</span> $$$da$$$ от текущей вершины. Боб же за свой ход может перепрыгнуть в вершину с расстоянием <span class="tex-font-style-bf">не более</span> $$$db$$$ от текущей вершины. Расстояние между двумя вершинами определяется как количество рёбер на уникальном простом пути между ними. В частности, любому из игроков разрешается остаться на одной и той же вершине в свой ход. Заметим, что при выполнении хода игрок занимает только начальную и конечную вершины своего хода, а не вершины между ними.</p><p>Если после не более чем $$$10^{100}$$$ ходов Алиса и Боб занимают одну и ту же вершину, то победителем объявляется Алиса. В противном случае побеждает Боб.</p><p>Определите победителя, если оба игрока играют оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит пять целых чисел $$$n,a,b,da,db$$$ ($$$2\le n\le 10^5$$$, $$$1\le a,b\le n$$$, $$$a\ne b$$$, $$$1\le da,db\le n-1$$$) — количество вершин, вершину Алисы, вершину Боба, максимальное расстояние прыжка Алисы и максимальное расстояние прыжка Боба, соответственно.</p><p>Следующие $$$n-1$$$ строк описывают ребра дерева. $$$i$$$-я из этих строк содержит два целых числа $$$u$$$, $$$v$$$ ($$$1\le u, v\le n, u\ne v$$$), обозначающие ребро между вершинами $$$u$$$ и $$$v$$$. Гарантируется, что данный граф является деревом.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую победителя игры: «<span class="tex-font-style-tt">Alice</span>» или «<span class="tex-font-style-tt">Bob</span>».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4 3 2 1 2
1 2
1 3
1 4
6 6 1 2 5
1 2
6 5
2 3
3 4
4 5
9 3 9 2 5
1 2
1 6
1 9
1 3
9 5
7 9
4 8
4 3
11 8 11 3 3
1 2
11 9
4 9
6 5
2 10
3 2
5 9
8 3
7 4
7 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Alice
Bob
Alice
Alice
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Алиса может выиграть, перейдя к вершине $$$1$$$. Тогда куда бы Боб не двигался дальше, Алиса сможет перейти к той же самой вершине на следующем шаге.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/205fb69920cc4da248aa83d83799f5bee152cc83.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором наборе входных данных у Боба есть следующая победная стратегия. Куда бы Алиса ни двигалась, Боб всегда будет двигаться к той из вершин $$$1$$$ или $$$6$$$, которая более удалена от Алисы.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e01029d970f0284101ce72c70949e9dd589efb53.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:19</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aabe9fd19d34',t:'MTY5NjY2NjIxOS4zOTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0438\u0433\u0440\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1900"] | ||
1405E | 1405 | E | ru | E. Уничтожение фиксированных точек | <div class="problem-statement"><div class="header"><div class="title">E. Уничтожение фиксированных точек</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дан массив $$$a_1, \ldots, a_n$$$ из $$$n$$$ положительных целых чисел. За одну операцию можно выбрать индекс $$$i$$$, удовлетворяющий $$$a_i = i$$$, и удалить $$$a_i$$$ из массива (после удаления остальные части массива соединяются).</p><p>Вес $$$a$$$ определяется как максимальное количество элементов, которые можно удалить.</p><p>Вы должны ответить на $$$q$$$ независимых запросов $$$(x, y)$$$: после замены первых $$$x$$$ элементов $$$a$$$ и последних $$$y$$$ элементов $$$a$$$ на $$$n+1$$$ (делая их удаление невозможным), чему будет равен вес $$$a$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n, q \le 3 \cdot 10^5$$$) — длину массива и количество запросов.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$) — элементы массива.</p><p>$$$i$$$-я из следующих $$$q$$$ строк содержит два целых числа $$$x$$$ и $$$y$$$ ($$$x, y \ge 0$$$ и $$$x+y < n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк, $$$i$$$-я строка должна содержать единственное целое число — ответ на $$$i$$$-й запрос.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
11
6
1
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 2
1 4 1 2 4
0 0
1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение первого запроса:</p><p>После того, как первые $$$x = 3$$$ и последние $$$y = 1$$$ элементов стало невозможно удалить, $$$a$$$ становится равным $$$[\times, \times, \times, 9, 5, 4, 6, 5, 7, 8, 3, 11, \times]$$$ (для наглядности мы представляем $$$14$$$ как $$$\times$$$).</p><p>Вот стратегия, которая удаляет $$$5$$$ элементов (удаленный элемент окрашен в красный цвет):</p><ul> <li> $$$[\times, \times, \times, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, \color{red}{6}, 5, 7, 8, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, 7, \color{red}{8}, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, \color{red}{7}, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, 3, \times]$$$ (конечное состояние) </li></ul><p>Невозможно удалить более $$$5$$$ элементов, поэтому вес составляет $$$5$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="a66589a30205a203d49c8d2daa551aab"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="fa1814eabd40b62c2428d7f73f5c0c1f9ed03946"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='a66589a30205a203d49c8d2daa551aab'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1405%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='a66589a30205a203d49c8d2daa551aab'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1405">Codeforces Round 668 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='a66589a30205a203d49c8d2daa551aab'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1405/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a66589a30205a203d49c8d2daa551aab'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718470"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a66589a30205a203d49c8d2daa551aab'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718470"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82288" title="Codeforces Round #668" target="_blank">Codeforces Round #668 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11869" resourceName="Codeforces Round #668"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82366" title="Codeforces Round #668 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11884" resourceName="Codeforces Round #668 Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1405">Задачи</a></li>
<li><a
href="/contest/1405/submit">Отослать</a></li>
<li><a
href="/contest/1405/my">Мои посылки</a></li>
<li><a
href="/contest/1405/status">Статус</a></li>
<li><a
href="/contest/1405/hacks">Взломы</a></li>
<li><a
href="/contest/1405/room/1">Комната</a></li>
<li><a
href="/contest/1405/standings">Положение</a></li>
<li><a
href="/contest/1405/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_e9c62661f4420f5ab237a96125335115256a22d4">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Уничтожение фиксированных точек</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дан массив $$$a_1, \ldots, a_n$$$ из $$$n$$$ положительных целых чисел. За одну операцию можно выбрать индекс $$$i$$$, удовлетворяющий $$$a_i = i$$$, и удалить $$$a_i$$$ из массива (после удаления остальные части массива соединяются).</p><p>Вес $$$a$$$ определяется как максимальное количество элементов, которые можно удалить.</p><p>Вы должны ответить на $$$q$$$ независимых запросов $$$(x, y)$$$: после замены первых $$$x$$$ элементов $$$a$$$ и последних $$$y$$$ элементов $$$a$$$ на $$$n+1$$$ (делая их удаление невозможным), чему будет равен вес $$$a$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n, q \le 3 \cdot 10^5$$$) — длину массива и количество запросов.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$) — элементы массива.</p><p>$$$i$$$-я из следующих $$$q$$$ строк содержит два целых числа $$$x$$$ и $$$y$$$ ($$$x, y \ge 0$$$ и $$$x+y < n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк, $$$i$$$-я строка должна содержать единственное целое число — ответ на $$$i$$$-й запрос.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
13 5
2 2 3 9 5 4 6 5 7 8 3 11 13
3 1
0 0
2 4
5 0
0 12
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
11
6
1
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 2
1 4 1 2 4
0 0
1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение первого запроса:</p><p>После того, как первые $$$x = 3$$$ и последние $$$y = 1$$$ элементов стало невозможно удалить, $$$a$$$ становится равным $$$[\times, \times, \times, 9, 5, 4, 6, 5, 7, 8, 3, 11, \times]$$$ (для наглядности мы представляем $$$14$$$ как $$$\times$$$).</p><p>Вот стратегия, которая удаляет $$$5$$$ элементов (удаленный элемент окрашен в красный цвет):</p><ul> <li> $$$[\times, \times, \times, 9, \color{red}{5}, 4, 6, 5, 7, 8, 3, 11, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 6, 5, 7, 8, 3, \color{red}{11}, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, \color{red}{6}, 5, 7, 8, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, 7, \color{red}{8}, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, \color{red}{7}, 3, \times]$$$ </li><li> $$$[\times, \times, \times, 9, 4, 5, 3, \times]$$$ (конечное состояние) </li></ul><p>Невозможно удалить более $$$5$$$ элементов, поэтому вес составляет $$$5$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:20</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aac6ee347b8b',t:'MTY5NjY2NjIyMC43MTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2300"] | ||
1406A | 1406 | A | ru | A. Mex подмножеств | <div class="problem-statement"><div class="header"><div class="title">A. Mex подмножеств</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан набор целых чисел (он может содержать одинаковые элементы).</p><p>Вы должны разделить его на два подмножества $$$A$$$ и $$$B$$$ (каждое из них также может содержать одинаковые элементы или может быть пустым). Вы должны максимизировать значение $$$mex(A)+mex(B)$$$.</p><p>Здесь $$$mex$$$ набора целых чисел определяется как наименьшее неотрицательное целое число, которое не принадлежит этому набору. Например:</p><ul> <li> $$$mex(\{1,4,0,2,2,1\})=3$$$ </li><li> $$$mex(\{3,3,2,1,3,0,0\})=4$$$ </li><li> $$$mex(\varnothing)=0$$$ ($$$mex$$$ пустого множества) </li></ul><p>Набор разделен на два подмножества $$$A$$$ и $$$B$$$, если для любого целого числа $$$x$$$ количество вхождений $$$x$$$ в этот набор равно сумме количеств вхождений $$$x$$$ в $$$A$$$ и $$$x$$$ в $$$B$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1\leq t\leq 100$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1\leq n\leq 100$$$) — размер набора целых чисел.</p><p>Во второй строке описания каждого набора входных данных находится $$$n$$$ целых чисел $$$a_1,a_2,\dots a_n$$$ ($$$0\leq a_i\leq 100$$$) — элементы данного вам набора целых чисел.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите максимальное значение $$$mex(A)+mex(B)$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
6
0 2 1 5 0 1
3
0 1 2
4
0 2 0 1
6
1 2 3 4 5 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
3
4
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$A=\left\{0,1,2\right\},B=\left\{0,1,5\right\}$$$ является возможным выбором разделения.</p><p>Во втором наборе входных данных $$$A=\left\{0,1,2\right\},B=\varnothing$$$ является возможным выбором разделения.</p><p>В третьем наборе входных данных $$$A=\left\{0,1,2\right\},B=\left\{0\right\}$$$ является возможным выбором разделения.</p><p>В четвертом наборе входных данных $$$A=\left\{1,3,5\right\},B=\left\{2,4,6\right\}$$$ является возможным выбором разделения.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="b9c3d4ce551db3c98337d5260ecc4822"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="f735038c1e10685b158c53179d4a1ed255ccde05"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='b9c3d4ce551db3c98337d5260ecc4822'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1406%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='b9c3d4ce551db3c98337d5260ecc4822'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1406">Codeforces Round 670 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='b9c3d4ce551db3c98337d5260ecc4822'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1406/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*900
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b9c3d4ce551db3c98337d5260ecc4822'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="720771"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b9c3d4ce551db3c98337d5260ecc4822'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="720771"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82500" title="Codeforces Round #670 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11904" resourceName="Codeforces Round #670 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82560" title="Codeforces Round #670 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12504" resourceName="Codeforces Round #670 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1406">Задачи</a></li>
<li><a
href="/contest/1406/submit">Отослать</a></li>
<li><a
href="/contest/1406/my">Мои посылки</a></li>
<li><a
href="/contest/1406/status">Статус</a></li>
<li><a
href="/contest/1406/hacks">Взломы</a></li>
<li><a
href="/contest/1406/room/1">Комната</a></li>
<li><a
href="/contest/1406/standings">Положение</a></li>
<li><a
href="/contest/1406/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_8634b5f559b8e646b02db80c6349a8684eadba57">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Mex подмножеств</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан набор целых чисел (он может содержать одинаковые элементы).</p><p>Вы должны разделить его на два подмножества $$$A$$$ и $$$B$$$ (каждое из них также может содержать одинаковые элементы или может быть пустым). Вы должны максимизировать значение $$$mex(A)+mex(B)$$$.</p><p>Здесь $$$mex$$$ набора целых чисел определяется как наименьшее неотрицательное целое число, которое не принадлежит этому набору. Например:</p><ul> <li> $$$mex(\{1,4,0,2,2,1\})=3$$$ </li><li> $$$mex(\{3,3,2,1,3,0,0\})=4$$$ </li><li> $$$mex(\varnothing)=0$$$ ($$$mex$$$ пустого множества) </li></ul><p>Набор разделен на два подмножества $$$A$$$ и $$$B$$$, если для любого целого числа $$$x$$$ количество вхождений $$$x$$$ в этот набор равно сумме количеств вхождений $$$x$$$ в $$$A$$$ и $$$x$$$ в $$$B$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1\leq t\leq 100$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1\leq n\leq 100$$$) — размер набора целых чисел.</p><p>Во второй строке описания каждого набора входных данных находится $$$n$$$ целых чисел $$$a_1,a_2,\dots a_n$$$ ($$$0\leq a_i\leq 100$$$) — элементы данного вам набора целых чисел.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите максимальное значение $$$mex(A)+mex(B)$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
6
0 2 1 5 0 1
3
0 1 2
4
0 2 0 1
6
1 2 3 4 5 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
3
4
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$A=\left\{0,1,2\right\},B=\left\{0,1,5\right\}$$$ является возможным выбором разделения.</p><p>Во втором наборе входных данных $$$A=\left\{0,1,2\right\},B=\varnothing$$$ является возможным выбором разделения.</p><p>В третьем наборе входных данных $$$A=\left\{0,1,2\right\},B=\left\{0\right\}$$$ является возможным выбором разделения.</p><p>В четвертом наборе входных данных $$$A=\left\{1,3,5\right\},B=\left\{2,4,6\right\}$$$ является возможным выбором разделения.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:22</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aacf8d4e16a7',t:'MTY5NjY2NjIyMi4xNjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*900"] | ||
1406B | 1406 | B | ru | B. Максимальное произведение | <div class="problem-statement"><div class="header"><div class="title">B. Максимальное произведение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив целых чисел $$$a_1,a_2,\ldots,a_n$$$. Найдите максимум $$$a_ia_ja_ka_la_t$$$ по всем пятеркам индексов $$$(i, j, k, l, t)$$$ ($$$i<j<k<l<t$$$).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1\le t\le 2 \cdot 10^4$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$5\le n\le 10^5$$$) — размер массива.</p><p>Во второй строке описания каждого набора входных данных находится $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$-3\times 10^3\le a_i\le 3\times 10^3$$$) — данный массив.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число — ответ на задачу.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
5
-1 -2 -3 -4 -5
6
-1 -2 -3 1 2 -1
6
-1 0 0 0 -1 -1
6
-9 -7 -5 -3 -2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-120
12
0
945
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных выбор $$$a_1,a_2,a_3,a_4,a_5$$$ является наилучшим: $$$(-1)\cdot (-2) \cdot (-3)\cdot (-4)\cdot (-5)=-120$$$.</p><p>Во втором наборе входных данных выбор $$$a_1,a_2,a_3,a_5,a_6$$$ является наилучшим: $$$(-1)\cdot (-2) \cdot (-3)\cdot 2\cdot (-1)=12$$$.</p><p>В третьем наборе входных данных выбор $$$a_1,a_2,a_3,a_4,a_5$$$ является наилучшим: $$$(-1)\cdot 0\cdot 0\cdot 0\cdot (-1)=0$$$.</p><p>В четвертом наборе входных данных выбор $$$a_1,a_2,a_3,a_4,a_6$$$ является наилучшим: $$$(-9)\cdot (-7) \cdot (-5)\cdot (-3)\cdot 1=945$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="a031723cb1f7abd0c8d4908c8a5b4297"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="f735038c1e10685b158c53179d4a1ed255ccde05"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='a031723cb1f7abd0c8d4908c8a5b4297'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1406%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='a031723cb1f7abd0c8d4908c8a5b4297'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1406">Codeforces Round 670 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='a031723cb1f7abd0c8d4908c8a5b4297'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1406/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a031723cb1f7abd0c8d4908c8a5b4297'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="725449"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a031723cb1f7abd0c8d4908c8a5b4297'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="725449"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82500" title="Codeforces Round #670 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11904" resourceName="Codeforces Round #670 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82560" title="Codeforces Round #670 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12504" resourceName="Codeforces Round #670 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1406">Задачи</a></li>
<li><a
href="/contest/1406/submit">Отослать</a></li>
<li><a
href="/contest/1406/my">Мои посылки</a></li>
<li><a
href="/contest/1406/status">Статус</a></li>
<li><a
href="/contest/1406/hacks">Взломы</a></li>
<li><a
href="/contest/1406/room/1">Комната</a></li>
<li><a
href="/contest/1406/standings">Положение</a></li>
<li><a
href="/contest/1406/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_f610fffe27e58ee5847afbf60ec98d20b238eaf0">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Максимальное произведение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив целых чисел $$$a_1,a_2,\ldots,a_n$$$. Найдите максимум $$$a_ia_ja_ka_la_t$$$ по всем пятеркам индексов $$$(i, j, k, l, t)$$$ ($$$i<j<k<l<t$$$).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1\le t\le 2 \cdot 10^4$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$5\le n\le 10^5$$$) — размер массива.</p><p>Во второй строке описания каждого набора входных данных находится $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$-3\times 10^3\le a_i\le 3\times 10^3$$$) — данный массив.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число — ответ на задачу.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
5
-1 -2 -3 -4 -5
6
-1 -2 -3 1 2 -1
6
-1 0 0 0 -1 -1
6
-9 -7 -5 -3 -2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-120
12
0
945
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных выбор $$$a_1,a_2,a_3,a_4,a_5$$$ является наилучшим: $$$(-1)\cdot (-2) \cdot (-3)\cdot (-4)\cdot (-5)=-120$$$.</p><p>Во втором наборе входных данных выбор $$$a_1,a_2,a_3,a_5,a_6$$$ является наилучшим: $$$(-1)\cdot (-2) \cdot (-3)\cdot 2\cdot (-1)=12$$$.</p><p>В третьем наборе входных данных выбор $$$a_1,a_2,a_3,a_4,a_5$$$ является наилучшим: $$$(-1)\cdot 0\cdot 0\cdot 0\cdot (-1)=0$$$.</p><p>В четвертом наборе входных данных выбор $$$a_1,a_2,a_3,a_4,a_6$$$ является наилучшим: $$$(-9)\cdot (-7) \cdot (-5)\cdot (-3)\cdot 1=945$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:23</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aad83abc2de2',t:'MTY5NjY2NjIyMy40NzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1200"] | ||
1406C | 1406 | C | ru | C. Link Cut центроиды | <div class="problem-statement"><div class="header"><div class="title">C. Link Cut центроиды</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Fishing Prince любит деревья и особенно он любит деревья с ровно одним центроидом. Деревом называется связный граф без циклов.</p><p>Вершина называется <span class="tex-font-style-bf">центроидом</span> дерева тогда и только тогда, когда при удалении этой вершины (удалении вершины и всех выходящих из нее ребер) размер наибольшей компоненты связности оставшегося графа будет наименьший возможный.</p><p>Например, вершина $$$2$$$ является центроидом дерева на следующей картинке, потому что после того, как вы удалите ее, размер наибольшей компоненты связности оставшегося графа будет равен $$$2$$$. Невозможно удалить другую вершину, чтобы этот размер был меньше.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5ad0d25c08ce9984ee6feb1955ddb2562dc91b7e.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Однако, в некоторых деревьях может быть больше одного центроида, например:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2d2d588643dde1aa8f6787434a88245bea97d5c7.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Обе вершины $$$1$$$ и $$$2$$$ являются центроидами, потому что размер наибольшей компоненты связности будет равен $$$3$$$ после удаления любой из них.</p><p>Сейчас у Fishing Prince есть дерево. Он должен удалить одно ребро дерева. После этого он должен добавить одно ребро. Получившийся после этих двух операций граф снова должен стать деревом. Можно добавить только что удаленное ребро.</p><p>Он хочет, чтобы у получившегося дерева был единственный центроид. Помогите ему и найдите любую возможную пару операций, которые можно сделать. Можно доказать, что хотя бы один способ сделать такую пару операций существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1\leq t\leq 10^4$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В первой строке описания каждого набора входных данных находится целое число $$$n$$$ ($$$3\leq n\leq 10^5$$$) — количество вершин.</p><p>Каждая из следующей $$$n-1$$$ строки содержит два целых числа $$$x, y$$$ ($$$1\leq x,y\leq n$$$). Они означают, что существует ребро, соединяющее вершины $$$x$$$ и $$$y$$$.</p><p>Гарантируется, что данный граф является деревом.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите два целых числа $$$x_1, y_1$$$ ($$$1 \leq x_1, y_1 \leq n$$$), которые означают, что вы удаляете ребро между вершинами $$$x_1$$$ и $$$y_1$$$. Должно существовать ребро, соединяющее вершины $$$x_1$$$ и $$$y_1$$$.</p><p>Во второй строке выведите два целых числа $$$x_2, y_2$$$ ($$$1 \leq x_2, y_2 \leq n$$$), которые означают, что вы добавляете ребро между вершинами $$$x_2$$$ и $$$y_2$$$.</p><p>Граф, получающийся после применения этих двух операций, должен снова являться деревом.</p><p>Если существует несколько возможных решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
5
1 2
1 3
2 4
2 5
6
1 2
1 3
1 4
2 5
2 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 2
1 2
1 3
2 3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обратите внимание, что вы можете добавлять то же самое ребро, которое вы удалили.</p><p>В первом наборе входных данных после удаления и добавления одного и того же ребра вершина $$$2$$$ по-прежнему останется единственным центроидом.</p><p>Во втором наборе входных данных вершина $$$2$$$ станет единственным центроидом после удаления ребра между вершинами $$$1$$$ и $$$3$$$ и добавления ребра между вершинами $$$2$$$ и $$$3$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="07b785abe002991d7be01cccc3ebdb74"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="f735038c1e10685b158c53179d4a1ed255ccde05"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='07b785abe002991d7be01cccc3ebdb74'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1406%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='07b785abe002991d7be01cccc3ebdb74'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1406">Codeforces Round 670 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='07b785abe002991d7be01cccc3ebdb74'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1406/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1700
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='07b785abe002991d7be01cccc3ebdb74'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="720773"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='07b785abe002991d7be01cccc3ebdb74'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="720773"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82500" title="Codeforces Round #670 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11904" resourceName="Codeforces Round #670 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82560" title="Codeforces Round #670 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12504" resourceName="Codeforces Round #670 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1406">Задачи</a></li>
<li><a
href="/contest/1406/submit">Отослать</a></li>
<li><a
href="/contest/1406/my">Мои посылки</a></li>
<li><a
href="/contest/1406/status">Статус</a></li>
<li><a
href="/contest/1406/hacks">Взломы</a></li>
<li><a
href="/contest/1406/room/1">Комната</a></li>
<li><a
href="/contest/1406/standings">Положение</a></li>
<li><a
href="/contest/1406/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_78a312b586330be7150eaefd6609df0b1852a961">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Link Cut центроиды</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Fishing Prince любит деревья и особенно он любит деревья с ровно одним центроидом. Деревом называется связный граф без циклов.</p><p>Вершина называется <span class="tex-font-style-bf">центроидом</span> дерева тогда и только тогда, когда при удалении этой вершины (удалении вершины и всех выходящих из нее ребер) размер наибольшей компоненты связности оставшегося графа будет наименьший возможный.</p><p>Например, вершина $$$2$$$ является центроидом дерева на следующей картинке, потому что после того, как вы удалите ее, размер наибольшей компоненты связности оставшегося графа будет равен $$$2$$$. Невозможно удалить другую вершину, чтобы этот размер был меньше.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5ad0d25c08ce9984ee6feb1955ddb2562dc91b7e.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Однако, в некоторых деревьях может быть больше одного центроида, например:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2d2d588643dde1aa8f6787434a88245bea97d5c7.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Обе вершины $$$1$$$ и $$$2$$$ являются центроидами, потому что размер наибольшей компоненты связности будет равен $$$3$$$ после удаления любой из них.</p><p>Сейчас у Fishing Prince есть дерево. Он должен удалить одно ребро дерева. После этого он должен добавить одно ребро. Получившийся после этих двух операций граф снова должен стать деревом. Можно добавить только что удаленное ребро.</p><p>Он хочет, чтобы у получившегося дерева был единственный центроид. Помогите ему и найдите любую возможную пару операций, которые можно сделать. Можно доказать, что хотя бы один способ сделать такую пару операций существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из нескольких наборов входных данных. В первой строке находится единственное целое число $$$t$$$ ($$$1\leq t\leq 10^4$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В первой строке описания каждого набора входных данных находится целое число $$$n$$$ ($$$3\leq n\leq 10^5$$$) — количество вершин.</p><p>Каждая из следующей $$$n-1$$$ строки содержит два целых числа $$$x, y$$$ ($$$1\leq x,y\leq n$$$). Они означают, что существует ребро, соединяющее вершины $$$x$$$ и $$$y$$$.</p><p>Гарантируется, что данный граф является деревом.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки.</p><p>В первой строке выведите два целых числа $$$x_1, y_1$$$ ($$$1 \leq x_1, y_1 \leq n$$$), которые означают, что вы удаляете ребро между вершинами $$$x_1$$$ и $$$y_1$$$. Должно существовать ребро, соединяющее вершины $$$x_1$$$ и $$$y_1$$$.</p><p>Во второй строке выведите два целых числа $$$x_2, y_2$$$ ($$$1 \leq x_2, y_2 \leq n$$$), которые означают, что вы добавляете ребро между вершинами $$$x_2$$$ и $$$y_2$$$.</p><p>Граф, получающийся после применения этих двух операций, должен снова являться деревом.</p><p>Если существует несколько возможных решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
5
1 2
1 3
2 4
2 5
6
1 2
1 3
1 4
2 5
2 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 2
1 2
1 3
2 3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обратите внимание, что вы можете добавлять то же самое ребро, которое вы удалили.</p><p>В первом наборе входных данных после удаления и добавления одного и того же ребра вершина $$$2$$$ по-прежнему останется единственным центроидом.</p><p>Во втором наборе входных данных вершина $$$2$$$ станет единственным центроидом после удаления ребра между вершинами $$$1$$$ и $$$3$$$ и добавления ребра между вершинами $$$2$$$ и $$$3$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:24</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aae0fb8b2de2',t:'MTY5NjY2NjIyNC44ODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*1700"] | ||
1406D | 1406 | D | ru | D. Три последовательности | <div class="problem-statement"><div class="header"><div class="title">D. Три последовательности</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дана последовательность из $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$.</p><p>Вы должны построить две последовательности целых чисел $$$b$$$ и $$$c$$$ длины $$$n$$$, которые удовлетворяют условиям:</p><ul> <li> для всех $$$i$$$ ($$$1\leq i\leq n$$$) $$$b_i+c_i=a_i$$$; </li><li> $$$b$$$ неубывающая, что означает, что для всех $$$1<i\leq n$$$, выполнено $$$b_i\geq b_{i-1}$$$; </li><li> $$$c$$$ невозрастающая, что означает, что для всех $$$1<i\leq n$$$, выполнено $$$c_i\leq c_{i-1}$$$. </li></ul><p>Вы хотите минимизировать $$$\max(b_i,c_i)$$$. Другими словами, вы хотите минимизировать максимум чисел в последовательностях $$$b$$$ и $$$c$$$.</p><p>Также будет сделано $$$q$$$ изменений, $$$i$$$-е изменение описывается тройкой чисел $$$l,r,x$$$. Вы должны добавить $$$x$$$ к $$$a_l,a_{l+1}, \ldots, a_r$$$.</p><p>Вы должны найти минимальное значение $$$\max(b_i,c_i)$$$ для изначальной последовательности и для последовательности после каждого изменения.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1\leq n\leq 10^5$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$1\leq i\leq n$$$, $$$-10^9\leq a_i\leq 10^9$$$).</p><p>В третьей строке находится единственное целое число $$$q$$$ ($$$1\leq q\leq 10^5$$$).</p><p>Каждая из следующих $$$q$$$ строк содержит три целых числа $$$l,r,x$$$ ($$$1\leq l\leq r\leq n,-10^9\leq x\leq 10^9$$$), описывающих очередное изменение. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q+1$$$ строку.</p><p>В $$$i$$$-й ($$$1 \leq i \leq q+1$$$) строке выведите ответ на задачу для последовательности после $$$i-1$$$ изменения.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
2 -1 7 3
2
2 4 -3
3 4 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
5
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
-9 -10 -9 -6 -5 4
3
2 6 -9
1 2 -10
4 6 -3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
3
3
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
0
2
1 1 -1
1 1 -1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте:</p><ul> <li> Изначальная последовательность $$$a = (2, -1, 7, 3)$$$. Пара последовательностей $$$b=(-3,-3,5,5),c=(5,2,2,-2)$$$ является возможным выбором. </li><li> После первого изменения $$$a = (2, -4, 4, 0)$$$. Пара последовательностей $$$b=(-3,-3,5,5),c=(5,-1,-1,-5)$$$ является возможным выбором. </li><li> После второго изменения $$$a = (2, -4, 6, 2)$$$. Пара последовательностей $$$b=(-4,-4,6,6),c=(6,0,0,-4)$$$ является возможным выбором. </li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="61a4a102c64810f0e9281121f400cb00"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="f735038c1e10685b158c53179d4a1ed255ccde05"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='61a4a102c64810f0e9281121f400cb00'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1406%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='61a4a102c64810f0e9281121f400cb00'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1406">Codeforces Round 670 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='61a4a102c64810f0e9281121f400cb00'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1406/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='61a4a102c64810f0e9281121f400cb00'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="720774"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='61a4a102c64810f0e9281121f400cb00'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="720774"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82500" title="Codeforces Round #670 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11904" resourceName="Codeforces Round #670 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82560" title="Codeforces Round #670 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12504" resourceName="Codeforces Round #670 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1406">Задачи</a></li>
<li><a
href="/contest/1406/submit">Отослать</a></li>
<li><a
href="/contest/1406/my">Мои посылки</a></li>
<li><a
href="/contest/1406/status">Статус</a></li>
<li><a
href="/contest/1406/hacks">Взломы</a></li>
<li><a
href="/contest/1406/room/1">Комната</a></li>
<li><a
href="/contest/1406/standings">Положение</a></li>
<li><a
href="/contest/1406/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_42c35f8aab46ca17319e6ea68fe8b119c3cc1514">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Три последовательности</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дана последовательность из $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$.</p><p>Вы должны построить две последовательности целых чисел $$$b$$$ и $$$c$$$ длины $$$n$$$, которые удовлетворяют условиям:</p><ul> <li> для всех $$$i$$$ ($$$1\leq i\leq n$$$) $$$b_i+c_i=a_i$$$; </li><li> $$$b$$$ неубывающая, что означает, что для всех $$$1<i\leq n$$$, выполнено $$$b_i\geq b_{i-1}$$$; </li><li> $$$c$$$ невозрастающая, что означает, что для всех $$$1<i\leq n$$$, выполнено $$$c_i\leq c_{i-1}$$$. </li></ul><p>Вы хотите минимизировать $$$\max(b_i,c_i)$$$. Другими словами, вы хотите минимизировать максимум чисел в последовательностях $$$b$$$ и $$$c$$$.</p><p>Также будет сделано $$$q$$$ изменений, $$$i$$$-е изменение описывается тройкой чисел $$$l,r,x$$$. Вы должны добавить $$$x$$$ к $$$a_l,a_{l+1}, \ldots, a_r$$$.</p><p>Вы должны найти минимальное значение $$$\max(b_i,c_i)$$$ для изначальной последовательности и для последовательности после каждого изменения.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1\leq n\leq 10^5$$$).</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1,a_2,\ldots,a_n$$$ ($$$1\leq i\leq n$$$, $$$-10^9\leq a_i\leq 10^9$$$).</p><p>В третьей строке находится единственное целое число $$$q$$$ ($$$1\leq q\leq 10^5$$$).</p><p>Каждая из следующих $$$q$$$ строк содержит три целых числа $$$l,r,x$$$ ($$$1\leq l\leq r\leq n,-10^9\leq x\leq 10^9$$$), описывающих очередное изменение. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q+1$$$ строку.</p><p>В $$$i$$$-й ($$$1 \leq i \leq q+1$$$) строке выведите ответ на задачу для последовательности после $$$i-1$$$ изменения.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
2 -1 7 3
2
2 4 -3
3 4 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
5
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
-9 -10 -9 -6 -5 4
3
2 6 -9
1 2 -10
4 6 -3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
3
3
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
0
2
1 1 -1
1 1 -1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте:</p><ul> <li> Изначальная последовательность $$$a = (2, -1, 7, 3)$$$. Пара последовательностей $$$b=(-3,-3,5,5),c=(5,2,2,-2)$$$ является возможным выбором. </li><li> После первого изменения $$$a = (2, -4, 4, 0)$$$. Пара последовательностей $$$b=(-3,-3,5,5),c=(5,-1,-1,-5)$$$ является возможным выбором. </li><li> После второго изменения $$$a = (2, -4, 6, 2)$$$. Пара последовательностей $$$b=(-4,-4,6,6),c=(6,0,0,-4)$$$ является возможным выбором. </li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:26</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aae92fba7b4b',t:'MTY5NjY2NjIyNi4yMjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"] | ||
1406E | 1406 | E | ru | E. Удаление чисел | <div class="problem-statement"><div class="header"><div class="title">E. Удаление чисел</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Загадано неизвестное целое число $$$x$$$ ($$$1\le x\le n$$$). Вы хотите найти $$$x$$$.</p><p>Сначала у вас есть множество целых чисел $$$\{1, 2, \ldots, n\}$$$. Вы можете сделать следующие операции не более $$$10000$$$ раз:</p><ul> <li> <span class="tex-font-style-tt">A</span> $$$a$$$: узнать, сколько есть чисел, делящихся на $$$a$$$ в текущем множестве. </li><li> <span class="tex-font-style-tt">B</span> $$$a$$$: узнать, сколько есть чисел, делящихся на $$$a$$$ в текущем множестве и затем удалить все числа, делящиеся на $$$a$$$ из множества. При этом число $$$x$$$ не будет удаляться никогда (даже если оно делится на $$$a$$$). В этой операции $$$a$$$ должно быть больше $$$1$$$. </li><li> <span class="tex-font-style-tt">C</span> $$$a$$$: вы делаете эту операцию, если вы знаете, что $$$x=a$$$. Эта операция может быть выполнена только один раз. </li></ul><p>Обратите внимание, что в операции типа <span class="tex-font-style-tt">B</span> должно выполняться, что $$$a>1$$$.</p><p>Напишите программу, которая найдет значение числа $$$x$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1\le n\le 10^5$$$). Остальные части входных данных будут получены в процессе взаимодействия.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Каждый раз, ваша программа должна вывести строку, содержащую один символ <span class="tex-font-style-tt">A</span>, <span class="tex-font-style-tt">B</span> или <span class="tex-font-style-tt">C</span> и целое число $$$a$$$ ($$$1\le a\le n$$$ для операций <span class="tex-font-style-tt">A</span> и <span class="tex-font-style-tt">C</span>, $$$2\le a\le n$$$ для операций <span class="tex-font-style-tt">B</span>). Эта строка описывает операцию, которую вы выполняете.</p><p>Если ваша операция имеет тип <span class="tex-font-style-tt">C</span>, ваша программа должна завершиться немедленно.</p><p>Иначе ваша программа должна считать единственное целое число, являющееся ответом на вашу операцию.</p><p>После вывода каждой строки не забывайте сбрасывать буфер потока вывода. Для этого используйте:</p><ul> <li> fflush(stdout) в C/C++; </li><li> System.out.flush() в Java; </li><li> sys.stdout.flush() в Python; </li><li> flush(output) в Pascal; </li><li> Обратитесь к документации для других языков. </li></ul><p>Гарантируется, что число $$$x$$$ зафиксировано и не будет меняться в процессе взаимодействия.</p><p><span class="tex-font-style-bf">Взломы:</span></p><p>Чтобы сделать взлом, используйте следующий формат входных данных:</p><p>В единственной строке находятся два целых числа $$$n$$$, $$$x$$$ ($$$1 \leq x \leq n \leq 10^5$$$).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
10
2
4
0</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
B 4
A 2
A 8
C 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обратите внимание, что для того, чтобы сделать тест из примера более понятным, мы добавили пустые строки. Вам не нужно выводить никаких пустых строк в процессе взаимодействия.</p><p>В первом тесте $$$n=10$$$ и $$$x=4$$$.</p><p>Изначальное множество — это $$$\{1,2,3,4,5,6,7,8,9,10\}$$$.</p><p>В первой операции вы спрашиваете, сколько чисел делятся на $$$4$$$ и удаляете их. Ответ $$$2$$$, потому что есть два числа, делящиеся на $$$4$$$: $$$\{4,8\}$$$. Число $$$8$$$ будет удалено, но $$$4$$$ нет, потому что число $$$x$$$ никогда не удаляется. Теперь множество — это $$$\{1,2,3,4,5,6,7,9,10\}$$$.</p><p>Во второй операции вы спрашиваете, сколько чисел являются делятся на $$$2$$$. Ответ равен $$$4$$$, потому что четыре числа делятся на $$$2$$$: $$$\{2,4,6,10\}$$$.</p><p>В третьей операции вы спрашиваете, сколько чисел делятся на $$$8$$$. Ответ равен $$$0$$$, потому что ни одно из чисел в текущем множестве не делится на $$$8$$$.</p><p>В четвертой операции вы сообщаете, что вы знаете, что $$$x=4$$$. Это является правильным ответом.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="180fd19840934d6018f2ab0a3bf23dd6"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="f735038c1e10685b158c53179d4a1ed255ccde05"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='180fd19840934d6018f2ab0a3bf23dd6'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1406%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='180fd19840934d6018f2ab0a3bf23dd6'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1406">Codeforces Round 670 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='180fd19840934d6018f2ab0a3bf23dd6'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1406/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='180fd19840934d6018f2ab0a3bf23dd6'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="720775"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='180fd19840934d6018f2ab0a3bf23dd6'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="720775"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82500" title="Codeforces Round #670 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11904" resourceName="Codeforces Round #670 (Div. 2)"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82560" title="Codeforces Round #670 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12504" resourceName="Codeforces Round #670 (Div. 2) Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1406">Задачи</a></li>
<li><a
href="/contest/1406/submit">Отослать</a></li>
<li><a
href="/contest/1406/my">Мои посылки</a></li>
<li><a
href="/contest/1406/status">Статус</a></li>
<li><a
href="/contest/1406/hacks">Взломы</a></li>
<li><a
href="/contest/1406/room/1">Комната</a></li>
<li><a
href="/contest/1406/standings">Положение</a></li>
<li><a
href="/contest/1406/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_e9a5ed15d2e238802af89f841d7e02b1fc02e75f">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Удаление чисел</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Загадано неизвестное целое число $$$x$$$ ($$$1\le x\le n$$$). Вы хотите найти $$$x$$$.</p><p>Сначала у вас есть множество целых чисел $$$\{1, 2, \ldots, n\}$$$. Вы можете сделать следующие операции не более $$$10000$$$ раз:</p><ul> <li> <span class="tex-font-style-tt">A</span> $$$a$$$: узнать, сколько есть чисел, делящихся на $$$a$$$ в текущем множестве. </li><li> <span class="tex-font-style-tt">B</span> $$$a$$$: узнать, сколько есть чисел, делящихся на $$$a$$$ в текущем множестве и затем удалить все числа, делящиеся на $$$a$$$ из множества. При этом число $$$x$$$ не будет удаляться никогда (даже если оно делится на $$$a$$$). В этой операции $$$a$$$ должно быть больше $$$1$$$. </li><li> <span class="tex-font-style-tt">C</span> $$$a$$$: вы делаете эту операцию, если вы знаете, что $$$x=a$$$. Эта операция может быть выполнена только один раз. </li></ul><p>Обратите внимание, что в операции типа <span class="tex-font-style-tt">B</span> должно выполняться, что $$$a>1$$$.</p><p>Напишите программу, которая найдет значение числа $$$x$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ ($$$1\le n\le 10^5$$$). Остальные части входных данных будут получены в процессе взаимодействия.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Каждый раз, ваша программа должна вывести строку, содержащую один символ <span class="tex-font-style-tt">A</span>, <span class="tex-font-style-tt">B</span> или <span class="tex-font-style-tt">C</span> и целое число $$$a$$$ ($$$1\le a\le n$$$ для операций <span class="tex-font-style-tt">A</span> и <span class="tex-font-style-tt">C</span>, $$$2\le a\le n$$$ для операций <span class="tex-font-style-tt">B</span>). Эта строка описывает операцию, которую вы выполняете.</p><p>Если ваша операция имеет тип <span class="tex-font-style-tt">C</span>, ваша программа должна завершиться немедленно.</p><p>Иначе ваша программа должна считать единственное целое число, являющееся ответом на вашу операцию.</p><p>После вывода каждой строки не забывайте сбрасывать буфер потока вывода. Для этого используйте:</p><ul> <li> fflush(stdout) в C/C++; </li><li> System.out.flush() в Java; </li><li> sys.stdout.flush() в Python; </li><li> flush(output) в Pascal; </li><li> Обратитесь к документации для других языков. </li></ul><p>Гарантируется, что число $$$x$$$ зафиксировано и не будет меняться в процессе взаимодействия.</p><p><span class="tex-font-style-bf">Взломы:</span></p><p>Чтобы сделать взлом, используйте следующий формат входных данных:</p><p>В единственной строке находятся два целых числа $$$n$$$, $$$x$$$ ($$$1 \leq x \leq n \leq 10^5$$$).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
10
2
4
0</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
B 4
A 2
A 8
C 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обратите внимание, что для того, чтобы сделать тест из примера более понятным, мы добавили пустые строки. Вам не нужно выводить никаких пустых строк в процессе взаимодействия.</p><p>В первом тесте $$$n=10$$$ и $$$x=4$$$.</p><p>Изначальное множество — это $$$\{1,2,3,4,5,6,7,8,9,10\}$$$.</p><p>В первой операции вы спрашиваете, сколько чисел делятся на $$$4$$$ и удаляете их. Ответ $$$2$$$, потому что есть два числа, делящиеся на $$$4$$$: $$$\{4,8\}$$$. Число $$$8$$$ будет удалено, но $$$4$$$ нет, потому что число $$$x$$$ никогда не удаляется. Теперь множество — это $$$\{1,2,3,4,5,6,7,9,10\}$$$.</p><p>Во второй операции вы спрашиваете, сколько чисел являются делятся на $$$2$$$. Ответ равен $$$4$$$, потому что четыре числа делятся на $$$2$$$: $$$\{2,4,6,10\}$$$.</p><p>В третьей операции вы спрашиваете, сколько чисел делятся на $$$8$$$. Ответ равен $$$0$$$, потому что ни одно из чисел в текущем множестве не делится на $$$8$$$.</p><p>В четвертой операции вы сообщаете, что вы знаете, что $$$x=4$$$. Это является правильным ответом.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:27</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aaf1acde1498',t:'MTY5NjY2NjIyNy42MTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2600"] | ||
1407A | 1407 | A | ru | A. Ахахахахахахахаха | <div class="problem-statement"><div class="header"><div class="title">A. Ахахахахахахахаха</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Александры есть массив $$$a$$$ <span class="tex-font-style-bf">четной</span> длины, состоящий из чисел $$$0$$$ и $$$1$$$. Элементы массива пронумерованы от $$$1$$$ до $$$n$$$. Она хочет удалить из него <span class="tex-font-style-bf">не более</span> $$$\frac{n}{2}$$$ элементов (где $$$n$$$ — его длина) таким образом, чтобы знакопеременная сумма массива была равна $$$0$$$ (т.е. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). Иными словами, Александра хочет, чтобы сумма всех элементов на нечетных позициях была равна сумме всех элементов на четных позициях. Элементы, которые вы удаляете, не обязаны быть последовательными.</p><p>К примеру, если у нее был массив $$$a = [1, 0, 1, 0, 0, 0]$$$, и она удалила $$$2$$$-й и $$$4$$$-й элементы, то $$$a$$$ станет равным $$$[1, 1, 0, 0]$$$ и его знакопеременная сумма будет равна $$$1 - 1 + 0 - 0 = 0$$$.</p><p>Помогите ей!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^3$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ <span class="tex-font-style-bf">четное</span>) — длину массива.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) — элементы массива.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^3$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных сначала выведите число $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) — число элементов, которые останутся после удаления. В следующей строке выведите $$$k$$$ чисел, которые не будут удалены, <span class="tex-font-style-bf">в том порядке, в котором они идут в массиве $$$a$$$</span>. Обратите внимание, вам надо вывести сами числа, <span class="tex-font-style-bf">а не их индексы</span>.</p><p>Можно показать, что ответ всегда существует. Если существует несколько ответов, выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
2
1 0
2
0 0
4
0 1 1 1
4
1 1 0 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
0
1
0
2
1 1
4
1 1 0 0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и втором наборах входных данных знакопеременная сумма массива, очевидно, равна $$$0$$$.</p><p>В третьем наборе входных данных знакопеременная сумма массива равна $$$1 - 1 = 0$$$.</p><p>В четвертом наборе входных данных знакопеременная сумма уже равна $$$1 - 1 + 0 - 0 = 0$$$, мы можем ничего не удалять.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="fa8d730976c693ee8a941471e9acee58"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0a39b312e9c3ad03d3dc5d4d9e9333a019bb6c8e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='fa8d730976c693ee8a941471e9acee58'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1407%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='fa8d730976c693ee8a941471e9acee58'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1407">Codeforces Round 669 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='fa8d730976c693ee8a941471e9acee58'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1407/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1100
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fa8d730976c693ee8a941471e9acee58'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718471"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fa8d730976c693ee8a941471e9acee58'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718471"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82329" title="82329" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12558:12559" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82417" title="Разбор Codeforces Round #669" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12086:12087" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1407">Задачи</a></li>
<li><a
href="/contest/1407/submit">Отослать</a></li>
<li><a
href="/contest/1407/my">Мои посылки</a></li>
<li><a
href="/contest/1407/status">Статус</a></li>
<li><a
href="/contest/1407/hacks">Взломы</a></li>
<li><a
href="/contest/1407/room/1">Комната</a></li>
<li><a
href="/contest/1407/standings">Положение</a></li>
<li><a
href="/contest/1407/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_98fce24e2e966b351eec735b193ec61370f8ee8d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Ахахахахахахахаха</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Александры есть массив $$$a$$$ <span class="tex-font-style-bf">четной</span> длины, состоящий из чисел $$$0$$$ и $$$1$$$. Элементы массива пронумерованы от $$$1$$$ до $$$n$$$. Она хочет удалить из него <span class="tex-font-style-bf">не более</span> $$$\frac{n}{2}$$$ элементов (где $$$n$$$ — его длина) таким образом, чтобы знакопеременная сумма массива была равна $$$0$$$ (т.е. $$$a_1 - a_2 + a_3 - a_4 + \dotsc = 0$$$). Иными словами, Александра хочет, чтобы сумма всех элементов на нечетных позициях была равна сумме всех элементов на четных позициях. Элементы, которые вы удаляете, не обязаны быть последовательными.</p><p>К примеру, если у нее был массив $$$a = [1, 0, 1, 0, 0, 0]$$$, и она удалила $$$2$$$-й и $$$4$$$-й элементы, то $$$a$$$ станет равным $$$[1, 1, 0, 0]$$$ и его знакопеременная сумма будет равна $$$1 - 1 + 0 - 0 = 0$$$.</p><p>Помогите ей!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^3$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^3$$$, $$$n$$$ <span class="tex-font-style-bf">четное</span>) — длину массива.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) — элементы массива.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^3$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных сначала выведите число $$$k$$$ ($$$\frac{n}{2} \leq k \leq n$$$) — число элементов, которые останутся после удаления. В следующей строке выведите $$$k$$$ чисел, которые не будут удалены, <span class="tex-font-style-bf">в том порядке, в котором они идут в массиве $$$a$$$</span>. Обратите внимание, вам надо вывести сами числа, <span class="tex-font-style-bf">а не их индексы</span>.</p><p>Можно показать, что ответ всегда существует. Если существует несколько ответов, выведите любой из них.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
2
1 0
2
0 0
4
0 1 1 1
4
1 1 0 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
0
1
0
2
1 1
4
1 1 0 0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и втором наборах входных данных знакопеременная сумма массива, очевидно, равна $$$0$$$.</p><p>В третьем наборе входных данных знакопеременная сумма массива равна $$$1 - 1 = 0$$$.</p><p>В четвертом наборе входных данных знакопеременная сумма уже равна $$$1 - 1 + 0 - 0 = 0$$$, мы можем ничего не удалять.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:29</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aafa486375a3',t:'MTY5NjY2NjIyOS4zNzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1100"] | ||
1407B | 1407 | B | ru | B. Большой Вова | <div class="problem-statement"><div class="header"><div class="title">B. Большой Вова</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Александр — известный в узких кругах программист. Однажды он решил наконец-то выйти на улицу и активно провести время с мячом, но первым же ударом он оставил вмятину на новом Rolls-Royce богатого и влиятельного предпринимателя Большого Вовы. Бизнесмен недавно открыл интернет-магазин на популярной торговой площадке «Змей-Горыныч», и предлагает Саше устроиться на работу: если он продемонстрирует свои способности, решив задачу, то получит должность специалиста по безопасности, а в противном случае — должность курьера.</p><p>Вам даны $$$n$$$ целых положительных чисел $$$a_1, a_2, \dots, a_n$$$. Используя каждое из данных чисел <span class="tex-font-style-bf">ровно 1 раз</span>, Вы должны составить такую последовательность $$$b_1, b_2, \dots, b_n$$$, что последовательность $$$c_1, c_2, \dots, c_n$$$ <span class="tex-font-style-it">лексикографически максимальна</span>, где $$$c_i=GCD(b_1,\dots,b_i)$$$ — наибольший общий делитель первых $$$i$$$ чисел последовательности $$$b$$$.</p><p>Александр сильно испугался условия этой несложной задачи, и поэтому он просит у Вас помощи.</p><p>Последовательность $$$a$$$ лексикографически меньше последовательности $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в последовательности $$$a$$$ элемент меньше, чем соответствующий элемент в $$$b$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^3$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^3$$$) — длину последовательности $$$a$$$.</p><p>Вторая строка каждого набора данных содержит $$$n$$$ целых чисел $$$a_1,\dots,a_n$$$ ($$$1 \le a_i \le 10^3$$$) — последовательность $$$a$$$.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^3$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ в отдельной строке — искомую последовательность $$$b$$$. Если существует несколько подходящих последовательностей, выведите любую из них. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
2
2 5
4
1 8 2 3
3
3 8 9
5
64 25 75 100 50
1
42
6
96 128 88 80 52 7
5
2 4 8 16 17
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5 2
8 2 1 3
9 3 8
100 50 25 75 64
42
128 96 80 88 52 7
17 2 4 8 16
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера есть всего две возможные перестановки $$$b$$$: $$$[2, 5]$$$ и $$$[5, 2]$$$. В первом случае $$$c=[2, 1]$$$, во втором $$$c=[5, 1]$$$.</p><p>В третьем наборе тестовых данных примера число $$$9$$$ должно идти первым в $$$b$$$, а $$$GCD(9, 3)=3$$$, $$$GCD(9, 8)=1$$$, поэтому вторым в $$$b$$$ идёт число $$$3$$$.</p><p>В седьмом наборе тестовых данных примера первые четыре числа попарно имеют общий делитель (степень двойки), однако ни одно из них не может идти первым в оптимальной перестановке $$$b$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="655c7016435bc50dfcd4a37a8dcf2e66"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0a39b312e9c3ad03d3dc5d4d9e9333a019bb6c8e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='655c7016435bc50dfcd4a37a8dcf2e66'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1407%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='655c7016435bc50dfcd4a37a8dcf2e66'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1407">Codeforces Round 669 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='655c7016435bc50dfcd4a37a8dcf2e66'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1407/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='655c7016435bc50dfcd4a37a8dcf2e66'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718472"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='655c7016435bc50dfcd4a37a8dcf2e66'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718472"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82329" title="82329" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12558:12559" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82417" title="Разбор Codeforces Round #669" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12086:12087" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1407">Задачи</a></li>
<li><a
href="/contest/1407/submit">Отослать</a></li>
<li><a
href="/contest/1407/my">Мои посылки</a></li>
<li><a
href="/contest/1407/status">Статус</a></li>
<li><a
href="/contest/1407/hacks">Взломы</a></li>
<li><a
href="/contest/1407/room/1">Комната</a></li>
<li><a
href="/contest/1407/standings">Положение</a></li>
<li><a
href="/contest/1407/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_0e3c14cda096d7a3e0963a198d54b53800b12726">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Большой Вова</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Александр — известный в узких кругах программист. Однажды он решил наконец-то выйти на улицу и активно провести время с мячом, но первым же ударом он оставил вмятину на новом Rolls-Royce богатого и влиятельного предпринимателя Большого Вовы. Бизнесмен недавно открыл интернет-магазин на популярной торговой площадке «Змей-Горыныч», и предлагает Саше устроиться на работу: если он продемонстрирует свои способности, решив задачу, то получит должность специалиста по безопасности, а в противном случае — должность курьера.</p><p>Вам даны $$$n$$$ целых положительных чисел $$$a_1, a_2, \dots, a_n$$$. Используя каждое из данных чисел <span class="tex-font-style-bf">ровно 1 раз</span>, Вы должны составить такую последовательность $$$b_1, b_2, \dots, b_n$$$, что последовательность $$$c_1, c_2, \dots, c_n$$$ <span class="tex-font-style-it">лексикографически максимальна</span>, где $$$c_i=GCD(b_1,\dots,b_i)$$$ — наибольший общий делитель первых $$$i$$$ чисел последовательности $$$b$$$.</p><p>Александр сильно испугался условия этой несложной задачи, и поэтому он просит у Вас помощи.</p><p>Последовательность $$$a$$$ лексикографически меньше последовательности $$$b$$$, если и только если выполняется один из следующих пунктов:</p><ul><li> $$$a$$$ — префикс $$$b$$$, но $$$a \ne b$$$;</li><li> в первой позиции, где $$$a$$$ и $$$b$$$ различны, в последовательности $$$a$$$ элемент меньше, чем соответствующий элемент в $$$b$$$.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. Первая строка содержит количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^3$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^3$$$) — длину последовательности $$$a$$$.</p><p>Вторая строка каждого набора данных содержит $$$n$$$ целых чисел $$$a_1,\dots,a_n$$$ ($$$1 \le a_i \le 10^3$$$) — последовательность $$$a$$$.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^3$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите ответ в отдельной строке — искомую последовательность $$$b$$$. Если существует несколько подходящих последовательностей, выведите любую из них. </p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
2
2 5
4
1 8 2 3
3
3 8 9
5
64 25 75 100 50
1
42
6
96 128 88 80 52 7
5
2 4 8 16 17
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5 2
8 2 1 3
9 3 8
100 50 25 75 64
42
128 96 80 88 52 7
17 2 4 8 16
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера есть всего две возможные перестановки $$$b$$$: $$$[2, 5]$$$ и $$$[5, 2]$$$. В первом случае $$$c=[2, 1]$$$, во втором $$$c=[5, 1]$$$.</p><p>В третьем наборе тестовых данных примера число $$$9$$$ должно идти первым в $$$b$$$, а $$$GCD(9, 3)=3$$$, $$$GCD(9, 8)=1$$$, поэтому вторым в $$$b$$$ идёт число $$$3$$$.</p><p>В седьмом наборе тестовых данных примера первые четыре числа попарно имеют общий делитель (степень двойки), однако ни одно из них не может идти первым в оптимальной перестановке $$$b$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:30</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab0538b475b7',t:'MTY5NjY2NjIzMC43MjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1300"] | ||
1407C | 1407 | C | ru | C. Шоколадный заяц | <div class="problem-statement"><div class="header"><div class="title">C. Шоколадный заяц</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Мы загадали перестановку $$$p$$$ длины $$$n$$$ из элементов от $$$1$$$ до $$$n$$$. Вам надо ее отгадать. Чтобы это сделать, вы можете сказать нам 2 различных индекса $$$i$$$ и $$$j$$$, и мы вам скажем, чему равняется $$$p_{i} \bmod p_{j}$$$ (остаток от деления $$$p_{i}$$$ на $$$p_{j}$$$).</p><p>У нас хватит терпения на то, чтобы ответить на $$$2 \cdot n$$$ запросов; вам нужно уложиться в это ограничение. Сможете ли вы это сделать?</p><p>Напомним, что перестановка длины $$$n$$$ — это массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$ в произвольном порядке. Например, $$$[2,3,1,5,4]$$$ — это перестановка, но $$$[1,2,2]$$$ — это не перестановка ($$$2$$$ встречается дважды в массиве), а $$$[1,3,4]$$$ также не является перестановкой ($$$n=3$$$, но в массиве встречается $$$4$$$).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^4$$$) — длину перестановки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начинается с чтения числа $$$n$$$.</p><p>Далее вы можете задать максимум $$$2 \cdot n$$$ запросов следующего вида: </p><ul> <li> «<span class="tex-font-style-tt">? x y</span>» ($$$1 \le x, y \le n, x \ne y$$$). </li></ul><p>После каждого запроса вам необходимо считать целое число $$$k$$$, равное $$$p_x \bmod p_y$$$.</p><p>Когда вы отгадаете перестановку, выведите в одной строку «<span class="tex-font-style-tt">! </span>» (без кавычек) и массив $$$p$$$, после чего завершите работу.</p><p>После вывода запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p>Ваша программа должна немедленно завершиться после прочтения ответа «<span class="tex-font-style-tt">-1</span>», вы получите вердикт <span class="tex-font-style-tt">Неправильный ответ</span>. В противном случае вы можете получить любой вердикт, так как программа продолжит чтение из закрытого потока.</p><p><span class="tex-font-style-bf">Формат взломов</span></p><p>В первой строке выведите $$$n$$$ ($$$1 \le n \le 10^4$$$). Во второй строке выведите перестановку из $$$n$$$ чисел $$$p_1, p_2, \ldots, p_n$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
1
2
1
0</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 2
? 3 2
? 1 3
? 2 1
! 1 3 2</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="1226f70f3af445942bec474819fe3ed5"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0a39b312e9c3ad03d3dc5d4d9e9333a019bb6c8e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='1226f70f3af445942bec474819fe3ed5'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1407%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='1226f70f3af445942bec474819fe3ed5'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1407">Codeforces Round 669 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='1226f70f3af445942bec474819fe3ed5'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1407/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1226f70f3af445942bec474819fe3ed5'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718473"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1226f70f3af445942bec474819fe3ed5'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718473"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82329" title="82329" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12558:12559" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82417" title="Разбор Codeforces Round #669" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12086:12087" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1407">Задачи</a></li>
<li><a
href="/contest/1407/submit">Отослать</a></li>
<li><a
href="/contest/1407/my">Мои посылки</a></li>
<li><a
href="/contest/1407/status">Статус</a></li>
<li><a
href="/contest/1407/hacks">Взломы</a></li>
<li><a
href="/contest/1407/room/1">Комната</a></li>
<li><a
href="/contest/1407/standings">Положение</a></li>
<li><a
href="/contest/1407/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_a664cb211219964a38d6dfd282d1ed4e4b07da32">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Шоколадный заяц</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Мы загадали перестановку $$$p$$$ длины $$$n$$$ из элементов от $$$1$$$ до $$$n$$$. Вам надо ее отгадать. Чтобы это сделать, вы можете сказать нам 2 различных индекса $$$i$$$ и $$$j$$$, и мы вам скажем, чему равняется $$$p_{i} \bmod p_{j}$$$ (остаток от деления $$$p_{i}$$$ на $$$p_{j}$$$).</p><p>У нас хватит терпения на то, чтобы ответить на $$$2 \cdot n$$$ запросов; вам нужно уложиться в это ограничение. Сможете ли вы это сделать?</p><p>Напомним, что перестановка длины $$$n$$$ — это массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$ в произвольном порядке. Например, $$$[2,3,1,5,4]$$$ — это перестановка, но $$$[1,2,2]$$$ — это не перестановка ($$$2$$$ встречается дважды в массиве), а $$$[1,3,4]$$$ также не является перестановкой ($$$n=3$$$, но в массиве встречается $$$4$$$).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка содержит целое число $$$n$$$ ($$$1 \le n \le 10^4$$$) — длину перестановки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Взаимодействие начинается с чтения числа $$$n$$$.</p><p>Далее вы можете задать максимум $$$2 \cdot n$$$ запросов следующего вида: </p><ul> <li> «<span class="tex-font-style-tt">? x y</span>» ($$$1 \le x, y \le n, x \ne y$$$). </li></ul><p>После каждого запроса вам необходимо считать целое число $$$k$$$, равное $$$p_x \bmod p_y$$$.</p><p>Когда вы отгадаете перестановку, выведите в одной строку «<span class="tex-font-style-tt">! </span>» (без кавычек) и массив $$$p$$$, после чего завершите работу.</p><p>После вывода запроса не забудьте вывести перевод строки и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p>Ваша программа должна немедленно завершиться после прочтения ответа «<span class="tex-font-style-tt">-1</span>», вы получите вердикт <span class="tex-font-style-tt">Неправильный ответ</span>. В противном случае вы можете получить любой вердикт, так как программа продолжит чтение из закрытого потока.</p><p><span class="tex-font-style-bf">Формат взломов</span></p><p>В первой строке выведите $$$n$$$ ($$$1 \le n \le 10^4$$$). Во второй строке выведите перестановку из $$$n$$$ чисел $$$p_1, p_2, \ldots, p_n$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
1
2
1
0</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 2
? 3 2
? 1 3
? 2 1
! 1 3 2</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:32</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab0dbf463a56',t:'MTY5NjY2NjIzMi4wNjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1600"] | ||
1407D | 1407 | D | ru | D. Дискретные Центробежные Прыжки | <div class="problem-statement"><div class="header"><div class="title">D. Дискретные Центробежные Прыжки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В Нью-Йорке есть $$$n$$$ красивых небоскребов, высота $$$i$$$-го равна $$$h_i$$$. Cегодня какие-то негодяи подожгли первые $$$n - 1$$$, и теперь единственное безопасное здание — небоскреб с индексом $$$n$$$.</p><p>Назовем прыжок с небоскреба $$$i$$$ на небоскреб $$$j$$$ ($$$i < j$$$) <span class="tex-font-style-bf">дискретным</span>, если все небоскребы между ними либо строго меньше по высоте, либо строго больше по высоте. Формально: прыжок дискретный, если $$$i < j$$$ и выполнено одно из условий: </p><ul> <li> $$$i + 1 = j$$$, </li><li> $$$\max(h_{i + 1}, \ldots, h_{j - 1}) < \min(h_i, h_j)$$$, </li><li> $$$\max(h_i, h_j) < \min(h_{i + 1}, \ldots, h_{j - 1})$$$. </li></ul><p>Вася сейчас стоит на первом небоскребе и хочет еще немножко пожить, поэтому хочет добраться до небоскреба с индексом $$$n$$$ за наименьшее число дискретных прыжков. Помогите ему посчитать это число.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — число небоскребов.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$) — высоты небоскребов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число $$$k$$$ — минимальное число дискретных прыжков. Можно показать, что ответ всегда существует.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
1 3 1 4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
4 2 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
100 1 100 1 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте Вася может посещать небоскребы в такой последовательности: $$$1 \rightarrow 2 \rightarrow 4 \rightarrow 5$$$.</p><p>Во втором и третьем тестах мы можем достичь последнего небоскреба за один прыжок.</p><p>Последовательность прыжков в четвертом тесте: $$$1 \rightarrow 3 \rightarrow 5$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="129ce746619b4468f345e317840b9246"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0a39b312e9c3ad03d3dc5d4d9e9333a019bb6c8e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='129ce746619b4468f345e317840b9246'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1407%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='129ce746619b4468f345e317840b9246'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1407">Codeforces Round 669 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='129ce746619b4468f345e317840b9246'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1407/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='129ce746619b4468f345e317840b9246'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718474"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='129ce746619b4468f345e317840b9246'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718474"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82329" title="82329" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12558:12559" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82417" title="Разбор Codeforces Round #669" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12086:12087" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1407">Задачи</a></li>
<li><a
href="/contest/1407/submit">Отослать</a></li>
<li><a
href="/contest/1407/my">Мои посылки</a></li>
<li><a
href="/contest/1407/status">Статус</a></li>
<li><a
href="/contest/1407/hacks">Взломы</a></li>
<li><a
href="/contest/1407/room/1">Комната</a></li>
<li><a
href="/contest/1407/standings">Положение</a></li>
<li><a
href="/contest/1407/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_d619c70a9732848dcbb43b71fc427cfc4aa78dcb">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Дискретные Центробежные Прыжки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В Нью-Йорке есть $$$n$$$ красивых небоскребов, высота $$$i$$$-го равна $$$h_i$$$. Cегодня какие-то негодяи подожгли первые $$$n - 1$$$, и теперь единственное безопасное здание — небоскреб с индексом $$$n$$$.</p><p>Назовем прыжок с небоскреба $$$i$$$ на небоскреб $$$j$$$ ($$$i < j$$$) <span class="tex-font-style-bf">дискретным</span>, если все небоскребы между ними либо строго меньше по высоте, либо строго больше по высоте. Формально: прыжок дискретный, если $$$i < j$$$ и выполнено одно из условий: </p><ul> <li> $$$i + 1 = j$$$, </li><li> $$$\max(h_{i + 1}, \ldots, h_{j - 1}) < \min(h_i, h_j)$$$, </li><li> $$$\max(h_i, h_j) < \min(h_{i + 1}, \ldots, h_{j - 1})$$$. </li></ul><p>Вася сейчас стоит на первом небоскребе и хочет еще немножко пожить, поэтому хочет добраться до небоскреба с индексом $$$n$$$ за наименьшее число дискретных прыжков. Помогите ему посчитать это число.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — число небоскребов.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$) — высоты небоскребов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число $$$k$$$ — минимальное число дискретных прыжков. Можно показать, что ответ всегда существует.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
1 3 1 4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
4 2 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
100 1 100 1 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте Вася может посещать небоскребы в такой последовательности: $$$1 \rightarrow 2 \rightarrow 4 \rightarrow 5$$$.</p><p>Во втором и третьем тестах мы можем достичь последнего небоскреба за один прыжок.</p><p>Последовательность прыжков в четвертом тесте: $$$1 \rightarrow 3 \rightarrow 5$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:33</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab16294c7b77',t:'MTY5NjY2NjIzMy40MzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"] | ||
1407E | 1407 | E | ru | E. Егор в республике Дагестан | <div class="problem-statement"><div class="header"><div class="title">E. Егор в республике Дагестан</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Егор — известный российский певец, рэпер, актёр и блогер, и наконец-то он решил дать концерт в солнечной республике Дагестан.</p><p>В республике есть $$$n$$$ городов, некоторые пары которых соединены $$$m$$$ односторонними дорогами без дополнительных условий. Иными словами, дорожная сеть Дагестана представляет собой <span class="tex-font-style-it">произвольный ориентированный граф</span>. Егор собирается прилететь в город $$$1$$$, проехать из него по дорогам вдоль некоторого пути до города $$$n$$$, дать в нём концерт и улететь.</p><p>Как и у любого артиста, у Егора есть множество недоброжелателей и слишком назойливых фанатов, поэтому ездить Егор и его команда будут только по безопасным дорогам. В Дагестане есть два типа дорог, чёрные и белые: по чёрным можно безопасно проехать только ночью, а по белым — только утром. Перед началом поездки менеджер Егора составляет расписание: он выбирает для каждого города его тип, чёрный или белый, и если команда посещает какой-то город, то уехать из него она сможет только по одной из дорог соответствующего типа. После определения расписания Егор выбирает любой маршрут из города $$$1$$$ в город $$$n$$$, причём из соображений безопасности этот путь должен быть кратчайшим. Менеджер Егора очень любит Дагестан и хочет задержаться здесь подольше, поэтому он попросил Вас составить такое расписание, чтобы из города $$$1$$$ в город $$$n$$$ не существовало пути вообще, или кратчайший путь был максимально возможной длины.</p><p><span class="tex-font-style-it">Путём</span> является один город или последовательность дорог такая что начало каждой дороги в последовательности (кроме первой) является концом предыдущей. Егор может перемещаться вдоль пути, только если все его дороги безопасны.</p><p>Длиной пути называется количество дорог в нём. Кратчайшим путём называется путь минимальной длины.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит числа $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 500000$$$, $$$0 \leq m \leq 500000$$$) — количество городов и дорог, соответственно.</p><p>В $$$i$$$-й из следующих $$$m$$$ строк даны три целых числа — $$$u_i$$$, $$$v_i$$$ и $$$t_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$t_i \in \{0, 1\}$$$) — номера городов, соединяемых дорогой, и тип дороги ($$$0$$$ — ночная, $$$1$$$ — утренняя).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите длину искомого пути (или $$$-1$$$, если можно подобрать расписание так, чтобы пути из $$$1$$$ в $$$n$$$ не существовало).</p><p>Во второй строке выведите искомое расписание — строку из $$$n$$$ целых чисел, где $$$i$$$-е число равно $$$0$$$, если из $$$i$$$-го города можно уехать только по ночным дорогам, и $$$1$$$, если только по утренним.</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 4
1 2 0
1 3 1
2 3 0
2 3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
011</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 8
1 1 0
1 3 0
1 3 1
3 2 0
2 1 0
3 4 1
2 4 0
2 4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
1101</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 10
1 2 0
1 3 1
1 4 0
2 3 0
2 3 1
2 5 0
3 4 0
3 4 1
4 2 1
4 5 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
11111</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, если покрасить город $$$1$$$ в белый цвет, кратчайший путь будет состоять из одной дороги, $$$1 \rightarrow 3$$$. Иначе, независимо от цветов остальных городов кратчайший путь будет $$$1 \rightarrow 2 \rightarrow 3$$$.</p><p>Во втором примере город $$$3$$$ следует покрасить в чёрный цвет, а из города $$$2$$$ существуют дороги обоих цветов в город $$$4$$$. Обратите внимание: может существовать дорога, соединяющая город с самим собой.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="549786f79572fcf80ceef8fd8834d281"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="0a39b312e9c3ad03d3dc5d4d9e9333a019bb6c8e"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='549786f79572fcf80ceef8fd8834d281'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1407%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='549786f79572fcf80ceef8fd8834d281'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1407">Codeforces Round 669 (Div. 2)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='549786f79572fcf80ceef8fd8834d281'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1407/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах">
кратчайшие пути
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='549786f79572fcf80ceef8fd8834d281'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="718475"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='549786f79572fcf80ceef8fd8834d281'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="718475"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82329" title="82329" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12558:12559" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82417" title="Разбор Codeforces Round #669" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12086:12087" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1407">Задачи</a></li>
<li><a
href="/contest/1407/submit">Отослать</a></li>
<li><a
href="/contest/1407/my">Мои посылки</a></li>
<li><a
href="/contest/1407/status">Статус</a></li>
<li><a
href="/contest/1407/hacks">Взломы</a></li>
<li><a
href="/contest/1407/room/1">Комната</a></li>
<li><a
href="/contest/1407/standings">Положение</a></li>
<li><a
href="/contest/1407/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_c8cdb4d0be07da408ca970c968a749be8031decd">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Егор в республике Дагестан</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Егор — известный российский певец, рэпер, актёр и блогер, и наконец-то он решил дать концерт в солнечной республике Дагестан.</p><p>В республике есть $$$n$$$ городов, некоторые пары которых соединены $$$m$$$ односторонними дорогами без дополнительных условий. Иными словами, дорожная сеть Дагестана представляет собой <span class="tex-font-style-it">произвольный ориентированный граф</span>. Егор собирается прилететь в город $$$1$$$, проехать из него по дорогам вдоль некоторого пути до города $$$n$$$, дать в нём концерт и улететь.</p><p>Как и у любого артиста, у Егора есть множество недоброжелателей и слишком назойливых фанатов, поэтому ездить Егор и его команда будут только по безопасным дорогам. В Дагестане есть два типа дорог, чёрные и белые: по чёрным можно безопасно проехать только ночью, а по белым — только утром. Перед началом поездки менеджер Егора составляет расписание: он выбирает для каждого города его тип, чёрный или белый, и если команда посещает какой-то город, то уехать из него она сможет только по одной из дорог соответствующего типа. После определения расписания Егор выбирает любой маршрут из города $$$1$$$ в город $$$n$$$, причём из соображений безопасности этот путь должен быть кратчайшим. Менеджер Егора очень любит Дагестан и хочет задержаться здесь подольше, поэтому он попросил Вас составить такое расписание, чтобы из города $$$1$$$ в город $$$n$$$ не существовало пути вообще, или кратчайший путь был максимально возможной длины.</p><p><span class="tex-font-style-it">Путём</span> является один город или последовательность дорог такая что начало каждой дороги в последовательности (кроме первой) является концом предыдущей. Егор может перемещаться вдоль пути, только если все его дороги безопасны.</p><p>Длиной пути называется количество дорог в нём. Кратчайшим путём называется путь минимальной длины.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит числа $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 500000$$$, $$$0 \leq m \leq 500000$$$) — количество городов и дорог, соответственно.</p><p>В $$$i$$$-й из следующих $$$m$$$ строк даны три целых числа — $$$u_i$$$, $$$v_i$$$ и $$$t_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$t_i \in \{0, 1\}$$$) — номера городов, соединяемых дорогой, и тип дороги ($$$0$$$ — ночная, $$$1$$$ — утренняя).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите длину искомого пути (или $$$-1$$$, если можно подобрать расписание так, чтобы пути из $$$1$$$ в $$$n$$$ не существовало).</p><p>Во второй строке выведите искомое расписание — строку из $$$n$$$ целых чисел, где $$$i$$$-е число равно $$$0$$$, если из $$$i$$$-го города можно уехать только по ночным дорогам, и $$$1$$$, если только по утренним.</p><p>Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 4
1 2 0
1 3 1
2 3 0
2 3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
011</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 8
1 1 0
1 3 0
1 3 1
3 2 0
2 1 0
3 4 1
2 4 0
2 4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
1101</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 10
1 2 0
1 3 1
1 4 0
2 3 0
2 3 1
2 5 0
3 4 0
3 4 1
4 2 1
4 5 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
11111</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, если покрасить город $$$1$$$ в белый цвет, кратчайший путь будет состоять из одной дороги, $$$1 \rightarrow 3$$$. Иначе, независимо от цветов остальных городов кратчайший путь будет $$$1 \rightarrow 2 \rightarrow 3$$$.</p><p>Во втором примере город $$$3$$$ следует покрасить в чёрный цвет, а из города $$$2$$$ существуют дороги обоих цветов в город $$$4$$$. Обратите внимание: может существовать дорога, соединяющая город с самим собой.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:34</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab1ebd5f16bb',t:'MTY5NjY2NjIzNC43ODcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2500"] | ||
1408A | 1408 | A | ru | A. Покраска круга | <div class="problem-statement"><div class="header"><div class="title">A. Покраска круга</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны три последовательности: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.</p><p>Для всех $$$i$$$ выполняется $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.</p><p>Найдите последовательность $$$p_1, p_2, \ldots, p_n$$$, которая удовлетворяет следующим условиям:</p><ul><li> $$$p_i \in \{a_i, b_i, c_i\}$$$;</li><li> $$$p_i \neq p_{(i \mod n) + 1}$$$.</li></ul><p>Другими словами, для всех позиций вы должны выбрать одно из трех возможных значений так, что никакие две соседние позиции не имеют одинаковое значение (мы рассматриваем позиции $$$i,i+1$$$ как соседние для всех $$$i<n$$$, и также позиции $$$1$$$ и $$$n$$$ являются соседними).</p><p>Можно доказать, что в данных ограничениях решение всегда существует. Вам не нужно ничего минимизировать/максимизировать, вам нужно просто найти любую подходящую последовательность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$): количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$3 \leq n \leq 100$$$): количество элементов в данных последовательностях.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$).</p><p>В третьей строке находится $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$).</p><p>В четвертой строке находится $$$n$$$ целых чисел $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$).</p><p>Гарантируется, что $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ для всех $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$n$$$ целых чисел $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$).</p><p>Если есть несколько возможных решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
3
1 1 1
2 2 2
3 3 3
4
1 2 1 2
2 1 2 1
3 4 3 4
7
1 3 3 1 1 1 1
2 4 4 3 2 2 4
4 2 2 2 4 4 2
3
1 2 1
2 3 3
3 1 2
10
1 1 1 2 2 2 3 3 3 1
2 2 2 3 3 3 1 1 1 2
3 3 3 1 1 1 2 2 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 2 3
1 2 1 2
1 3 4 3 2 4 2
1 3 2
1 2 3 1 2 3 1 2 3 2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$p = [1, 2, 3]$$$.</p><p>Это правильный ответ, потому что:</p><ul> <li> $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$; </li><li> $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$. </li></ul><p>Все возможные правильные ответы на этот набор входных данных: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.</p><p>Во втором наборе входных данных $$$p = [1, 2, 1, 2]$$$.</p><p>В этой последовательности $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Также можно заметить, что никакие два соседние элемента этой последовательности не равны.</p><p>В третьем наборе входных данных $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.</p><p>В этой последовательности $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Также можно заметить, что никакие два соседние элемента этой последовательности не равны.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="ae932eb2442d37f8cf76cebefb3f58a6"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='ae932eb2442d37f8cf76cebefb3f58a6'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='ae932eb2442d37f8cf76cebefb3f58a6'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='ae932eb2442d37f8cf76cebefb3f58a6'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ae932eb2442d37f8cf76cebefb3f58a6'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743624"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ae932eb2442d37f8cf76cebefb3f58a6'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743624"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_f20eb2e71b614953ab4a9621f6ea917ee9c86be3">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Покраска круга</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны три последовательности: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.</p><p>Для всех $$$i$$$ выполняется $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.</p><p>Найдите последовательность $$$p_1, p_2, \ldots, p_n$$$, которая удовлетворяет следующим условиям:</p><ul><li> $$$p_i \in \{a_i, b_i, c_i\}$$$;</li><li> $$$p_i \neq p_{(i \mod n) + 1}$$$.</li></ul><p>Другими словами, для всех позиций вы должны выбрать одно из трех возможных значений так, что никакие две соседние позиции не имеют одинаковое значение (мы рассматриваем позиции $$$i,i+1$$$ как соседние для всех $$$i<n$$$, и также позиции $$$1$$$ и $$$n$$$ являются соседними).</p><p>Можно доказать, что в данных ограничениях решение всегда существует. Вам не нужно ничего минимизировать/максимизировать, вам нужно просто найти любую подходящую последовательность.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$): количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$3 \leq n \leq 100$$$): количество элементов в данных последовательностях.</p><p>Во второй строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$).</p><p>В третьей строке находится $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$).</p><p>В четвертой строке находится $$$n$$$ целых чисел $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$).</p><p>Гарантируется, что $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ для всех $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$n$$$ целых чисел $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$).</p><p>Если есть несколько возможных решений, выведите любое.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
3
1 1 1
2 2 2
3 3 3
4
1 2 1 2
2 1 2 1
3 4 3 4
7
1 3 3 1 1 1 1
2 4 4 3 2 2 4
4 2 2 2 4 4 2
3
1 2 1
2 3 3
3 1 2
10
1 1 1 2 2 2 3 3 3 1
2 2 2 3 3 3 1 1 1 2
3 3 3 1 1 1 2 2 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 2 3
1 2 1 2
1 3 4 3 2 4 2
1 3 2
1 2 3 1 2 3 1 2 3 2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$p = [1, 2, 3]$$$.</p><p>Это правильный ответ, потому что:</p><ul> <li> $$$p_1 = 1 = a_1$$$, $$$p_2 = 2 = b_2$$$, $$$p_3 = 3 = c_3$$$; </li><li> $$$p_1 \neq p_2 $$$, $$$p_2 \neq p_3 $$$, $$$p_3 \neq p_1$$$. </li></ul><p>Все возможные правильные ответы на этот набор входных данных: $$$[1, 2, 3]$$$, $$$[1, 3, 2]$$$, $$$[2, 1, 3]$$$, $$$[2, 3, 1]$$$, $$$[3, 1, 2]$$$, $$$[3, 2, 1]$$$.</p><p>Во втором наборе входных данных $$$p = [1, 2, 1, 2]$$$.</p><p>В этой последовательности $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = a_3$$$, $$$p_4 = a_4$$$. Также можно заметить, что никакие два соседние элемента этой последовательности не равны.</p><p>В третьем наборе входных данных $$$p = [1, 3, 4, 3, 2, 4, 2]$$$.</p><p>В этой последовательности $$$p_1 = a_1$$$, $$$p_2 = a_2$$$, $$$p_3 = b_3$$$, $$$p_4 = b_4$$$, $$$p_5 = b_5$$$, $$$p_6 = c_6$$$, $$$p_7 = c_7$$$. Также можно заметить, что никакие два соседние элемента этой последовательности не равны.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:36</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab27189c00bc',t:'MTY5NjY2NjIzNi4zODUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*800"] | ||
1408B | 1408 | B | ru | B. Суммы массивов | <div class="problem-statement"><div class="header"><div class="title">B. Суммы массивов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан <span class="tex-font-style-bf">неубывающий</span> массив, состоящий из <span class="tex-font-style-bf">неотрицательных</span> целых чисел $$$a_1, a_2, \ldots, a_n$$$. Также вам дано положительное целое число $$$k$$$.</p><p>Вы хотите найти $$$m$$$ <span class="tex-font-style-bf">неубывающих</span> массивов, состоящих из <span class="tex-font-style-bf">неотрицательных</span> целых чисел $$$b_1, b_2, \ldots, b_m$$$, таких что:</p><ul> <li> размер $$$b_i$$$ равен $$$n$$$ для всех $$$1 \leq i \leq m$$$; </li><li> для всех $$$1 \leq j \leq n$$$, $$$a_j = b_{1, j} + b_{2, j} + \ldots + b_{m, j}$$$. Другими словами, массив $$$a$$$ равен поэлементной сумме массивов $$$b_i$$$; </li><li> количество различных элементов массива $$$b_i$$$ не превосходит $$$k$$$ для всех $$$1 \leq i \leq m$$$. </li></ul><p>Найдите минимальное возможное значение $$$m$$$ или сообщите, что ни одного возможного значения $$$m$$$ не существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$): количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находятся два целых числа $$$n$$$, $$$k$$$ ($$$1 \leq n \leq 100$$$, $$$1 \leq k \leq n$$$).</p><p>Во второй строке находятся $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 100$$$, $$$a_n > 0$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число: минимальное возможное значение $$$m$$$. Если таких $$$m$$$ не существует, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
4 1
0 0 0 1
3 1
3 3 3
11 3
0 1 2 2 3 3 3 4 4 4 4
5 3
1 2 3 4 5
9 4
2 2 3 5 7 11 13 13 17
10 7
0 1 1 2 3 3 4 5 5 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
1
2
2
2
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных не существует ни одного возможного значения $$$m$$$, потому что все элементы всех массивов должны будут быть равными $$$0$$$. Но в этом случае невозможно получить $$$a_4 = 1$$$ как сумму нескольких нулей.</p><p>Во втором наборе входных данных мы можем взять $$$b_1 = [3, 3, 3]$$$. $$$1$$$ — это минимальное возможное значение $$$m$$$.</p><p>В третьем наборе входных данных мы можем взять $$$b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]$$$ и $$$b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]$$$. Легко заметить, что $$$a_i = b_{1, i} + b_{2, i}$$$ для всех $$$i$$$ и количество различных элементов в каждом из массивов $$$b_1$$$ и $$$b_2$$$ равно $$$3$$$ (что не превосходит $$$3$$$). Можно доказать, что $$$2$$$ — это минимальное возможное значение $$$m$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="308bafe194d1f5c29b023005e58c8985"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='308bafe194d1f5c29b023005e58c8985'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='308bafe194d1f5c29b023005e58c8985'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='308bafe194d1f5c29b023005e58c8985'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='308bafe194d1f5c29b023005e58c8985'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743625"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='308bafe194d1f5c29b023005e58c8985'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743625"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_ba1a85be3bc9aa80dbb53b8112ee11dca53da233">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Суммы массивов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан <span class="tex-font-style-bf">неубывающий</span> массив, состоящий из <span class="tex-font-style-bf">неотрицательных</span> целых чисел $$$a_1, a_2, \ldots, a_n$$$. Также вам дано положительное целое число $$$k$$$.</p><p>Вы хотите найти $$$m$$$ <span class="tex-font-style-bf">неубывающих</span> массивов, состоящих из <span class="tex-font-style-bf">неотрицательных</span> целых чисел $$$b_1, b_2, \ldots, b_m$$$, таких что:</p><ul> <li> размер $$$b_i$$$ равен $$$n$$$ для всех $$$1 \leq i \leq m$$$; </li><li> для всех $$$1 \leq j \leq n$$$, $$$a_j = b_{1, j} + b_{2, j} + \ldots + b_{m, j}$$$. Другими словами, массив $$$a$$$ равен поэлементной сумме массивов $$$b_i$$$; </li><li> количество различных элементов массива $$$b_i$$$ не превосходит $$$k$$$ для всех $$$1 \leq i \leq m$$$. </li></ul><p>Найдите минимальное возможное значение $$$m$$$ или сообщите, что ни одного возможного значения $$$m$$$ не существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$): количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находятся два целых числа $$$n$$$, $$$k$$$ ($$$1 \leq n \leq 100$$$, $$$1 \leq k \leq n$$$).</p><p>Во второй строке находятся $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_1 \leq a_2 \leq \ldots \leq a_n \leq 100$$$, $$$a_n > 0$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число: минимальное возможное значение $$$m$$$. Если таких $$$m$$$ не существует, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
4 1
0 0 0 1
3 1
3 3 3
11 3
0 1 2 2 3 3 3 4 4 4 4
5 3
1 2 3 4 5
9 4
2 2 3 5 7 11 13 13 17
10 7
0 1 1 2 3 3 4 5 5 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
1
2
2
2
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных не существует ни одного возможного значения $$$m$$$, потому что все элементы всех массивов должны будут быть равными $$$0$$$. Но в этом случае невозможно получить $$$a_4 = 1$$$ как сумму нескольких нулей.</p><p>Во втором наборе входных данных мы можем взять $$$b_1 = [3, 3, 3]$$$. $$$1$$$ — это минимальное возможное значение $$$m$$$.</p><p>В третьем наборе входных данных мы можем взять $$$b_1 = [0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]$$$ и $$$b_2 = [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]$$$. Легко заметить, что $$$a_i = b_{1, i} + b_{2, i}$$$ для всех $$$i$$$ и количество различных элементов в каждом из массивов $$$b_1$$$ и $$$b_2$$$ равно $$$3$$$ (что не превосходит $$$3$$$). Можно доказать, что $$$2$$$ — это минимальное возможное значение $$$m$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:37</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab312e4b03d1',t:'MTY5NjY2NjIzNy43NzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1400"] | ||
1408C | 1408 | C | ru | C. Дискретное ускорение | <div class="problem-statement"><div class="header"><div class="title">C. Дискретное ускорение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим дорогу длиной $$$l$$$ метров. Начало дороги имеет координату $$$0$$$, конец дороги имеет координату $$$l$$$.</p><p>Есть две машины, первая стоит в начале дороги, вторая стоит в конце дороги. Они начинают ехать одновременно. Первая машина будет ехать от начала дороги к концу, вторая машина будет ехать от конца дороги к началу.</p><p>Изначально они будут ехать со скоростью $$$1$$$ метр в секунду. Есть $$$n$$$ флажков, расположенных в <span class="tex-font-style-bf">различных</span> координатах $$$a_1, a_2, \ldots, a_n$$$. Каждый раз, когда любая из двух машин проезжает мимо флажка, скорость этой машины увеличивается на $$$1$$$ метр в секунду.</p><p>Найдите, через какое время машины встретятся (их координаты совпадут).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$): количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находятся два целых числа $$$n$$$, $$$l$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq l \leq 10^9$$$): количество флажков и длина дороги.</p><p>Во второй строке находятся $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ в <span class="tex-font-style-bf">возрастающем</span> порядке ($$$1 \leq a_1 < a_2 < \ldots < a_n < l$$$).</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное вещественное число: время, через которое машины встретятся.</p><p>Ваш ответ будет признан правильным, если его абсолютная или относительная ошибка не превосходит $$$10^{-6}$$$. Более формально, если ваш ответ $$$a$$$ и ответ жюри $$$b$$$, ваш ответ будет признан правильным, если $$$\frac{|a-b|}{\max{(1, b)}} \leq 10^{-6}$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2 10
1 9
1 10
1
5 7
1 2 3 4 6
2 1000000000
413470354 982876160
9 478
1 10 25 33 239 445 453 468 477
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3.000000000000000
3.666666666666667
2.047619047619048
329737645.750000000000000
53.700000000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных машины встретятся в координате $$$5$$$.</p><p>Первая машина будет в координате $$$1$$$ через $$$1$$$ секунду, и после этого ее скорость увеличится на $$$1$$$ и станет равной $$$2$$$-м метрам в секунду. Через $$$2$$$ секунды машина окажется в координате $$$5$$$. Итак, первая машина будет в координате $$$5$$$ через $$$3$$$ секунды.</p><p>Вторая машина будет в координате $$$9$$$ через $$$1$$$ секунду, и после этого ее скорость увеличится на $$$1$$$ и станет равной $$$2$$$-м метрам в секунду. Через $$$2$$$ секунды машина окажется в координате $$$5$$$. Итак, вторая машина будет в координате $$$5$$$ через $$$3$$$ секунды.</p><p>Во втором наборе входных данных через $$$1$$$ секунду первая машина будет в координате $$$1$$$ и будет иметь скорость, равную $$$2$$$-м метрам в секунду; вторая машина будет в координате $$$9$$$ и будет иметь скорость $$$1$$$ метр в секунду. Поэтому после этого они встретятся через $$$\frac{9-1}{2+1} = \frac{8}{3}$$$ секунд. Итак, ответ равен $$$1 + \frac{8}{3} = \frac{11}{3}$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="b5fcd2c2407958daf66702645499d292"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='b5fcd2c2407958daf66702645499d292'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='b5fcd2c2407958daf66702645499d292'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='b5fcd2c2407958daf66702645499d292'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b5fcd2c2407958daf66702645499d292'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743626"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b5fcd2c2407958daf66702645499d292'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743626"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_f91ca8b48eb0b0305c778151e90558d603d45cea">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Дискретное ускорение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим дорогу длиной $$$l$$$ метров. Начало дороги имеет координату $$$0$$$, конец дороги имеет координату $$$l$$$.</p><p>Есть две машины, первая стоит в начале дороги, вторая стоит в конце дороги. Они начинают ехать одновременно. Первая машина будет ехать от начала дороги к концу, вторая машина будет ехать от конца дороги к началу.</p><p>Изначально они будут ехать со скоростью $$$1$$$ метр в секунду. Есть $$$n$$$ флажков, расположенных в <span class="tex-font-style-bf">различных</span> координатах $$$a_1, a_2, \ldots, a_n$$$. Каждый раз, когда любая из двух машин проезжает мимо флажка, скорость этой машины увеличивается на $$$1$$$ метр в секунду.</p><p>Найдите, через какое время машины встретятся (их координаты совпадут).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 10^4$$$): количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находятся два целых числа $$$n$$$, $$$l$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq l \leq 10^9$$$): количество флажков и длина дороги.</p><p>Во второй строке находятся $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ в <span class="tex-font-style-bf">возрастающем</span> порядке ($$$1 \leq a_1 < a_2 < \ldots < a_n < l$$$).</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное вещественное число: время, через которое машины встретятся.</p><p>Ваш ответ будет признан правильным, если его абсолютная или относительная ошибка не превосходит $$$10^{-6}$$$. Более формально, если ваш ответ $$$a$$$ и ответ жюри $$$b$$$, ваш ответ будет признан правильным, если $$$\frac{|a-b|}{\max{(1, b)}} \leq 10^{-6}$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2 10
1 9
1 10
1
5 7
1 2 3 4 6
2 1000000000
413470354 982876160
9 478
1 10 25 33 239 445 453 468 477
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3.000000000000000
3.666666666666667
2.047619047619048
329737645.750000000000000
53.700000000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных машины встретятся в координате $$$5$$$.</p><p>Первая машина будет в координате $$$1$$$ через $$$1$$$ секунду, и после этого ее скорость увеличится на $$$1$$$ и станет равной $$$2$$$-м метрам в секунду. Через $$$2$$$ секунды машина окажется в координате $$$5$$$. Итак, первая машина будет в координате $$$5$$$ через $$$3$$$ секунды.</p><p>Вторая машина будет в координате $$$9$$$ через $$$1$$$ секунду, и после этого ее скорость увеличится на $$$1$$$ и станет равной $$$2$$$-м метрам в секунду. Через $$$2$$$ секунды машина окажется в координате $$$5$$$. Итак, вторая машина будет в координате $$$5$$$ через $$$3$$$ секунды.</p><p>Во втором наборе входных данных через $$$1$$$ секунду первая машина будет в координате $$$1$$$ и будет иметь скорость, равную $$$2$$$-м метрам в секунду; вторая машина будет в координате $$$9$$$ и будет иметь скорость $$$1$$$ метр в секунду. Поэтому после этого они встретятся через $$$\frac{9-1}{2+1} = \frac{8}{3}$$$ секунд. Итак, ответ равен $$$1 + \frac{8}{3} = \frac{11}{3}$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:39</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab39cd7b009d',t:'MTY5NjY2NjIzOS4xNzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1500"] | ||
1408D | 1408 | D | ru | D. Прожекторы | <div class="problem-statement"><div class="header"><div class="title">D. Прожекторы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть $$$n$$$ грабителей в координатах $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, ..., $$$(a_n, b_n)$$$ и $$$m$$$ прожекторов в координатах $$$(c_1, d_1)$$$, $$$(c_2, d_2)$$$, ..., $$$(c_m, d_m)$$$.</p><p>За один ход вы можете подвинуть всех грабителей направо (увеличить $$$a_i$$$ всех грабителей на единицу) или подвинуть всех грабителей вверх (увеличить $$$b_i$$$ всех грабителей на единицу). Обратите внимание, что вы должны либо увеличить <span class="tex-font-style-bf">все</span> $$$a_i$$$, либо <span class="tex-font-style-bf">все</span> $$$b_i$$$, вы <span class="tex-font-style-bf">не можете</span> увеличить $$$a_i$$$ некоторых грабителей и $$$b_i$$$ некоторых других грабителей за одну операцию.</p><p>Прожектор $$$j$$$ освещает грабителя $$$i$$$, если $$$a_i \leq c_j$$$ и $$$b_i \leq d_j$$$.</p><p>Конфигурация грабителей называется <span class="tex-font-style-it">безопасной</span>, если ни один прожектор не освещает ни одного грабителя (то есть нет такой пары $$$i,j$$$, что прожектор $$$j$$$ освещает грабителя $$$i$$$).</p><p>Какое минимальное количество ходов нужно сделать, чтобы грабители оказались в безопасной конфигурации?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 2000$$$): количество грабителей и количество прожекторов.</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$a_i$$$, $$$b_i$$$ ($$$0 \leq a_i, b_i \leq 10^6$$$), координаты грабителей.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$c_i$$$, $$$d_i$$$ ($$$0 \leq c_i, d_i \leq 10^6$$$), координаты прожекторов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число: минимальное количество ходов, необходимое, чтобы грабители оказались в безопасной конфигурации.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1 1
0 0
2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 3
1 6
6 1
10 1
1 10
7 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 2
0 0
0 0
0 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 3
0 8
3 8
2 7
0 10
5 5
7 0
3 5
6 6
3 11
11 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте вы можете подвинуть всех грабителей направо три раза. После этого будет один грабитель в координатах $$$(3, 0)$$$.</p><p>Конфигурация грабителей будет безопасной, потому что единственный прожектор не освещает грабителя, так как он в координатах $$$(2, 3)$$$, а $$$3 > 2$$$.</p><p>Во втором тесте вы можете подвинуть всех грабителей направо два раза и вверх два раза. После этого грабители будут в координатах $$$(3, 8)$$$, $$$(8, 3)$$$.</p><p>Легко увидеть, что такая конфигурация безопасна.</p><p>Можно доказать, что невозможно получить безопасную конфигурацию, используя не больше, чем $$$3$$$ хода.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="01a7cd649c1d67984040f3f33efb6e54"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='01a7cd649c1d67984040f3f33efb6e54'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='01a7cd649c1d67984040f3f33efb6e54'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='01a7cd649c1d67984040f3f33efb6e54'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2000
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='01a7cd649c1d67984040f3f33efb6e54'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743627"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='01a7cd649c1d67984040f3f33efb6e54'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743627"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_118de1a3ae072f74fb8f34f54d6b6e48a3370f1f">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Прожекторы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть $$$n$$$ грабителей в координатах $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, ..., $$$(a_n, b_n)$$$ и $$$m$$$ прожекторов в координатах $$$(c_1, d_1)$$$, $$$(c_2, d_2)$$$, ..., $$$(c_m, d_m)$$$.</p><p>За один ход вы можете подвинуть всех грабителей направо (увеличить $$$a_i$$$ всех грабителей на единицу) или подвинуть всех грабителей вверх (увеличить $$$b_i$$$ всех грабителей на единицу). Обратите внимание, что вы должны либо увеличить <span class="tex-font-style-bf">все</span> $$$a_i$$$, либо <span class="tex-font-style-bf">все</span> $$$b_i$$$, вы <span class="tex-font-style-bf">не можете</span> увеличить $$$a_i$$$ некоторых грабителей и $$$b_i$$$ некоторых других грабителей за одну операцию.</p><p>Прожектор $$$j$$$ освещает грабителя $$$i$$$, если $$$a_i \leq c_j$$$ и $$$b_i \leq d_j$$$.</p><p>Конфигурация грабителей называется <span class="tex-font-style-it">безопасной</span>, если ни один прожектор не освещает ни одного грабителя (то есть нет такой пары $$$i,j$$$, что прожектор $$$j$$$ освещает грабителя $$$i$$$).</p><p>Какое минимальное количество ходов нужно сделать, чтобы грабители оказались в безопасной конфигурации?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 2000$$$): количество грабителей и количество прожекторов.</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$a_i$$$, $$$b_i$$$ ($$$0 \leq a_i, b_i \leq 10^6$$$), координаты грабителей.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$c_i$$$, $$$d_i$$$ ($$$0 \leq c_i, d_i \leq 10^6$$$), координаты прожекторов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число: минимальное количество ходов, необходимое, чтобы грабители оказались в безопасной конфигурации.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1 1
0 0
2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 3
1 6
6 1
10 1
1 10
7 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 2
0 0
0 0
0 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 3
0 8
3 8
2 7
0 10
5 5
7 0
3 5
6 6
3 11
11 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте вы можете подвинуть всех грабителей направо три раза. После этого будет один грабитель в координатах $$$(3, 0)$$$.</p><p>Конфигурация грабителей будет безопасной, потому что единственный прожектор не освещает грабителя, так как он в координатах $$$(2, 3)$$$, а $$$3 > 2$$$.</p><p>Во втором тесте вы можете подвинуть всех грабителей направо два раза и вверх два раза. После этого грабители будут в координатах $$$(3, 8)$$$, $$$(8, 3)$$$.</p><p>Легко увидеть, что такая конфигурация безопасна.</p><p>Можно доказать, что невозможно получить безопасную конфигурацию, используя не больше, чем $$$3$$$ хода.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:40</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab42986013b4',t:'MTY5NjY2NjI0MC41NjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2000"] | ||
1408E | 1408 | E | ru | E. Избегайте разноцветных циклов | <div class="problem-statement"><div class="header"><div class="title">E. Избегайте разноцветных циклов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано $$$m$$$ множеств $$$A_1, A_2, \ldots, A_m$$$, состоящих из целых чисел; элементы этих множеств — целые числа от $$$1$$$ до $$$n$$$ включительно.</p><p>Есть два массива положительных целых чисел $$$a_1, a_2, \ldots, a_m$$$ и $$$b_1, b_2, \ldots, b_n$$$. </p><p>За одну операцию вы можете удалить элемент $$$j$$$ из множества $$$A_i$$$ и заплатить за это $$$a_i + b_j$$$ монет.</p><p>Вы можете сделать несколько (возможно, ноль) операций (после этого некоторые множества могут стать пустыми).</p><p>После этого вы построите неориентированный граф, где каждое ребро будет иметь цвет. Граф будет иметь $$$n$$$ вершин. Для каждого множества $$$A_i$$$ вы добавите ребро $$$(x, y)$$$ цвета $$$i$$$ для всех $$$x, y \in A_i$$$ и $$$x < y$$$. Некоторые пары вершин могут быть соединены больше чем одним ребром, но такие ребра будут иметь разные цвета.</p><p>Мы называем цикл $$$i_1 \to e_1 \to i_2 \to e_2 \to \ldots \to i_k \to e_k \to i_1$$$ ($$$e_j$$$ это какое-то ребро, соединяющее вершины $$$i_j$$$ и $$$i_{j+1}$$$ этого графа) <span class="tex-font-style-it">разноцветным</span>, если цвета всех ребер этого цикла различны.</p><p>Найдите минимальное количество монет, которое нужно заплатить, чтобы получить граф без разноцветных циклов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$m$$$ и $$$n$$$ ($$$1 \leq m, n \leq 10^5$$$), количество множеств и количество вершин в графе.</p><p>Во второй строке находятся $$$m$$$ целых чисел $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \leq a_i \leq 10^9$$$).</p><p>В третьей строке находятся $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$).</p><p>В каждой из следующих $$$m$$$ строк находится описание множества. В $$$i$$$-й строке первое число $$$s_i$$$ ($$$1 \leq s_i \leq n$$$) равно размеру $$$A_i$$$. Затем следуют $$$s_i$$$ целых чисел — элементы множества $$$A_i$$$. Эти целые числа различны и находятся в пределах от $$$1$$$ до $$$n$$$ включительно.</p><p>Гарантируется, что сумма $$$s_i$$$ для всех $$$1 \leq i \leq m$$$ не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальное количество монет, которое нужно заплатить, чтобы получить граф без разноцветных циклов.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
11
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
66
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте можно сделать следующие операции.</p><ul> <li> Удалить элемент $$$1$$$ из множества $$$1$$$. Вы должны заплатить $$$a_1 + b_1 = 5$$$ монет за эту операцию. </li><li> Удалить элемент $$$1$$$ из множества $$$2$$$. Вы должны заплатить $$$a_2 + b_1 = 6$$$ монет за эту операцию. </li></ul><p>Суммарно вы заплатите $$$11$$$ монет. После этих операций первое и второй множества будут равны $$$\{2\}$$$, а третье множество будет равно $$$\{1, 2\}$$$. Поэтому построенный граф будет содержать одно ребро $$$(1, 2)$$$ цвета $$$3$$$.</p><p>Во втором тесте можно сделать следующие операции.</p><ul> <li> Удалить элемент $$$1$$$ из множества $$$1$$$. Вы должны заплатить $$$a_1 + b_1 = 11$$$ монет за эту операцию. </li><li> Удалить элемент $$$4$$$ из множества $$$2$$$. Вы должны заплатить $$$a_2 + b_4 = 13$$$ монет за эту операцию. </li><li> Удалить элемент $$$7$$$ из множества $$$3$$$. Вы должны заплатить $$$a_3 + b_7 = 13$$$ монет за эту операцию. </li><li> Удалить элемент $$$4$$$ из множества $$$4$$$. Вы должны заплатить $$$a_4 + b_4 = 16$$$ монет за эту операцию. </li><li> Удалить элемент $$$7$$$ из множества $$$6$$$. Вы должны заплатить $$$a_6 + b_7 = 13$$$ монет за эту операцию. </li></ul><p>Суммарно вы заплатите $$$66$$$ монет. После этих операций будут следующие множества:</p><ul> <li> $$$\{2, 3\}$$$; </li><li> $$$\{1\}$$$; </li><li> $$$\{1, 3\}$$$; </li><li> $$$\{3\}$$$; </li><li> $$$\{3, 4, 5, 6, 7\}$$$; </li><li> $$$\{5\}$$$; </li><li> $$$\{8\}$$$. </li></ul><p>Вы построите такой граф:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/5cf40a2ec741d258c6734584e25a52b6f7b14fd7.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>В нем нет разноцветных циклов.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="4cc34e358c89514d14408a14f0886726"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='4cc34e358c89514d14408a14f0886726'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='4cc34e358c89514d14408a14f0886726'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='4cc34e358c89514d14408a14f0886726'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств">
снм
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4cc34e358c89514d14408a14f0886726'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743628"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4cc34e358c89514d14408a14f0886726'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743628"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_c87499ccc3a17fb6cc88e96a7b85f6b46484aa3d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Избегайте разноцветных циклов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано $$$m$$$ множеств $$$A_1, A_2, \ldots, A_m$$$, состоящих из целых чисел; элементы этих множеств — целые числа от $$$1$$$ до $$$n$$$ включительно.</p><p>Есть два массива положительных целых чисел $$$a_1, a_2, \ldots, a_m$$$ и $$$b_1, b_2, \ldots, b_n$$$. </p><p>За одну операцию вы можете удалить элемент $$$j$$$ из множества $$$A_i$$$ и заплатить за это $$$a_i + b_j$$$ монет.</p><p>Вы можете сделать несколько (возможно, ноль) операций (после этого некоторые множества могут стать пустыми).</p><p>После этого вы построите неориентированный граф, где каждое ребро будет иметь цвет. Граф будет иметь $$$n$$$ вершин. Для каждого множества $$$A_i$$$ вы добавите ребро $$$(x, y)$$$ цвета $$$i$$$ для всех $$$x, y \in A_i$$$ и $$$x < y$$$. Некоторые пары вершин могут быть соединены больше чем одним ребром, но такие ребра будут иметь разные цвета.</p><p>Мы называем цикл $$$i_1 \to e_1 \to i_2 \to e_2 \to \ldots \to i_k \to e_k \to i_1$$$ ($$$e_j$$$ это какое-то ребро, соединяющее вершины $$$i_j$$$ и $$$i_{j+1}$$$ этого графа) <span class="tex-font-style-it">разноцветным</span>, если цвета всех ребер этого цикла различны.</p><p>Найдите минимальное количество монет, которое нужно заплатить, чтобы получить граф без разноцветных циклов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$m$$$ и $$$n$$$ ($$$1 \leq m, n \leq 10^5$$$), количество множеств и количество вершин в графе.</p><p>Во второй строке находятся $$$m$$$ целых чисел $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \leq a_i \leq 10^9$$$).</p><p>В третьей строке находятся $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 10^9$$$).</p><p>В каждой из следующих $$$m$$$ строк находится описание множества. В $$$i$$$-й строке первое число $$$s_i$$$ ($$$1 \leq s_i \leq n$$$) равно размеру $$$A_i$$$. Затем следуют $$$s_i$$$ целых чисел — элементы множества $$$A_i$$$. Эти целые числа различны и находятся в пределах от $$$1$$$ до $$$n$$$ включительно.</p><p>Гарантируется, что сумма $$$s_i$$$ для всех $$$1 \leq i \leq m$$$ не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальное количество монет, которое нужно заплатить, чтобы получить граф без разноцветных циклов.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 2
1 2 3
4 5
2 1 2
2 1 2
2 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
11
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 8
3 6 7 9 10 7 239
8 1 9 7 10 2 6 239
3 2 1 3
2 4 1
3 1 3 7
2 4 3
5 3 4 5 6 7
2 5 7
1 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
66
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте можно сделать следующие операции.</p><ul> <li> Удалить элемент $$$1$$$ из множества $$$1$$$. Вы должны заплатить $$$a_1 + b_1 = 5$$$ монет за эту операцию. </li><li> Удалить элемент $$$1$$$ из множества $$$2$$$. Вы должны заплатить $$$a_2 + b_1 = 6$$$ монет за эту операцию. </li></ul><p>Суммарно вы заплатите $$$11$$$ монет. После этих операций первое и второй множества будут равны $$$\{2\}$$$, а третье множество будет равно $$$\{1, 2\}$$$. Поэтому построенный граф будет содержать одно ребро $$$(1, 2)$$$ цвета $$$3$$$.</p><p>Во втором тесте можно сделать следующие операции.</p><ul> <li> Удалить элемент $$$1$$$ из множества $$$1$$$. Вы должны заплатить $$$a_1 + b_1 = 11$$$ монет за эту операцию. </li><li> Удалить элемент $$$4$$$ из множества $$$2$$$. Вы должны заплатить $$$a_2 + b_4 = 13$$$ монет за эту операцию. </li><li> Удалить элемент $$$7$$$ из множества $$$3$$$. Вы должны заплатить $$$a_3 + b_7 = 13$$$ монет за эту операцию. </li><li> Удалить элемент $$$4$$$ из множества $$$4$$$. Вы должны заплатить $$$a_4 + b_4 = 16$$$ монет за эту операцию. </li><li> Удалить элемент $$$7$$$ из множества $$$6$$$. Вы должны заплатить $$$a_6 + b_7 = 13$$$ монет за эту операцию. </li></ul><p>Суммарно вы заплатите $$$66$$$ монет. После этих операций будут следующие множества:</p><ul> <li> $$$\{2, 3\}$$$; </li><li> $$$\{1\}$$$; </li><li> $$$\{1, 3\}$$$; </li><li> $$$\{3\}$$$; </li><li> $$$\{3, 4, 5, 6, 7\}$$$; </li><li> $$$\{5\}$$$; </li><li> $$$\{8\}$$$. </li></ul><p>Вы построите такой граф:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/5cf40a2ec741d258c6734584e25a52b6f7b14fd7.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>В нем нет разноцветных циклов.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:41</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab4b1c0416df',t:'MTY5NjY2NjI0MS45MjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043d\u043c", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"] | ||
1408F | 1408 | F | ru | F. Два различных | <div class="problem-statement"><div class="header"><div class="title">F. Два различных</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано целое число $$$n$$$.</p><p>Вы должны найти список пар $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, ..., $$$(x_q, y_q)$$$ ($$$1 \leq x_i, y_i \leq n$$$) который удовлетворяет следующему условию.</p><p>Рассмотрим некоторую функцию $$$f: \mathbb{N} \times \mathbb{N} \to \mathbb{N}$$$ (мы определяем $$$\mathbb{N}$$$ как множество положительных целых чисел). Другими словами, $$$f$$$ это функция, возвращающая положительное целое число по паре положительных целых чисел.</p><p>Давайте рассмотрим массив $$$a_1, a_2, \ldots, a_n$$$, где изначально $$$a_i = i$$$.</p><p>Вы сделаете $$$q$$$ операций, в $$$i$$$-й из них вы сделаете: </p><ol> <li> присвоите $$$t = f(a_{x_i}, a_{y_i})$$$ ($$$t$$$ это временная переменная, она используется <span class="tex-font-style-bf">только</span> для следующих двух присвоений); </li><li> присвоите $$$a_{x_i} = t$$$; </li><li> присвоите $$$a_{y_i} = t$$$. </li></ol><p>Другими словами, вам нужно <span class="tex-font-style-bf">одновременно</span> заменить $$$a_{x_i}$$$ и $$$a_{y_i}$$$ на $$$f(a_{x_i}, a_{y_i})$$$. Обратите внимание, что в течение процесса значение $$$f(p, q)$$$ всегда одинаково для заданных положительных целых чисел $$$p$$$ и $$$q$$$.</p><p>В конце должно быть не больше двух различных чисел в массиве $$$a$$$.</p><p>Это должно быть выполнено для любой функции $$$f$$$.</p><p>Найдите любой возможный список пар. Количество пар должно не превосходить $$$5 \cdot 10^5$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 15\,000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите $$$q$$$ ($$$0 \leq q \leq 5 \cdot 10^5$$$) — количество пар.</p><p>В каждой из следующих $$$q$$$ строк выведите по два целых числа. В $$$i$$$-й строке выведите $$$x_i$$$, $$$y_i$$$ ($$$1 \leq x_i, y_i \leq n$$$).</p><p>Условие, описанное в тексте условия задачи, должно быть удовлетворено.</p><p>Если есть несколько возможных ответов, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1 2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
1 2
3 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте после применения единственной операции массив $$$a$$$ будет $$$[f(a_1, a_2), f(a_1, a_2), a_3]$$$. В нем всегда не больше двух различных чисел.</p><p>Во втором тесте после применения двух операций массив $$$a$$$ будет $$$[f(a_1, a_2), f(a_1, a_2), f(a_3, a_4), f(a_3, a_4)]$$$. В нем всегда не больше двух различных чисел.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="859cbb4a72fc8b58651692f4f85f29f4"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - F - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='859cbb4a72fc8b58651692f4f85f29f4'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FF%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='859cbb4a72fc8b58651692f4f85f29f4'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='859cbb4a72fc8b58651692f4f85f29f4'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Разделяй и властвуй">
разделяй и властвуй
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='859cbb4a72fc8b58651692f4f85f29f4'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743629"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='859cbb4a72fc8b58651692f4f85f29f4'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743629"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="F" data-uuid="ps_6af1ed7f338c6a60b92d75f5bf7fffd81cd970f5">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Два различных</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано целое число $$$n$$$.</p><p>Вы должны найти список пар $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, ..., $$$(x_q, y_q)$$$ ($$$1 \leq x_i, y_i \leq n$$$) который удовлетворяет следующему условию.</p><p>Рассмотрим некоторую функцию $$$f: \mathbb{N} \times \mathbb{N} \to \mathbb{N}$$$ (мы определяем $$$\mathbb{N}$$$ как множество положительных целых чисел). Другими словами, $$$f$$$ это функция, возвращающая положительное целое число по паре положительных целых чисел.</p><p>Давайте рассмотрим массив $$$a_1, a_2, \ldots, a_n$$$, где изначально $$$a_i = i$$$.</p><p>Вы сделаете $$$q$$$ операций, в $$$i$$$-й из них вы сделаете: </p><ol> <li> присвоите $$$t = f(a_{x_i}, a_{y_i})$$$ ($$$t$$$ это временная переменная, она используется <span class="tex-font-style-bf">только</span> для следующих двух присвоений); </li><li> присвоите $$$a_{x_i} = t$$$; </li><li> присвоите $$$a_{y_i} = t$$$. </li></ol><p>Другими словами, вам нужно <span class="tex-font-style-bf">одновременно</span> заменить $$$a_{x_i}$$$ и $$$a_{y_i}$$$ на $$$f(a_{x_i}, a_{y_i})$$$. Обратите внимание, что в течение процесса значение $$$f(p, q)$$$ всегда одинаково для заданных положительных целых чисел $$$p$$$ и $$$q$$$.</p><p>В конце должно быть не больше двух различных чисел в массиве $$$a$$$.</p><p>Это должно быть выполнено для любой функции $$$f$$$.</p><p>Найдите любой возможный список пар. Количество пар должно не превосходить $$$5 \cdot 10^5$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 15\,000$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите $$$q$$$ ($$$0 \leq q \leq 5 \cdot 10^5$$$) — количество пар.</p><p>В каждой из следующих $$$q$$$ строк выведите по два целых числа. В $$$i$$$-й строке выведите $$$x_i$$$, $$$y_i$$$ ($$$1 \leq x_i, y_i \leq n$$$).</p><p>Условие, описанное в тексте условия задачи, должно быть удовлетворено.</p><p>Если есть несколько возможных ответов, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1 2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
1 2
3 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте после применения единственной операции массив $$$a$$$ будет $$$[f(a_1, a_2), f(a_1, a_2), a_3]$$$. В нем всегда не больше двух различных чисел.</p><p>Во втором тесте после применения двух операций массив $$$a$$$ будет $$$[f(a_1, a_2), f(a_1, a_2), f(a_3, a_4), f(a_3, a_4)]$$$. В нем всегда не больше двух различных чисел.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:43</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab53fc5a9d39',t:'MTY5NjY2NjI0My4yOTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "*2300"] | ||
1408G | 1408 | G | ru | G. Подсчет кластеризаций | <div class="problem-statement"><div class="header"><div class="title">G. Подсчет кластеризаций</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В сети компании есть $$$n$$$ компьютеров. Они пронумерованы от $$$1$$$ до $$$n$$$.</p><p>Для каждой пары компьютеров $$$1 \leq i < j \leq n$$$ вы знаете значение $$$a_{i,j}$$$: сложность отправки сообщения между компьютерами $$$i$$$ и $$$j$$$. Значения $$$a_{i,j}$$$ для $$$i<j$$$ различны.</p><p>Вы хотите разделить компьютеры на $$$k$$$ множеств $$$A_1, A_2, \ldots, A_k$$$, чтобы следующие условия выполнялись: </p><ul> <li> для каждого компьютера $$$1 \leq i \leq n$$$ есть <span class="tex-font-style-bf">ровно</span> одно множество $$$A_j$$$ такое, что $$$i \in A_j$$$; </li><li> для каждых двух пар компьютеров $$$(s, f)$$$ и $$$(x, y)$$$ ($$$s \neq f$$$, $$$x \neq y$$$) таких, что $$$s$$$, $$$f$$$, $$$x$$$ из одного множества, а $$$x$$$ и $$$y$$$ из разных, выполняется $$$a_{s,f} < a_{x,y}$$$. </li></ul><p>Для каждого $$$1 \leq k \leq n$$$ найдите число способов разделить компьютеры на $$$k$$$ групп так, чтобы все упомянутые условия соблюдались. Эти значения могут быть большими, так что вам нужно найти их по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 1500$$$): количество компьютеров.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк записаны $$$n$$$ целых чисел $$$a_{i,1}, a_{i,2}, \ldots, a_{i,n}$$$ ($$$0 \leq a_{i,j} \leq \frac{n (n-1)}{2}$$$).</p><p>Гарантируется, что: </p><ul> <li> для всех $$$1 \leq i \leq n$$$ выполняется $$$a_{i,i} = 0$$$; </li><li> для всех $$$1 \leq i < j \leq n$$$ выполняется $$$a_{i,j} > 0$$$; </li><li> для всех $$$1 \leq i < j \leq n$$$ выполняется $$$a_{i,j} = a_{j,i}$$$; </li><li> все $$$a_{i,j}$$$ для $$$i <j$$$ различны. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел: $$$k$$$-е из них должно быть равно числу способов разбить компьютеры на $$$k$$$ групп, соблюдая все описанные условия, по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
0 3 4 6
3 0 2 1
4 2 0 5
6 1 5 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 0 1 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7
0 1 18 15 19 12 21
1 0 16 13 17 20 14
18 16 0 2 7 10 9
15 13 2 0 6 8 11
19 17 7 6 0 4 5
12 20 10 8 4 0 3
21 14 9 11 5 3 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 1 2 3 4 3 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже приведены все возможные разбиения компьютеров на $$$4$$$ группы для второго примера:</p><ul> <li> $$$\{1, 2\}, \{3, 4\}, \{5\}, \{6, 7\}$$$; </li><li> $$$\{1\}, \{2\}, \{3, 4\}, \{5, 6, 7\}$$$; </li><li> $$$\{1, 2\}, \{3\}, \{4\}, \{5, 6, 7\}$$$. </li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="303e6959cc5ca7a3043b5ea7380178be"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - G - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - G - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='303e6959cc5ca7a3043b5ea7380178be'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FG%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='303e6959cc5ca7a3043b5ea7380178be'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='303e6959cc5ca7a3043b5ea7380178be'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Быстрое преобразование Фурье">
бпф
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика">
комбинаторика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств">
снм
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2700
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='303e6959cc5ca7a3043b5ea7380178be'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743630"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='303e6959cc5ca7a3043b5ea7380178be'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743630"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="G" data-uuid="ps_24ce0575d089b30e85862a2f31a80ebb76a77b00">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Подсчет кластеризаций</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В сети компании есть $$$n$$$ компьютеров. Они пронумерованы от $$$1$$$ до $$$n$$$.</p><p>Для каждой пары компьютеров $$$1 \leq i < j \leq n$$$ вы знаете значение $$$a_{i,j}$$$: сложность отправки сообщения между компьютерами $$$i$$$ и $$$j$$$. Значения $$$a_{i,j}$$$ для $$$i<j$$$ различны.</p><p>Вы хотите разделить компьютеры на $$$k$$$ множеств $$$A_1, A_2, \ldots, A_k$$$, чтобы следующие условия выполнялись: </p><ul> <li> для каждого компьютера $$$1 \leq i \leq n$$$ есть <span class="tex-font-style-bf">ровно</span> одно множество $$$A_j$$$ такое, что $$$i \in A_j$$$; </li><li> для каждых двух пар компьютеров $$$(s, f)$$$ и $$$(x, y)$$$ ($$$s \neq f$$$, $$$x \neq y$$$) таких, что $$$s$$$, $$$f$$$, $$$x$$$ из одного множества, а $$$x$$$ и $$$y$$$ из разных, выполняется $$$a_{s,f} < a_{x,y}$$$. </li></ul><p>Для каждого $$$1 \leq k \leq n$$$ найдите число способов разделить компьютеры на $$$k$$$ групп так, чтобы все упомянутые условия соблюдались. Эти значения могут быть большими, так что вам нужно найти их по модулю $$$998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 1500$$$): количество компьютеров.</p><p>В $$$i$$$-й из следующих $$$n$$$ строк записаны $$$n$$$ целых чисел $$$a_{i,1}, a_{i,2}, \ldots, a_{i,n}$$$ ($$$0 \leq a_{i,j} \leq \frac{n (n-1)}{2}$$$).</p><p>Гарантируется, что: </p><ul> <li> для всех $$$1 \leq i \leq n$$$ выполняется $$$a_{i,i} = 0$$$; </li><li> для всех $$$1 \leq i < j \leq n$$$ выполняется $$$a_{i,j} > 0$$$; </li><li> для всех $$$1 \leq i < j \leq n$$$ выполняется $$$a_{i,j} = a_{j,i}$$$; </li><li> все $$$a_{i,j}$$$ для $$$i <j$$$ различны. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел: $$$k$$$-е из них должно быть равно числу способов разбить компьютеры на $$$k$$$ групп, соблюдая все описанные условия, по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
0 3 4 6
3 0 2 1
4 2 0 5
6 1 5 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 0 1 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7
0 1 18 15 19 12 21
1 0 16 13 17 20 14
18 16 0 2 7 10 9
15 13 2 0 6 8 11
19 17 7 6 0 4 5
12 20 10 8 4 0 3
21 14 9 11 5 3 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 1 2 3 4 3 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже приведены все возможные разбиения компьютеров на $$$4$$$ группы для второго примера:</p><ul> <li> $$$\{1, 2\}, \{3, 4\}, \{5\}, \{6, 7\}$$$; </li><li> $$$\{1\}, \{2\}, \{3, 4\}, \{5, 6, 7\}$$$; </li><li> $$$\{1, 2\}, \{3\}, \{4\}, \{5, 6, 7\}$$$. </li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=G]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:44</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab5c5e2b16e8',t:'MTY5NjY2NjI0NC42OTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u044b\u0441\u0442\u0440\u043e\u0435 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0424\u0443\u0440\u044c\u0435", "\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u043f\u0444", "\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0441\u043d\u043c", "*2700"] | ||
1408H | 1408 | H | ru | H. Разноцветные тройки | <div class="problem-statement"><div class="header"><div class="title">H. Разноцветные тройки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дана последовательность $$$a_1, a_2, \ldots, a_n$$$ неотрицательных целых чисел.</p><p>Вам нужно найти наибольшее число $$$m$$$ троек $$$(i_1, j_1, k_1)$$$, $$$(i_2, j_2, k_2)$$$, ..., $$$(i_m, j_m, k_m)$$$ таких, что выполняются следующие условия:</p><ul><li> $$$1 \leq i_p < j_p < k_p \leq n$$$ для всех $$$p$$$ среди $$$1, 2, \ldots, m$$$;</li><li> $$$a_{i_p} = a_{k_p} = 0$$$, $$$a_{j_p} \neq 0$$$;</li><li> значения $$$a_{j_1}, a_{j_2}, \ldots, a_{j_m}$$$ различны;</li><li> значения $$$i_1, j_1, k_1, i_2, j_2, k_2, \ldots, i_m, j_m, k_m$$$ различны.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \leq t \leq 500\,000$$$): количество наборов входных данных.</p><p>В первой строке каждого набора входных данных находится одно целое число $$$n$$$ ($$$1 \leq n \leq 500\,000$$$).</p><p>Во второй строке находятся $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq n$$$).</p><p>Сумма по всем $$$n$$$ не превосходит $$$500\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора выходных данных выведите одно целое число $$$m$$$: наибольшее количество троек, которое вы можете найти.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
8
1
1
2
0 0
3
0 1 0
6
0 0 1 2 0 0
6
0 1 0 0 1 0
6
0 1 3 2 0 0
6
0 0 0 0 5 0
12
0 1 0 2 2 2 0 0 3 3 4 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
1
2
1
1
1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первых двух примерах не хватает элементов даже для одной тройки, так что ответ $$$0$$$.</p><p>Во втором примере вы можете выбрать одну тройку $$$(1, 2, 3)$$$.</p><p>В четвертом примере можно выбрать две тройки $$$(1, 3, 5)$$$ и $$$(2, 4, 6)$$$.</p><p>В пятом примере можно выбрать одну тройку $$$(1, 2, 3)$$$. Мы не можем выбрать тройки $$$(1, 2, 3)$$$ и $$$(4, 5, 6)$$$ одновременно, так как $$$a_2 = a_5$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="a37ca44364e86824290da8ce6d6b3dcf"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - H - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - H - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='a37ca44364e86824290da8ce6d6b3dcf'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FH%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='a37ca44364e86824290da8ce6d6b3dcf'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='a37ca44364e86824290da8ce6d6b3dcf'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Потоки в графах">
потоки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3300
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a37ca44364e86824290da8ce6d6b3dcf'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743631"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a37ca44364e86824290da8ce6d6b3dcf'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743631"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="H" data-uuid="ps_f57292062d93a828b2a3d10064eaa9b498797384">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">H. Разноцветные тройки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дана последовательность $$$a_1, a_2, \ldots, a_n$$$ неотрицательных целых чисел.</p><p>Вам нужно найти наибольшее число $$$m$$$ троек $$$(i_1, j_1, k_1)$$$, $$$(i_2, j_2, k_2)$$$, ..., $$$(i_m, j_m, k_m)$$$ таких, что выполняются следующие условия:</p><ul><li> $$$1 \leq i_p < j_p < k_p \leq n$$$ для всех $$$p$$$ среди $$$1, 2, \ldots, m$$$;</li><li> $$$a_{i_p} = a_{k_p} = 0$$$, $$$a_{j_p} \neq 0$$$;</li><li> значения $$$a_{j_1}, a_{j_2}, \ldots, a_{j_m}$$$ различны;</li><li> значения $$$i_1, j_1, k_1, i_2, j_2, k_2, \ldots, i_m, j_m, k_m$$$ различны.</li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \leq t \leq 500\,000$$$): количество наборов входных данных.</p><p>В первой строке каждого набора входных данных находится одно целое число $$$n$$$ ($$$1 \leq n \leq 500\,000$$$).</p><p>Во второй строке находятся $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq n$$$).</p><p>Сумма по всем $$$n$$$ не превосходит $$$500\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора выходных данных выведите одно целое число $$$m$$$: наибольшее количество троек, которое вы можете найти.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
8
1
1
2
0 0
3
0 1 0
6
0 0 1 2 0 0
6
0 1 0 0 1 0
6
0 1 3 2 0 0
6
0 0 0 0 5 0
12
0 1 0 2 2 2 0 0 3 3 4 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
1
2
1
1
1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первых двух примерах не хватает элементов даже для одной тройки, так что ответ $$$0$$$.</p><p>Во втором примере вы можете выбрать одну тройку $$$(1, 2, 3)$$$.</p><p>В четвертом примере можно выбрать две тройки $$$(1, 3, 5)$$$ и $$$(2, 4, 6)$$$.</p><p>В пятом примере можно выбрать одну тройку $$$(1, 2, 3)$$$. Мы не можем выбрать тройки $$$(1, 2, 3)$$$ и $$$(4, 5, 6)$$$ одновременно, так как $$$a_2 = a_5$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=H]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:45</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab64fe747b4b',t:'MTY5NjY2NjI0Ni4wMTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0442\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3300"] | ||
1408I | 1408 | I | ru | I. Битовая магия | <div class="problem-statement"><div class="header"><div class="title">I. Битовая магия</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>6 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано положительное целое число $$$k$$$ и массив $$$a_1, a_2, \ldots, a_n$$$ неотрицательных различных чисел от $$$k$$$ до $$$2^c-1$$$.</p><p>В каждую из следующих $$$k$$$ секунд один элемент выбирается случайно равновероятно из всех $$$n$$$ элементов и уменьшается на $$$1$$$. </p><p>Для каждого целого числа $$$x$$$, $$$0 \leq x \leq 2^c - 1$$$, вам нужно найти вероятность, что в конце побитовый XOR всех чисел в массиве равен $$$x$$$. </p><p>Каждое из этих значений может быть представлено в виде несократимой дроби $$$\frac{p}{q}$$$, и вам нужно найти $$$p \cdot q^{-1}$$$ по модулю $$$998\,244\,353$$$. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся три целых числа $$$n, k, c$$$ ($$$1 \leq n \leq (2^c - k)$$$, $$$1 \leq k \leq 16$$$, $$$1 \leq c \leq 16$$$).</p><p>Во второй строке находятся $$$n$$$ различных целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$k \leq a_i \leq 2^c-1$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$2^c$$$ целых чисел: вероятность, что побитовой XOR в конце равен $$$x$$$, для всех $$$x$$$ среди $$$\{0, 1, \ldots, 2^c-1\}$$$ по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 1 3
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 0 748683265 0 499122177 0 748683265
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="236aef74bb9da0ba7f59f729ff3fe569"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - I - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="27b2fb2f51536b9d36534af580b9fdba390a96ed"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - I - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='236aef74bb9da0ba7f59f729ff3fe569'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/graknforces"><img src="https://assets.codeforces.com/images/graknlabs-logo.png" style="width:300px;"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1408%2Fproblem%2FI%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='236aef74bb9da0ba7f59f729ff3fe569'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1408">Grakn Forces 2020</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='236aef74bb9da0ba7f59f729ff3fe569'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1408/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='236aef74bb9da0ba7f59f729ff3fe569'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="743632"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='236aef74bb9da0ba7f59f729ff3fe569'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="743632"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/83180" title="Grakn Forces 2020 [Div1 and Div2 combined]" target="_blank">Анонс №1 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12010" resourceName="Grakn Forces 2020 [Div1 and Div2 combined]"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82787" title="Grakn Forces 2020" target="_blank">Grakn Forces 2020 <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11952" resourceName="Grakn Forces 2020"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/83233" title="Grakn Forces -- Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12025" resourceName="Grakn Forces -- Editorial"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1408">Задачи</a></li>
<li><a
href="/contest/1408/submit">Отослать</a></li>
<li><a
href="/contest/1408/my">Мои посылки</a></li>
<li><a
href="/contest/1408/status">Статус</a></li>
<li><a
href="/contest/1408/hacks">Взломы</a></li>
<li><a
href="/contest/1408/room/1">Комната</a></li>
<li><a
href="/contest/1408/standings">Положение</a></li>
<li><a
href="/contest/1408/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="I" data-uuid="ps_e5eb77331740aadf0d3cbf2fc4ae04c16deec98d">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">I. Битовая магия</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>6 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано положительное целое число $$$k$$$ и массив $$$a_1, a_2, \ldots, a_n$$$ неотрицательных различных чисел от $$$k$$$ до $$$2^c-1$$$.</p><p>В каждую из следующих $$$k$$$ секунд один элемент выбирается случайно равновероятно из всех $$$n$$$ элементов и уменьшается на $$$1$$$. </p><p>Для каждого целого числа $$$x$$$, $$$0 \leq x \leq 2^c - 1$$$, вам нужно найти вероятность, что в конце побитовый XOR всех чисел в массиве равен $$$x$$$. </p><p>Каждое из этих значений может быть представлено в виде несократимой дроби $$$\frac{p}{q}$$$, и вам нужно найти $$$p \cdot q^{-1}$$$ по модулю $$$998\,244\,353$$$. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся три целых числа $$$n, k, c$$$ ($$$1 \leq n \leq (2^c - k)$$$, $$$1 \leq k \leq 16$$$, $$$1 \leq c \leq 16$$$).</p><p>Во второй строке находятся $$$n$$$ различных целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$k \leq a_i \leq 2^c-1$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$2^c$$$ целых чисел: вероятность, что побитовой XOR в конце равен $$$x$$$, для всех $$$x$$$ среди $$$\{0, 1, \ldots, 2^c-1\}$$$ по модулю $$$998\,244\,353$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 1 3
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0 0 748683265 0 499122177 0 748683265
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=I]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:47</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab6d4ed13aa7',t:'MTY5NjY2NjI0Ny4zNzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3200"] | ||
1409A | 1409 | A | ru | A. Ещё одна задача о двух числах | <div class="problem-statement"><div class="header"><div class="title">A. Ещё одна задача о двух числах</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два целых числа $$$a$$$ и $$$b$$$.</p><p>За один ход вы можете выбрать некоторое <span class="tex-font-style-bf">целое число</span> $$$k$$$ от $$$1$$$ до $$$10$$$ и прибавить его к $$$a$$$ или вычесть из $$$a$$$. Другими словами, вы выбираете целое число $$$k \in [1; 10]$$$ и выполняете $$$a := a + k$$$ или $$$a := a - k$$$. Вы можете использовать <span class="tex-font-style-bf">различные</span> значения $$$k$$$ во время разных ходов.</p><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое, чтобы получить $$$b$$$ из $$$a$$$.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит два целых числа $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: минимальное количество ходов, необходимое, чтобы получить $$$b$$$ из $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
5 5
13 42
18 4
1337 420
123456789 1000000000
100500 9000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
3
2
92
87654322
9150
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера вам ничего не нужно делать.</p><p>Во втором наборе тестовых данных примера может быть применена следующая последовательность ходов: $$$13 \rightarrow 23 \rightarrow 32 \rightarrow 42$$$ (прибавить $$$10$$$, прибавить $$$9$$$, прибавить $$$10$$$).</p><p>В третьем наборе тестовых данных примера может быть применена следующая последовательность ходов: $$$18 \rightarrow 10 \rightarrow 4$$$ (вычесть $$$8$$$, вычесть $$$6$$$).</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="39ba6f4ad5f8bb4c77e84629a9b6c991"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e9b7f9079eb3851451777dff2d08620c1e26e58d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='39ba6f4ad5f8bb4c77e84629a9b6c991'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1409%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='39ba6f4ad5f8bb4c77e84629a9b6c991'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1409">Codeforces Round 667 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='39ba6f4ad5f8bb4c77e84629a9b6c991'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1409/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='39ba6f4ad5f8bb4c77e84629a9b6c991'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="716925"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='39ba6f4ad5f8bb4c77e84629a9b6c991'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="716925"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82231" title="Codeforces Round #667 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11855:11856" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82284" title="Разбор Codeforces Round #667 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11870:11871" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1409">Задачи</a></li>
<li><a
href="/contest/1409/submit">Отослать</a></li>
<li><a
href="/contest/1409/my">Мои посылки</a></li>
<li><a
href="/contest/1409/status">Статус</a></li>
<li><a
href="/contest/1409/hacks">Взломы</a></li>
<li><a
href="/contest/1409/standings">Положение</a></li>
<li><a
href="/contest/1409/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_e88e47c6a5092d0114ddc46f9c873b91ddce93f8">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Ещё одна задача о двух числах</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два целых числа $$$a$$$ и $$$b$$$.</p><p>За один ход вы можете выбрать некоторое <span class="tex-font-style-bf">целое число</span> $$$k$$$ от $$$1$$$ до $$$10$$$ и прибавить его к $$$a$$$ или вычесть из $$$a$$$. Другими словами, вы выбираете целое число $$$k \in [1; 10]$$$ и выполняете $$$a := a + k$$$ или $$$a := a - k$$$. Вы можете использовать <span class="tex-font-style-bf">различные</span> значения $$$k$$$ во время разных ходов.</p><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> количество ходов, необходимое, чтобы получить $$$b$$$ из $$$a$$$.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит два целых числа $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: минимальное количество ходов, необходимое, чтобы получить $$$b$$$ из $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
5 5
13 42
18 4
1337 420
123456789 1000000000
100500 9000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
3
2
92
87654322
9150
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера вам ничего не нужно делать.</p><p>Во втором наборе тестовых данных примера может быть применена следующая последовательность ходов: $$$13 \rightarrow 23 \rightarrow 32 \rightarrow 42$$$ (прибавить $$$10$$$, прибавить $$$9$$$, прибавить $$$10$$$).</p><p>В третьем наборе тестовых данных примера может быть применена следующая последовательность ходов: $$$18 \rightarrow 10 \rightarrow 4$$$ (вычесть $$$8$$$, вычесть $$$6$$$).</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:48</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab760b441607',t:'MTY5NjY2NjI0OC43NzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"] | ||
1409B | 1409 | B | ru | B. Минимальное произведение | <div class="problem-statement"><div class="header"><div class="title">B. Минимальное произведение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны четыре целых числа $$$a$$$, $$$b$$$, $$$x$$$ и $$$y$$$. Изначально $$$a \ge x$$$ и $$$b \ge y$$$. Вы можете применить следующую операцию <span class="tex-font-style-bf">не более</span> $$$n$$$ раз:</p><ul> <li> Выбрать $$$a$$$ или $$$b$$$ и уменьшить это число на единицу. Однако в результате этой операции значение $$$a$$$ не может стать меньше $$$x$$$, а значение $$$b$$$ не может стать меньше $$$y$$$. </li></ul><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> возможное произведение $$$a$$$ и $$$b$$$ ($$$a \cdot b$$$), которое можно получить, применив данную операцию не более $$$n$$$ раз.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит пять целых чисел $$$a$$$, $$$b$$$, $$$x$$$, $$$y$$$ и $$$n$$$ ($$$1 \le a, b, x, y, n \le 10^9$$$). Дополнительное ограничение на входные данные: всегда справедливы неравенства $$$a \ge x$$$ и $$$b \ge y$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите число: <span class="tex-font-style-bf">минимальное</span> возможное произведение $$$a$$$ и $$$b$$$ ($$$a \cdot b$$$), которое можно получить, применив данную операцию не более $$$n$$$ раз.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
10 10 8 5 3
12 8 8 7 2
12343 43 4543 39 123212
1000000000 1000000000 1 1 1
1000000000 1000000000 1 1 1000000000
10 11 2 1 5
10 11 9 1 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
70
77
177177
999999999000000000
999999999
55
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера нужно уменьшить $$$b$$$ три раза и получить $$$10 \cdot 7 = 70$$$.</p><p>Во втором наборе тестовых данных примера нужно уменьшить $$$a$$$ один раз, $$$b$$$ один раз и получить $$$11 \cdot 7 = 77$$$.</p><p>В шестом наборе тестовых данных примера нужно уменьшить $$$a$$$ пять раз и получить $$$5 \cdot 11 = 55$$$.</p><p>В седьмом наборе тестовых данных примера нужно уменьшить $$$b$$$ десять раз и получить $$$10 \cdot 1 = 10$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="25b06976e415ca910485d71e8118579d"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e9b7f9079eb3851451777dff2d08620c1e26e58d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='25b06976e415ca910485d71e8118579d'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1409%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='25b06976e415ca910485d71e8118579d'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1409">Codeforces Round 667 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='25b06976e415ca910485d71e8118579d'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1409/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1100
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='25b06976e415ca910485d71e8118579d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="716926"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='25b06976e415ca910485d71e8118579d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="716926"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82231" title="Codeforces Round #667 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11855:11856" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82284" title="Разбор Codeforces Round #667 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11870:11871" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1409">Задачи</a></li>
<li><a
href="/contest/1409/submit">Отослать</a></li>
<li><a
href="/contest/1409/my">Мои посылки</a></li>
<li><a
href="/contest/1409/status">Статус</a></li>
<li><a
href="/contest/1409/hacks">Взломы</a></li>
<li><a
href="/contest/1409/standings">Положение</a></li>
<li><a
href="/contest/1409/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_d83feb0009c09950644057160e39139afd9674d2">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Минимальное произведение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны четыре целых числа $$$a$$$, $$$b$$$, $$$x$$$ и $$$y$$$. Изначально $$$a \ge x$$$ и $$$b \ge y$$$. Вы можете применить следующую операцию <span class="tex-font-style-bf">не более</span> $$$n$$$ раз:</p><ul> <li> Выбрать $$$a$$$ или $$$b$$$ и уменьшить это число на единицу. Однако в результате этой операции значение $$$a$$$ не может стать меньше $$$x$$$, а значение $$$b$$$ не может стать меньше $$$y$$$. </li></ul><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> возможное произведение $$$a$$$ и $$$b$$$ ($$$a \cdot b$$$), которое можно получить, применив данную операцию не более $$$n$$$ раз.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит пять целых чисел $$$a$$$, $$$b$$$, $$$x$$$, $$$y$$$ и $$$n$$$ ($$$1 \le a, b, x, y, n \le 10^9$$$). Дополнительное ограничение на входные данные: всегда справедливы неравенства $$$a \ge x$$$ и $$$b \ge y$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите число: <span class="tex-font-style-bf">минимальное</span> возможное произведение $$$a$$$ и $$$b$$$ ($$$a \cdot b$$$), которое можно получить, применив данную операцию не более $$$n$$$ раз.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
10 10 8 5 3
12 8 8 7 2
12343 43 4543 39 123212
1000000000 1000000000 1 1 1
1000000000 1000000000 1 1 1000000000
10 11 2 1 5
10 11 9 1 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
70
77
177177
999999999000000000
999999999
55
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных примера нужно уменьшить $$$b$$$ три раза и получить $$$10 \cdot 7 = 70$$$.</p><p>Во втором наборе тестовых данных примера нужно уменьшить $$$a$$$ один раз, $$$b$$$ один раз и получить $$$11 \cdot 7 = 77$$$.</p><p>В шестом наборе тестовых данных примера нужно уменьшить $$$a$$$ пять раз и получить $$$5 \cdot 11 = 55$$$.</p><p>В седьмом наборе тестовых данных примера нужно уменьшить $$$b$$$ десять раз и получить $$$10 \cdot 1 = 10$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:50</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab7e78f29d86',t:'MTY5NjY2NjI1MC4xMDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1100"] | ||
1409C | 1409 | C | ru | C. Ещё одно восстановление массива | <div class="problem-statement"><div class="header"><div class="title">C. Ещё одно восстановление массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У нас есть секретный массив. Вы не знаете этот массив, и вам нужно его восстановить. Однако, вам известны некоторые факты об этом массиве:</p><ul> <li> Массив состоит из $$$n$$$ <span class="tex-font-style-bf">различных положительных</span> (больше $$$0$$$) целых чисел. </li><li> Массив содержит два элемента $$$x$$$ и $$$y$$$ (вам <span class="tex-font-style-bf">известны</span> эти элементы) такие, что $$$x < y$$$. </li><li> Если отсортировать массив по возрастанию (таким образом, что $$$a_1 < a_2 < \ldots < a_n$$$), то разности между всеми соседними (последовательными) элементами равны (то есть $$$a_2 - a_1 = a_3 - a_2 = \ldots = a_n - a_{n-1})$$$. </li></ul><p>Можно доказать, что такой массив всегда существует при ограничениях, заданных ниже.</p><p>Среди всех возможных массивов, удовлетворяющих данным условиям, мы просим восстановить массив, имеющий <span class="tex-font-style-bf">минимально возможный</span> максимальный элемент. Другими словами, необходимо минимизировать $$$\max(a_1, a_2, \dots, a_n)$$$.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит три целых числа $$$n$$$, $$$x$$$ и $$$y$$$ ($$$2 \le n \le 50$$$; $$$1 \le x < y \le 50$$$) — длину массива и два элемента, которые представлены в массиве, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), где $$$a_i$$$ — $$$i$$$-й элемент загаданного массива. Если существует несколько подходящих ответов, вы можете выбрать любой (это также означает, что порядок элементов не имеет значения).</p><p>Можно доказать, что такой массив всегда существует при заданных ограничениях.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2 1 49
5 20 50
6 20 50
5 3 8
9 13 22
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 49
20 40 30 50 10
26 32 20 38 44 50
8 23 18 13 3
1 10 13 4 19 22 25 16 7 </pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="c0294c717f0c574b2ecf231201d549b5"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - C - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e9b7f9079eb3851451777dff2d08620c1e26e58d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='c0294c717f0c574b2ecf231201d549b5'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1409%2Fproblem%2FC%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='c0294c717f0c574b2ecf231201d549b5'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1409">Codeforces Round 667 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='c0294c717f0c574b2ecf231201d549b5'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1409/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c0294c717f0c574b2ecf231201d549b5'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="716927"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c0294c717f0c574b2ecf231201d549b5'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="716927"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82231" title="Codeforces Round #667 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11855:11856" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82284" title="Разбор Codeforces Round #667 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11870:11871" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1409">Задачи</a></li>
<li><a
href="/contest/1409/submit">Отослать</a></li>
<li><a
href="/contest/1409/my">Мои посылки</a></li>
<li><a
href="/contest/1409/status">Статус</a></li>
<li><a
href="/contest/1409/hacks">Взломы</a></li>
<li><a
href="/contest/1409/standings">Положение</a></li>
<li><a
href="/contest/1409/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="C" data-uuid="ps_69eae2898efa2e44041adc6e8ea3d0f320c43cdc">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Ещё одно восстановление массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У нас есть секретный массив. Вы не знаете этот массив, и вам нужно его восстановить. Однако, вам известны некоторые факты об этом массиве:</p><ul> <li> Массив состоит из $$$n$$$ <span class="tex-font-style-bf">различных положительных</span> (больше $$$0$$$) целых чисел. </li><li> Массив содержит два элемента $$$x$$$ и $$$y$$$ (вам <span class="tex-font-style-bf">известны</span> эти элементы) такие, что $$$x < y$$$. </li><li> Если отсортировать массив по возрастанию (таким образом, что $$$a_1 < a_2 < \ldots < a_n$$$), то разности между всеми соседними (последовательными) элементами равны (то есть $$$a_2 - a_1 = a_3 - a_2 = \ldots = a_n - a_{n-1})$$$. </li></ul><p>Можно доказать, что такой массив всегда существует при ограничениях, заданных ниже.</p><p>Среди всех возможных массивов, удовлетворяющих данным условиям, мы просим восстановить массив, имеющий <span class="tex-font-style-bf">минимально возможный</span> максимальный элемент. Другими словами, необходимо минимизировать $$$\max(a_1, a_2, \dots, a_n)$$$.</p><p>Вам нужно ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка теста содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит три целых числа $$$n$$$, $$$x$$$ и $$$y$$$ ($$$2 \le n \le 50$$$; $$$1 \le x < y \le 50$$$) — длину массива и два элемента, которые представлены в массиве, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ на него: $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), где $$$a_i$$$ — $$$i$$$-й элемент загаданного массива. Если существует несколько подходящих ответов, вы можете выбрать любой (это также означает, что порядок элементов не имеет значения).</p><p>Можно доказать, что такой массив всегда существует при заданных ограничениях.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2 1 49
5 20 50
6 20 50
5 3 8
9 13 22
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 49
20 40 30 50 10
26 32 20 38 44 50
8 23 18 13 3
1 10 13 4 19 22 25 16 7 </pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:51</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab86dcce1610',t:'MTY5NjY2NjI1MS40MTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1200"] | ||
1409D | 1409 | D | ru | D. Уменьшение суммы цифр | <div class="problem-statement"><div class="header"><div class="title">D. Уменьшение суммы цифр</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано целое положительное число $$$n$$$. За один ход вы можете увеличить $$$n$$$ на единицу (то есть сделать $$$n := n + 1$$$). Ваша задача — найти минимальное количество ходов, которое надо совершить, чтобы сделать сумму цифр $$$n$$$ не превышающей $$$s$$$.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$s$$$ ($$$1 \le n \le 10^{18}$$$; $$$1 \le s \le 162$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор тестовых данных выведите ответ: минимальное количество ходов, которое надо совершить, чтобы сделать сумму цифр $$$n$$$ не превышающей $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
0
500
2128012501878
899999999999999999
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="d7c5b6aedc86fd8a099bedd7f085cbab"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - D - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e9b7f9079eb3851451777dff2d08620c1e26e58d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='d7c5b6aedc86fd8a099bedd7f085cbab'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1409%2Fproblem%2FD%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='d7c5b6aedc86fd8a099bedd7f085cbab'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1409">Codeforces Round 667 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='d7c5b6aedc86fd8a099bedd7f085cbab'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1409/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d7c5b6aedc86fd8a099bedd7f085cbab'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="717432"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d7c5b6aedc86fd8a099bedd7f085cbab'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="717432"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82231" title="Codeforces Round #667 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11855:11856" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82284" title="Разбор Codeforces Round #667 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11870:11871" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1409">Задачи</a></li>
<li><a
href="/contest/1409/submit">Отослать</a></li>
<li><a
href="/contest/1409/my">Мои посылки</a></li>
<li><a
href="/contest/1409/status">Статус</a></li>
<li><a
href="/contest/1409/hacks">Взломы</a></li>
<li><a
href="/contest/1409/standings">Положение</a></li>
<li><a
href="/contest/1409/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="D" data-uuid="ps_229594e4053323468242755f676311cb10814571">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Уменьшение суммы цифр</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано целое положительное число $$$n$$$. За один ход вы можете увеличить $$$n$$$ на единицу (то есть сделать $$$n := n + 1$$$). Ваша задача — найти минимальное количество ходов, которое надо совершить, чтобы сделать сумму цифр $$$n$$$ не превышающей $$$s$$$.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$s$$$ ($$$1 \le n \le 10^{18}$$$; $$$1 \le s \le 162$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор тестовых данных выведите ответ: минимальное количество ходов, которое надо совершить, чтобы сделать сумму цифр $$$n$$$ не превышающей $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2 1
1 1
500 4
217871987498122 10
100000000000000001 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
0
500
2128012501878
899999999999999999
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:52</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab8ee8dd9d46',t:'MTY5NjY2NjI1Mi43NDIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1500"] | ||
1409E | 1409 | E | ru | E. Две платформы | <div class="problem-statement"><div class="header"><div class="title">E. Две платформы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На плоскости находится $$$n$$$ точек. Точка $$$i$$$ имеет координаты $$$(x_i, y_i)$$$. У вас есть две горизонтальные платформы, обе длины $$$k$$$. Каждая платформа может быть размещена в любом месте на плоскости, но она должна быть размещена <span class="tex-font-style-bf">горизонтально</span> (на одной и той же $$$y$$$-координате) и иметь <span class="tex-font-style-bf">целочисленные границы</span>. Если левая граница платформы равна $$$(x, y)$$$, то правая граница равна $$$(x + k, y)$$$, и все точки между границами (включая границы) принадлежат платформе.</p><p>Обратите внимание, что платформы могут иметь общие точки (пересекаться), а также не обязательно размещать обе платформы на одной $$$y$$$-координате.</p><p>После размещения обеих платформ на плоскости все точки начинают падать вниз, уменьшая $$$y$$$-координату. Если в какой-то момент точка сталкивается с какой-либо платформой, то она останавливается и считается <span class="tex-font-style-bf">сохраненной</span>. Точки, которые никогда не сталкиваются ни с какой платформой, теряются.</p><p>Ваша задача — найти максимальное количество точек, которые вы можете <span class="tex-font-style-bf">сохранить</span>, если вы разместите обе платформы оптимально.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Для лучшего понимания, пожалуйста, ознакомьтесь с разделом <span class="tex-font-style-bf">Примечание</span> ниже, чтобы увидеть картинку для первого набора тестовых данных примера.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следует $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — количество точек и длину каждой платформы, соответственно. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), где $$$x_i$$$ — это $$$x$$$-координата $$$i$$$-й точки. Третья строка набора тестовых данных содержит $$$n$$$ целых чисел $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$), где $$$y_i$$$ — это $$$y$$$-координата $$$i$$$-й точки. Все точки различны (не существует такой пары $$$1 \le i < j \le n$$$, что $$$x_i = x_j$$$ и $$$y_i = y_j$$$).</p><p>Гарантируется, что сумма $$$n$$$ не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на каждый набор тестовых данных: максимальное количество точек, которые вы можете сохранить, если вы разместите обе платформы оптимально.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
7 1
1 5 2 3 1 5 4
1 3 6 7 2 5 4
1 1
1000000000
1000000000
5 10
10 7 5 15 8
20 199 192 219 1904
10 10
15 19 8 17 20 10 9 2 10 19
12 13 6 17 1 14 7 9 19 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
1
5
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка, соответствующая первому набору тестовых данных примера:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/8a3aa078020926a84255072419871610d7b6a31f.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Синие точки представляют собой точки из входных данных, красные отрезки — платформы. Одним из возможных способов является размещение первой платформы между точками $$$(1, -1)$$$ и $$$(2, -1)$$$, а второй платформы — между точками $$$(4, 3)$$$ и $$$(5, 3)$$$. Векторы обозначают, как будут падать точки. Можно заметить, что единственная точка, которую мы не можем сохранить — это точка $$$(3, 7)$$$, поэтому она будет падать бесконечно и в итоге будет потеряна. Можно доказать, что мы не можем добиться лучшего ответа. Также обратите внимание, что точка $$$(5, 3)$$$ вообще не падает, потому что она уже находится на платформе.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="84927a40d9fcf60fce4c0d06829c04eb"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - E - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e9b7f9079eb3851451777dff2d08620c1e26e58d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - E - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='84927a40d9fcf60fce4c0d06829c04eb'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1409%2Fproblem%2FE%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='84927a40d9fcf60fce4c0d06829c04eb'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1409">Codeforces Round 667 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='84927a40d9fcf60fce4c0d06829c04eb'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1409/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='84927a40d9fcf60fce4c0d06829c04eb'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="716928"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='84927a40d9fcf60fce4c0d06829c04eb'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="716928"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82231" title="Codeforces Round #667 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11855:11856" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82284" title="Разбор Codeforces Round #667 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11870:11871" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1409">Задачи</a></li>
<li><a
href="/contest/1409/submit">Отослать</a></li>
<li><a
href="/contest/1409/my">Мои посылки</a></li>
<li><a
href="/contest/1409/status">Статус</a></li>
<li><a
href="/contest/1409/hacks">Взломы</a></li>
<li><a
href="/contest/1409/standings">Положение</a></li>
<li><a
href="/contest/1409/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="E" data-uuid="ps_ca2200e6f817817fe43e15191caea2e77b94178b">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Две платформы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На плоскости находится $$$n$$$ точек. Точка $$$i$$$ имеет координаты $$$(x_i, y_i)$$$. У вас есть две горизонтальные платформы, обе длины $$$k$$$. Каждая платформа может быть размещена в любом месте на плоскости, но она должна быть размещена <span class="tex-font-style-bf">горизонтально</span> (на одной и той же $$$y$$$-координате) и иметь <span class="tex-font-style-bf">целочисленные границы</span>. Если левая граница платформы равна $$$(x, y)$$$, то правая граница равна $$$(x + k, y)$$$, и все точки между границами (включая границы) принадлежат платформе.</p><p>Обратите внимание, что платформы могут иметь общие точки (пересекаться), а также не обязательно размещать обе платформы на одной $$$y$$$-координате.</p><p>После размещения обеих платформ на плоскости все точки начинают падать вниз, уменьшая $$$y$$$-координату. Если в какой-то момент точка сталкивается с какой-либо платформой, то она останавливается и считается <span class="tex-font-style-bf">сохраненной</span>. Точки, которые никогда не сталкиваются ни с какой платформой, теряются.</p><p>Ваша задача — найти максимальное количество точек, которые вы можете <span class="tex-font-style-bf">сохранить</span>, если вы разместите обе платформы оптимально.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Для лучшего понимания, пожалуйста, ознакомьтесь с разделом <span class="tex-font-style-bf">Примечание</span> ниже, чтобы увидеть картинку для первого набора тестовых данных примера.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следует $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le 10^9$$$) — количество точек и длину каждой платформы, соответственно. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), где $$$x_i$$$ — это $$$x$$$-координата $$$i$$$-й точки. Третья строка набора тестовых данных содержит $$$n$$$ целых чисел $$$y_1, y_2, \dots, y_n$$$ ($$$1 \le y_i \le 10^9$$$), где $$$y_i$$$ — это $$$y$$$-координата $$$i$$$-й точки. Все точки различны (не существует такой пары $$$1 \le i < j \le n$$$, что $$$x_i = x_j$$$ и $$$y_i = y_j$$$).</p><p>Гарантируется, что сумма $$$n$$$ не превосходит $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на каждый набор тестовых данных: максимальное количество точек, которые вы можете сохранить, если вы разместите обе платформы оптимально.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
7 1
1 5 2 3 1 5 4
1 3 6 7 2 5 4
1 1
1000000000
1000000000
5 10
10 7 5 15 8
20 199 192 219 1904
10 10
15 19 8 17 20 10 9 2 10 19
12 13 6 17 1 14 7 9 19 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
1
5
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка, соответствующая первому набору тестовых данных примера:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/8a3aa078020926a84255072419871610d7b6a31f.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Синие точки представляют собой точки из входных данных, красные отрезки — платформы. Одним из возможных способов является размещение первой платформы между точками $$$(1, -1)$$$ и $$$(2, -1)$$$, а второй платформы — между точками $$$(4, 3)$$$ и $$$(5, 3)$$$. Векторы обозначают, как будут падать точки. Можно заметить, что единственная точка, которую мы не можем сохранить — это точка $$$(3, 7)$$$, поэтому она будет падать бесконечно и в итоге будет потеряна. Можно доказать, что мы не можем добиться лучшего ответа. Также обратите внимание, что точка $$$(5, 3)$$$ вообще не падает, потому что она уже находится на платформе.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:54</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab975dd37a69',t:'MTY5NjY2NjI1NC4wODUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"] | ||
1409F | 1409 | F | ru | F. Подпоследовательности длины два | <div class="problem-statement"><div class="header"><div class="title">F. Подпоследовательности длины два</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано две строки $$$s$$$ и $$$t$$$, состоящие из строчных букв латинского алфавита. Длина $$$t$$$ равна $$$2$$$ (то есть эта строка состоит ровно из двух символов).</p><p>За один ход вы можете выбрать <span class="tex-font-style-bf">любой</span> символ $$$s$$$ и заменить его на <span class="tex-font-style-bf">любую</span> строчную букву латинского алфавита. Более формально, вы выбираете какое-то $$$i$$$ и заменяете $$$s_i$$$ (символ на позиции $$$i$$$) на какой-то символ от '<span class="tex-font-style-tt">a</span>' до '<span class="tex-font-style-tt">z</span>'.</p><p>Вы хотите сделать <span class="tex-font-style-bf">не более</span> $$$k$$$ замен таким образом, чтобы <span class="tex-font-style-bf">максимизировать</span> количество вхождений $$$t$$$ в $$$s$$$ в качестве <span class="tex-font-style-bf">подпоследовательности</span>.</p><p>Напомним, что подпоследовательность — это последовательность, которая может быть получена из заданной последовательности путем удаления нуля или более элементов без изменения порядка остальных элементов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 200$$$; $$$0 \le k \le n$$$) — длина $$$s$$$ и максимальное количество ходов, которое можно сделать. Вторая строка входных данных содержит строку $$$s$$$, состоящую из $$$n$$$ строчных букв латинского алфавита. Третья строка входных данных содержит строку $$$t$$$, состоящую из двух строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимально возможное количество вхождений $$$t$$$ в $$$s$$$ в качестве <span class="tex-font-style-bf">подпоследовательности</span> при оптимальной замене не более $$$k$$$ символов в $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2
bbaa
ab
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 3
asddsaf
sd
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
15 6
qwertyhgfdsazxc
qa
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
16
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 2
abacaba
aa
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
15
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно получить строку «<span class="tex-font-style-tt">abab</span>», заменив $$$s_1$$$ на '<span class="tex-font-style-tt">a</span>' и $$$s_4$$$ на '<span class="tex-font-style-tt">b</span>'. Тогда ответ будет равен $$$3$$$.</p><p>Во втором примере можно получить строку «<span class="tex-font-style-tt">ssddsdd</span>» и получить ответ $$$10$$$.</p><p>В четвертом примере можно получить строку «<span class="tex-font-style-tt">aaacaaa</span>» и получить ответ $$$15$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="9bbae1395aead7d25d4231bbf2968ca7"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - F - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="e9b7f9079eb3851451777dff2d08620c1e26e58d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='9bbae1395aead7d25d4231bbf2968ca7'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<a href="/"><img height="65" style="height: 65px;" alt="Codeforces" title="Codeforces" src="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png"/></a>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1409%2Fproblem%2FF%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='9bbae1395aead7d25d4231bbf2968ca7'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1409">Codeforces Round 667 (Div. 3)</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='9bbae1395aead7d25d4231bbf2968ca7'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1409/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2100
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9bbae1395aead7d25d4231bbf2968ca7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="716930"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9bbae1395aead7d25d4231bbf2968ca7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="716930"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/82231" title="Codeforces Round #667 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11855:11856" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/82284" title="Разбор Codeforces Round #667 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11870:11871" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1409">Задачи</a></li>
<li><a
href="/contest/1409/submit">Отослать</a></li>
<li><a
href="/contest/1409/my">Мои посылки</a></li>
<li><a
href="/contest/1409/status">Статус</a></li>
<li><a
href="/contest/1409/hacks">Взломы</a></li>
<li><a
href="/contest/1409/standings">Положение</a></li>
<li><a
href="/contest/1409/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="F" data-uuid="ps_94c40971522897f181bc643cdb09e5486cfb4560">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Подпоследовательности длины два</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано две строки $$$s$$$ и $$$t$$$, состоящие из строчных букв латинского алфавита. Длина $$$t$$$ равна $$$2$$$ (то есть эта строка состоит ровно из двух символов).</p><p>За один ход вы можете выбрать <span class="tex-font-style-bf">любой</span> символ $$$s$$$ и заменить его на <span class="tex-font-style-bf">любую</span> строчную букву латинского алфавита. Более формально, вы выбираете какое-то $$$i$$$ и заменяете $$$s_i$$$ (символ на позиции $$$i$$$) на какой-то символ от '<span class="tex-font-style-tt">a</span>' до '<span class="tex-font-style-tt">z</span>'.</p><p>Вы хотите сделать <span class="tex-font-style-bf">не более</span> $$$k$$$ замен таким образом, чтобы <span class="tex-font-style-bf">максимизировать</span> количество вхождений $$$t$$$ в $$$s$$$ в качестве <span class="tex-font-style-bf">подпоследовательности</span>.</p><p>Напомним, что подпоследовательность — это последовательность, которая может быть получена из заданной последовательности путем удаления нуля или более элементов без изменения порядка остальных элементов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 200$$$; $$$0 \le k \le n$$$) — длина $$$s$$$ и максимальное количество ходов, которое можно сделать. Вторая строка входных данных содержит строку $$$s$$$, состоящую из $$$n$$$ строчных букв латинского алфавита. Третья строка входных данных содержит строку $$$t$$$, состоящую из двух строчных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимально возможное количество вхождений $$$t$$$ в $$$s$$$ в качестве <span class="tex-font-style-bf">подпоследовательности</span> при оптимальной замене не более $$$k$$$ символов в $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2
bbaa
ab
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 3
asddsaf
sd
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
15 6
qwertyhgfdsazxc
qa
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
16
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 2
abacaba
aa
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
15
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно получить строку «<span class="tex-font-style-tt">abab</span>», заменив $$$s_1$$$ на '<span class="tex-font-style-tt">a</span>' и $$$s_4$$$ на '<span class="tex-font-style-tt">b</span>'. Тогда ответ будет равен $$$3$$$.</p><p>Во втором примере можно получить строку «<span class="tex-font-style-tt">ssddsdd</span>» и получить ответ $$$10$$$.</p><p>В четвертом примере можно получить строку «<span class="tex-font-style-tt">aaacaaa</span>» и получить ответ $$$15$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:55</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124ab9fbf439daa',t:'MTY5NjY2NjI1NS40MzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*2100"] | ||
1411A | 1411 | A | ru | A. Игровой чат | <div class="problem-statement"><div class="header"><div class="title">A. Игровой чат</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам предстоит разработать фильтр для плохих сообщений в чате одной игры. Сообщение представляет из себя строку $$$S$$$ длины $$$n$$$, состоящую из строчных английских букв и символов '<span class="tex-font-style-tt">)</span>'. Строка считается <span class="tex-font-style-it">плохой</span>, если количество символов '<span class="tex-font-style-tt">)</span>' в конце строки превышает количество остальных символов. Например, у строки «<span class="tex-font-style-tt">)bc)))</span>» три скобки в конце, три остальных символа, и эта строка не считается плохой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано целое число $$$t$$$ — количество тестовых случаев ($$$1 \leq t \leq 100$$$). Далее дано описание $$$t$$$ тестовых случаев.</p><p>В первой строке дано число $$$n$$$ ($$$1 \leq n \leq 100$$$). Во второй строке дана строка $$$S$$$ длины $$$n$$$, состоящая из строчных английских букв и символов '<span class="tex-font-style-tt">)</span>'.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из $$$t$$$ тестовых случаев выведите «<span class="tex-font-style-tt">Yes</span>», если строка является плохой, иначе выведите «<span class="tex-font-style-tt">No</span>».</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2
))
12
gl))hf))))))
9
gege)))))
14
)aa))b))))))))
1
)
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
No
Yes
Yes
Yes
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="6d250d223a6c2497655ebeb8d6090da8"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - A - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="3427b4493a6af77e1eef101b3ce463d0fffb310d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - A - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='6d250d223a6c2497655ebeb8d6090da8'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/technocup2021"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1411%2Fproblem%2FA%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='6d250d223a6c2497655ebeb8d6090da8'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1411">Технокубок 2021 - Отборочный Раунд 3</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='6d250d223a6c2497655ebeb8d6090da8'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1411/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6d250d223a6c2497655ebeb8d6090da8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="839203"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6d250d223a6c2497655ebeb8d6090da8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="839203"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/85746" title="Технокубок 2021 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 692 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12664:12665" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/85792" title="Разбор Технокубок 2021 - Отборочный раунд 3 + Round #692 (Div. 1 + Div. 2)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12675:12676" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1411">Задачи</a></li>
<li><a
href="/contest/1411/submit">Отослать</a></li>
<li><a
href="/contest/1411/my">Мои посылки</a></li>
<li><a
href="/contest/1411/status">Статус</a></li>
<li><a
href="/contest/1411/hacks">Взломы</a></li>
<li><a
href="/contest/1411/room/1">Комната</a></li>
<li><a
href="/contest/1411/standings">Положение</a></li>
<li><a
href="/contest/1411/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="A" data-uuid="ps_1b0c0cbc283eb1d4ed556316f45bc4db686239d3">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Игровой чат</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам предстоит разработать фильтр для плохих сообщений в чате одной игры. Сообщение представляет из себя строку $$$S$$$ длины $$$n$$$, состоящую из строчных английских букв и символов '<span class="tex-font-style-tt">)</span>'. Строка считается <span class="tex-font-style-it">плохой</span>, если количество символов '<span class="tex-font-style-tt">)</span>' в конце строки превышает количество остальных символов. Например, у строки «<span class="tex-font-style-tt">)bc)))</span>» три скобки в конце, три остальных символа, и эта строка не считается плохой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано целое число $$$t$$$ — количество тестовых случаев ($$$1 \leq t \leq 100$$$). Далее дано описание $$$t$$$ тестовых случаев.</p><p>В первой строке дано число $$$n$$$ ($$$1 \leq n \leq 100$$$). Во второй строке дана строка $$$S$$$ длины $$$n$$$, состоящая из строчных английских букв и символов '<span class="tex-font-style-tt">)</span>'.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из $$$t$$$ тестовых случаев выведите «<span class="tex-font-style-tt">Yes</span>», если строка является плохой, иначе выведите «<span class="tex-font-style-tt">No</span>».</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2
))
12
gl))hf))))))
9
gege)))))
14
)aa))b))))))))
1
)
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
No
Yes
Yes
Yes
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:56</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124aba839f49d8a',t:'MTY5NjY2NjI1Ni44ODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"] | ||
1411B | 1411 | B | ru | B. Справедливые числа | <div class="problem-statement"><div class="header"><div class="title">B. Справедливые числа</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовём натуральное число <span class="tex-font-style-it">справедливым</span>, если оно делится на каждую из своих ненулевых цифр. Например, число $$$102$$$ справедливое (так как оно делится и на $$$1$$$, и на $$$2$$$), а число $$$282$$$ — нет, потому что не делится на $$$8$$$. По данному $$$n$$$ найдите минимальное $$$x$$$, такое что $$$n \leq x$$$ и $$$x$$$ — справедливое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится $$$t$$$ — количество тестовых случаев ($$$1 \leq t \leq 10^3$$$). В каждой из следующих $$$t$$$ строк по одному целому числу $$$n$$$ ($$$1 \leq n \leq 10^{18}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из $$$t$$$ тестовых случаев в новой строке выведите наименьшее справедливое число, не меньшее $$$n$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1
282
1234567890
1000000000000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
288
1234568040
1000000000000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пояснения к некоторым тестовым случаям: </p><ul> <li> В первом тестовом случае число $$$1$$$ само по себе является справедливым. </li><li> Во втором тестовом случае число $$$288$$$ — справедливое (делится и на $$$2$$$, и на $$$8$$$). Ни одно число из отрезка $$$[282, 287]$$$ не является справедливым, потому что, например, не делится на $$$8$$$. </li></ul></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="7279198ef7d64ac6fe63dcb1a15835a9"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - B - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="3427b4493a6af77e1eef101b3ce463d0fffb310d"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - B - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='7279198ef7d64ac6fe63dcb1a15835a9'> </span>
<!-- .notificationTextCleaner used in Codeforces.showAnnouncements() -->
<div class="notificationTextCleaner" style="font-size: 0"></div>
<div class="button-up" style="display: none; opacity: 0.7; width: 50px; height:100%; position: fixed; left: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 3.0rem;"><i class="icon-circle-arrow-up"></i></div>
<div class="verdictPrototypeDiv" style="display: none;"></div>
<!-- Codeforces JavaScripts. -->
<script type="text/javascript">
String.prototype.hashCode = function() {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
var queryMobile = Codeforces.queryString.mobile;
if (queryMobile === "true" || queryMobile === "false") {
Codeforces.putToStorage("useMobile", queryMobile === "true");
} else {
var useMobile = Codeforces.getFromStorage("useMobile");
if (useMobile === true || useMobile === false) {
if (useMobile != false) {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", useMobile));
}
}
}
</script>
<script type="text/javascript">
if (window.parent.frames.length > 0) {
window.stop();
}
</script>
<script type="text/javascript">
$(document).ready(function () {
(function () {
jQuery.expr[':'].containsCI = function(elem, index, match) {
return !match || !match.length || match.length < 4 || !match[3] || (
elem.textContent || elem.innerText || jQuery(elem).text() || ''
).toLowerCase().indexOf(match[3].toLowerCase()) >= 0;
}
}(jQuery));
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var csrf = Codeforces.getCsrfToken();
if (csrf) {
var data = originalOptions.data;
if (originalOptions.data !== undefined) {
if (Object.prototype.toString.call(originalOptions.data) === '[object String]') {
data = $.deparam(originalOptions.data);
}
} else {
data = {};
}
options.data = $.param($.extend(data, { csrf_token: csrf }));
}
});
window.getCodeforcesServerTime = function(callback) {
$.post("/data/time", {}, callback, "json");
}
window.updateTypography = function () {
$("div.ttypography code").addClass("tt");
$("div.ttypography pre>code").addClass("prettyprint").removeClass("tt");
$("div.ttypography table").addClass("bordertable");
prettyPrint();
}
$.ajaxSetup({ scriptCharset: "utf-8" ,contentType: "application/x-www-form-urlencoded; charset=UTF-8", headers: {
'X-Csrf-Token': Codeforces.getCsrfToken()
}});
window.updateTypography();
Codeforces.signForms();
setTimeout(function() {
$(".second-level-menu-list").lavaLamp({
fx: "backout",
speed: 700
});
}, 100);
Codeforces.countdown();
$("a[rel='photobox']").colorbox();
function showAnnouncements(json) {
//info("j=" + JSON.stringify(json));
if (json.t != "a") {
return;
}
setTimeout(function() {
Codeforces.showAnnouncements(json.d, "ru");
}, Math.random() * 500);
}
function showEventCatcherUserMessage(json) {
if (json.t == "s") {
var points = json.d[5];
var passedTestCount = json.d[7];
var judgedTestCount = json.d[8];
var verdict = preparedVerdictFormats[json.d[12]];
var verdictPrototypeDiv = $(".verdictPrototypeDiv");
verdictPrototypeDiv.html(verdict);
if (judgedTestCount != null && judgedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-judged").text(judgedTestCount);
}
if (passedTestCount != null && passedTestCount != undefined) {
verdictPrototypeDiv.find(".verdict-format-passed").text(passedTestCount);
}
if (points != null && points != undefined) {
verdictPrototypeDiv.find(".verdict-format-points").text(points);
}
Codeforces.showMessage(verdictPrototypeDiv.text());
}
}
$(".clickable-title").each(function() {
var title = $(this).attr("data-title");
if (title) {
var tmp = document.createElement("DIV");
tmp.innerHTML = title;
$(this).attr("title", tmp.textContent || tmp.innerText || "");
}
});
$(".clickable-title").click(function() {
var title = $(this).attr("data-title");
if (title) {
Codeforces.alert(title);
} else {
Codeforces.alert($(this).attr("title"));
}
}).css("position", "relative").css("bottom", "3px");
Codeforces.showDelayedMessage();
Codeforces.reformatTimes();
//Codeforces.initializePubSub();
if (window.codeforcesOptions.subscribeServerUrl) {
window.eventCatcher = new EventCatcher(
window.codeforcesOptions.subscribeServerUrl,
[
Codeforces.getGlobalChannel(),
Codeforces.getUserChannel(),
Codeforces.getUserShowMessageChannel(),
Codeforces.getContestChannel(),
Codeforces.getParticipantChannel(),
Codeforces.getTalkChannel()
]
);
if (Codeforces.getParticipantChannel()) {
window.eventCatcher.subscribe(Codeforces.getParticipantChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getContestChannel()) {
window.eventCatcher.subscribe(Codeforces.getContestChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getGlobalChannel()) {
window.eventCatcher.subscribe(Codeforces.getGlobalChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserChannel(), function(json) {
showAnnouncements(json);
});
}
if (Codeforces.getUserShowMessageChannel()) {
window.eventCatcher.subscribe(Codeforces.getUserShowMessageChannel(), function(json) {
showEventCatcherUserMessage(json);
});
}
}
Codeforces.setupContestTimes("/data/contests");
Codeforces.setupSpoilers();
Codeforces.setupTutorials("/data/problemTutorial");
});
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-743380-5']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = (document.location.protocol == 'https:' ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<div id="body">
<div class="side-bell" style="visibility: hidden; display: none; opacity: 0.7; width: 40px; position: fixed; right: 0; top: 0; cursor: pointer; text-align: center; line-height: 35px; color: #d3dbe4; font-weight: bold; font-size: 1.5rem;">
<span class="icon-stack" style="width: 100%;">
<i class="icon-circle icon-stack-base"></i>
<i class="icon-bell-alt icon-light"></i>
</span>
<br/>
<span class="side-bell__count" style="position: relative; top: -10px;"></span>
</div>
<div id="header" style="position: relative;">
<div style="float:left; max-height: 60px;">
<div><a href="/technocup2021"><img src="//assets.codeforces.com/images/technocup-logo.png"/></a></div>
</div>
<div class="lang-chooser">
<div style="text-align: right;">
<a href="?locale=en"><img src="//codeforces.org/s/36819/images/flags/24/gb.png" title="In English" alt="In English"/></a>
<a href="?locale=ru"><img src="//codeforces.org/s/36819/images/flags/24/ru.png" title="По-русски" alt="По-русски"/></a>
</div>
<div >
<a href="/enter?back=%2Fcontest%2F1411%2Fproblem%2FB%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='7279198ef7d64ac6fe63dcb1a15835a9'/>
<input class="search" name="query" data-isPlaceholder="true" value=""/>
</form>
<br style="clear: both;"/>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("input.search").focus(function () {
if ($(this).attr("data-isPlaceholder") === "true") {
$(this).val("");
$(this).removeAttr("data-isPlaceholder");
}
});
});
</script>
<br style="height: 3em; clear: both;"/>
<div style="position: relative;">
<div id="sidebar">
<div class="roundbox sidebox borderTopRound " style="">
<table class="rtable ">
<tbody>
<tr>
<th class="left" style="width:100%;"><a style="color: black" href="/contest/1411">Технокубок 2021 - Отборочный Раунд 3</a></th>
</tr>
<tr>
<td class="left bottom" colspan="1"><span class="contest-state-phase">Закончено</span></td>
</tr>
</tbody>
</table>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Дорешивание?
<div class="top-links">
</div>
</div>
<div>
<div style="margin:1em;font-size:0.8em;">
Хотите дорешать задачи? Просто зарегистрируйтесь на дорешивание.
</div>
<div style="text-align:center;margin:1em;">
<form action="" method="post"><input type='hidden' name='csrf_token' value='7279198ef7d64ac6fe63dcb1a15835a9'/>
<input type="hidden" name="action" value="registerForPractice"/>
<input type="submit" name="submit" value="Зарегистрироваться" style="padding:0 0.5em;">
</form>
</div>
</div>
</div>
<div class="roundbox sidebox ContestVirtualFrame borderTopRound " style="">
<div class="caption titled">→ Виртуальное участие <i class="sidebar-caption-icon las la-angle-down"></i>
<div class="top-links">
</div>
</div>
<div style=" "
data-page-url="/data/sidebarFrames"
>
<div style="margin:1em;font-size:0.8em;">
Виртуальное соревнование – это способ прорешать прошедшее соревнование в режиме, максимально близком к участию во время его проведения. Поддерживается только ICPC режим для виртуальных соревнований.
Если вы раньше видели эти задачи,
виртуальное соревнование не для вас – решайте эти задачи в архиве.
Если вы хотите просто дорешать задачи, виртуальное соревнование не для вас – решайте эти задачи в архиве.
Запрещается использовать чужой код, читать разборы задач и общаться по содержанию соревнования с кем-либо.
</div>
<div style="text-align:center;margin:1em;">
<form action="/contest/1411/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1000
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7279198ef7d64ac6fe63dcb1a15835a9'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="839204"/>
<input name="tagName" type="hidden" value=""/>
</form>
<form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7279198ef7d64ac6fe63dcb1a15835a9'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="839204"/>
<input name="tagName" type="hidden" value=""/>
</form>
<script type="text/javascript">
$(".tag-box img").click(function () {
var tagName = $(this).attr("value");
Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () {
$("#removeTagForm input[name=tagName]").val(tagName);
$("#removeTagForm").submit();
}, function () {
}, "Да", "Нет");
});
$("#addTagLink").click(function () {
$(this).hide();
$("#addTagLabel").show();
return false;
});
$("#addTagSelect").change(function () {
var tagName = $(this).val();
if (tagName === "") {
$("#addTagLabel").hide();
$("#addTagLink").show();
} else {
$("#addTagForm input[name=tagName]").val(tagName);
$("#addTagForm").submit();
}
});
</script>
<style type="text/css">
#new-resource-form tr td {
padding-top: 0.5em;
}
#new-resource-form input:not([type="submit"]) {
font-size: 0.8em;
}
#new-resource-form select {
font-size: 0.8em;
}
.new-resource-error {
font-size: 0.8em;
}
.resource-locale {
color: #666;
font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Liberation Mono", "Nimbus Mono L", Monaco, "Courier New", Courier, monospace;
}
</style>
<div class="roundbox sidebox sidebar-menu borderTopRound " style="">
<div class="caption titled">→ Материалы соревнования
<div class="top-links">
</div>
</div>
<ul>
<li>
<span>
<a href="/blog/entry/85746" title="Технокубок 2021 — Отборочный Раунд 3 (и открытые рейтинговые раунды Codeforces Round 692 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12664:12665" resourceName="Анонс"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
<li>
<span>
<a href="/blog/entry/85792" title="Разбор Технокубок 2021 - Отборочный раунд 3 + Round #692 (Div. 1 + Div. 2)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12675:12676" resourceName="Разбор задач"
resourceManual="true" src="//codeforces.org/s/36819/images/icons/close-10x10.png"
style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/>
</span>
<div style="clear: both;"></div>
</li>
</ul>
</div></div>
<div id="pageContent" class="content-with-sidebar">
<div class="second-level-menu">
<ul class="second-level-menu-list">
<li class="current selectedLava"><a
href="/contest/1411">Задачи</a></li>
<li><a
href="/contest/1411/submit">Отослать</a></li>
<li><a
href="/contest/1411/my">Мои посылки</a></li>
<li><a
href="/contest/1411/status">Статус</a></li>
<li><a
href="/contest/1411/hacks">Взломы</a></li>
<li><a
href="/contest/1411/room/1">Комната</a></li>
<li><a
href="/contest/1411/standings">Положение</a></li>
<li><a
href="/contest/1411/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="B" data-uuid="ps_6149ea2c282aca01fc718021b88ea3efaf0dac83">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Справедливые числа</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Назовём натуральное число <span class="tex-font-style-it">справедливым</span>, если оно делится на каждую из своих ненулевых цифр. Например, число $$$102$$$ справедливое (так как оно делится и на $$$1$$$, и на $$$2$$$), а число $$$282$$$ — нет, потому что не делится на $$$8$$$. По данному $$$n$$$ найдите минимальное $$$x$$$, такое что $$$n \leq x$$$ и $$$x$$$ — справедливое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится $$$t$$$ — количество тестовых случаев ($$$1 \leq t \leq 10^3$$$). В каждой из следующих $$$t$$$ строк по одному целому числу $$$n$$$ ($$$1 \leq n \leq 10^{18}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из $$$t$$$ тестовых случаев в новой строке выведите наименьшее справедливое число, не меньшее $$$n$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1
282
1234567890
1000000000000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
288
1234568040
1000000000000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пояснения к некоторым тестовым случаям: </p><ul> <li> В первом тестовом случае число $$$1$$$ само по себе является справедливым. </li><li> Во втором тестовом случае число $$$288$$$ — справедливое (делится и на $$$2$$$, и на $$$8$$$). Ни одно число из отрезка $$$[282, 287]$$$ не является справедливым, потому что, например, не делится на $$$8$$$. </li></ul></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:10:58</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124abb13dac7b43',t:'MTY5NjY2NjI1OC4yMzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1000"] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.