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
|
---|---|---|---|---|---|---|---|---|---|---|
1446D1 | 1446 | D1 | ru | D1. Задача о частотах (простая версия) | <div class="problem-statement"><div class="header"><div class="title">D1. Задача о частотах (простая версия)</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>Вам дан массив $$$[a_1, a_2, \dots, a_n]$$$. </p><p>Ваша цель — найти длину самого длинного подмассива этого массива такого, в котором наиболее часто встречающееся значение <span class="tex-font-style-bf">не</span> единственно. Другими словами, вы ищете подмассив такой, что если в этом подмассиве наиболее часто встречающееся значение встречается $$$f$$$ раз, то как минимум $$$2$$$ разных значения должны встречаться в нем ровно $$$f$$$ раз.</p><p>Массив $$$c$$$ является подмассивом массива $$$d$$$, если $$$c$$$ может быть получен из $$$d$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — длину массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le min(n, 100)$$$) — элементы массива.</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
1 1 2 2 3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 1 1 5 4 1 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подмассив $$$[1, 1, 2, 2, 3, 3]$$$ хороший, но $$$[1, 1, 2, 2, 3, 3, 3]$$$ нет: во втором число $$$3$$$ встречается $$$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="90cc2238ce6c3a57e4f7de71f4182a4e"/>
<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="Задача - D1 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="44cb692c6a24e8e464e5021070fc7ec89a7c9686"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D1 - 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='90cc2238ce6c3a57e4f7de71f4182a4e'> </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%2F1446%2Fproblem%2FD1%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='90cc2238ce6c3a57e4f7de71f4182a4e'/>
<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/1446">Codeforces Round 683 (Div. 1, by Meet IT)</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='90cc2238ce6c3a57e4f7de71f4182a4e'/>
<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/1446/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="Сложность">
*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='90cc2238ce6c3a57e4f7de71f4182a4e'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797258"/>
<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='90cc2238ce6c3a57e4f7de71f4182a4e'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797258"/>
<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/83967" title="Codeforces Round #683 by Meet IT (Div1, Div2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12349" resourceName="Codeforces Round #683 by Meet IT (Div1, Div2)"
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/82067" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12350" resourceName="E"
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/1446">Задачи</a></li>
<li><a
href="/contest/1446/submit">Отослать</a></li>
<li><a
href="/contest/1446/my">Мои посылки</a></li>
<li><a
href="/contest/1446/status">Статус</a></li>
<li><a
href="/contest/1446/hacks">Взломы</a></li>
<li><a
href="/contest/1446/room/1">Комната</a></li>
<li><a
href="/contest/1446/standings">Положение</a></li>
<li><a
href="/contest/1446/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="D1" data-uuid="ps_c000738b1165cdad39a4ff7a79902bc067468e68">
<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">D1. Задача о частотах (простая версия)</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>Вам дан массив $$$[a_1, a_2, \dots, a_n]$$$. </p><p>Ваша цель — найти длину самого длинного подмассива этого массива такого, в котором наиболее часто встречающееся значение <span class="tex-font-style-bf">не</span> единственно. Другими словами, вы ищете подмассив такой, что если в этом подмассиве наиболее часто встречающееся значение встречается $$$f$$$ раз, то как минимум $$$2$$$ разных значения должны встречаться в нем ровно $$$f$$$ раз.</p><p>Массив $$$c$$$ является подмассивом массива $$$d$$$, если $$$c$$$ может быть получен из $$$d$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — длину массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le min(n, 100)$$$) — элементы массива.</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
1 1 2 2 3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 1 1 5 4 1 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подмассив $$$[1, 1, 2, 2, 3, 3]$$$ хороший, но $$$[1, 1, 2, 2, 3, 3, 3]$$$ нет: во втором число $$$3$$$ встречается $$$3$$$ раза, и ни один другой элемент не встречается $$$3$$$ раза.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D1]");
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:16: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:'8124b340de701411',t:'MTY5NjY2NjU2Ny45MDMwMDA='};_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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2600"] | ||
1446D2 | 1446 | D2 | ru | D2. Задача о частотах (сложная версия) | <div class="problem-statement"><div class="header"><div class="title">D2. Задача о частотах (сложная версия)</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>Вам дан массив $$$[a_1, a_2, \dots, a_n]$$$. </p><p>Ваша цель — найти длину самого длинного подмассива этого массива такого, в котором наиболее часто встречающееся значение <span class="tex-font-style-bf">не</span> единственно. Другими словами, вы ищете подмассив такой, что если в этом подмассиве наиболее часто встречающееся значение встречается $$$f$$$ раз, то как минимум $$$2$$$ разные значения должны встречаться в нем ровно $$$f$$$ раз.</p><p>Массив $$$c$$$ является подмассивом массива $$$d$$$, если $$$c$$$ может быть получен из $$$d$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — длину массива.</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>Необходимо вывести ровно одно целое число — длину самого длинного подмассива массива, наиболее частое значение которого не является единственным. Если такого подмассива нет, выведите $$$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
1 1 2 2 3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 1 1 5 4 1 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подмассив $$$[1, 1, 2, 2, 3, 3]$$$ хороший, но $$$[1, 1, 2, 2, 3, 3, 3]$$$ нет: во втором число $$$3$$$ встречается $$$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="c4a97c67351826e07cc5ecf077908d97"/>
<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="Задача - D2 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="44cb692c6a24e8e464e5021070fc7ec89a7c9686"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - D2 - 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='c4a97c67351826e07cc5ecf077908d97'> </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%2F1446%2Fproblem%2FD2%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='c4a97c67351826e07cc5ecf077908d97'/>
<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/1446">Codeforces Round 683 (Div. 1, by Meet IT)</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='c4a97c67351826e07cc5ecf077908d97'/>
<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/1446/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="Сложность">
*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='c4a97c67351826e07cc5ecf077908d97'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797259"/>
<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='c4a97c67351826e07cc5ecf077908d97'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797259"/>
<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/83967" title="Codeforces Round #683 by Meet IT (Div1, Div2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12349" resourceName="Codeforces Round #683 by Meet IT (Div1, Div2)"
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/82067" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12350" resourceName="E"
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/1446">Задачи</a></li>
<li><a
href="/contest/1446/submit">Отослать</a></li>
<li><a
href="/contest/1446/my">Мои посылки</a></li>
<li><a
href="/contest/1446/status">Статус</a></li>
<li><a
href="/contest/1446/hacks">Взломы</a></li>
<li><a
href="/contest/1446/room/1">Комната</a></li>
<li><a
href="/contest/1446/standings">Положение</a></li>
<li><a
href="/contest/1446/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="D2" data-uuid="ps_4e14351f2bb322d254ebd77d64f6783db284abd7">
<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">D2. Задача о частотах (сложная версия)</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>Вам дан массив $$$[a_1, a_2, \dots, a_n]$$$. </p><p>Ваша цель — найти длину самого длинного подмассива этого массива такого, в котором наиболее часто встречающееся значение <span class="tex-font-style-bf">не</span> единственно. Другими словами, вы ищете подмассив такой, что если в этом подмассиве наиболее часто встречающееся значение встречается $$$f$$$ раз, то как минимум $$$2$$$ разные значения должны встречаться в нем ровно $$$f$$$ раз.</p><p>Массив $$$c$$$ является подмассивом массива $$$d$$$, если $$$c$$$ может быть получен из $$$d$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — длину массива.</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>Необходимо вывести ровно одно целое число — длину самого длинного подмассива массива, наиболее частое значение которого не является единственным. Если такого подмассива нет, выведите $$$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
1 1 2 2 3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 1 1 5 4 1 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подмассив $$$[1, 1, 2, 2, 3, 3]$$$ хороший, но $$$[1, 1, 2, 2, 3, 3, 3]$$$ нет: во втором число $$$3$$$ встречается $$$3$$$ раза, и ни один другой элемент не встречается $$$3$$$ раза.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D2]");
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:16: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:'8124b34909b19d92',t:'MTY5NjY2NjU2OS4yNTUwMDA='};_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", "\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", "\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", "*3000"] | ||
1446E | 1446 | 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 секунды</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><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d71696fb5b0ffb3765ab500f11af61727bf21193.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Две клетки являются соседними, если у них есть общая сторона. Поэтому у каждой ячейки ($$$x$$$, $$$y$$$) есть ровно три соседа: </p><ul> <li> ($$$x+1$$$, $$$y$$$) </li><li> ($$$x-1$$$, $$$y$$$) </li><li> ($$$x+1$$$, $$$y-1$$$), если $$$x$$$ четно и ($$$x-1$$$, $$$y+1$$$) в противном случае. </li></ul> <p>Изначально некоторые ячейки заражены, все остальные здоровы. Начинается процесс выздоровления. Каждую секунду для <span class="tex-font-style-bf">ровно одной</span> ячейки (хотя может быть несколько ячеек, которые могут изменить свое состояние) происходит одно из следующих событий:</p><ul> <li> Здоровая клетка с по крайней мере $$$2$$$ зараженными соседями становится зараженной. </li><li> Зараженная клетка с по крайней мере $$$2$$$ здоровыми соседями становится здоровой. </li></ul><p>Если такой клетки нет, то процесс выздоровления останавливается. Пациент считается выздоровевшим, если процесс выздоровления остановлен и все клетки здоровы.</p><p>Нас интересует <span class="tex-font-style-bf">худший</span> сценарий: возможно ли, что пациент никогда не выздоровеет, или, если это невозможно, какова максимально возможная продолжительность процесса выздоровления?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$n$$$ $$$(1 \leq n \leq 250000)$$$ — количество зараженных ячеек. </p><p>В $$$i$$$-й из следующих $$$n$$$ строк содержится два разделенных пробелами целых числа $$$x_i$$$ и $$$y_i$$$ $$$(0 \leq x_i, y_i < 500)$$$, что означает, что ячейка $$$(x_i, y_i)$$$ заражена. Все ячейки $$$(x_i, y_i)$$$ попарно различны, а все остальные клетки считаются здоровыми. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если может случиться так, что организм никогда полностью не выздоровеет после болезни, выведите <span class="tex-font-style-tt">SICK</span>. В противном случае выведите <span class="tex-font-style-tt">RECOVERED</span> и в следующей строке целое число $$$k$$$ — максимально возможную продолжительность процесса выздоровления, по модулю $$$998244353$$$. </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 0
1 0
2 0
0 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
RECOVERED
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 0
3 0
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
SICK
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера следующие рисунки описывают самый длительный возможный процесс восстановления. Можно доказать, что нет периодов восстановления длиной $$$5$$$ и более, и что организм всегда восстанавливается.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/4304fadee8c661b22d927b71c678b25bd460c1e6.png" style="max-width: 100.0%;max-height: 100.0%;"/> $$$\hspace{40pt} \downarrow$$$ <img class="tex-graphics" src="https://espresso.codeforces.com/21514f93fd2b06586e1ba1ef6cc8c69410535449.png" style="max-width: 100.0%;max-height: 100.0%;"/> $$$\hspace{40pt} \downarrow$$$ <img class="tex-graphics" src="https://espresso.codeforces.com/931a4509a081717d40280e678fd458f5e8985cfd.png" style="max-width: 100.0%;max-height: 100.0%;"/> $$$\hspace{40pt} \downarrow$$$ <img class="tex-graphics" src="https://espresso.codeforces.com/b4e9b2eebad32bf9f83186b7ebfe0f4ca686a5e3.png" style="max-width: 100.0%;max-height: 100.0%;"/> $$$\hspace{40pt} \downarrow$$$</p><p>$$$\hspace{15pt}$$$ RECOVERED</p><p>Для второго теста можно заразить клетки $$$(2, 0)$$$, $$$(2, 1)$$$, $$$(0, 1)$$$. После этого ни одна клетка не может изменить свое состояние, поэтому ответ <span class="tex-font-style-tt">SICK</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="0db426aac44457c1e171d7664f695ddb"/>
<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="44cb692c6a24e8e464e5021070fc7ec89a7c9686"/>
<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='0db426aac44457c1e171d7664f695ddb'> </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%2F1446%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='0db426aac44457c1e171d7664f695ddb'/>
<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/1446">Codeforces Round 683 (Div. 1, by Meet IT)</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='0db426aac44457c1e171d7664f695ddb'/>
<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/1446/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="Сложность">
*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='0db426aac44457c1e171d7664f695ddb'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797260"/>
<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='0db426aac44457c1e171d7664f695ddb'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797260"/>
<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/83967" title="Codeforces Round #683 by Meet IT (Div1, Div2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12349" resourceName="Codeforces Round #683 by Meet IT (Div1, Div2)"
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/82067" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12350" resourceName="E"
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/1446">Задачи</a></li>
<li><a
href="/contest/1446/submit">Отослать</a></li>
<li><a
href="/contest/1446/my">Мои посылки</a></li>
<li><a
href="/contest/1446/status">Статус</a></li>
<li><a
href="/contest/1446/hacks">Взломы</a></li>
<li><a
href="/contest/1446/room/1">Комната</a></li>
<li><a
href="/contest/1446/standings">Положение</a></li>
<li><a
href="/contest/1446/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_0c68118998512cfa9a8712e7cff1b76de69dad1f">
<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 секунды</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><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d71696fb5b0ffb3765ab500f11af61727bf21193.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Две клетки являются соседними, если у них есть общая сторона. Поэтому у каждой ячейки ($$$x$$$, $$$y$$$) есть ровно три соседа: </p><ul> <li> ($$$x+1$$$, $$$y$$$) </li><li> ($$$x-1$$$, $$$y$$$) </li><li> ($$$x+1$$$, $$$y-1$$$), если $$$x$$$ четно и ($$$x-1$$$, $$$y+1$$$) в противном случае. </li></ul> <p>Изначально некоторые ячейки заражены, все остальные здоровы. Начинается процесс выздоровления. Каждую секунду для <span class="tex-font-style-bf">ровно одной</span> ячейки (хотя может быть несколько ячеек, которые могут изменить свое состояние) происходит одно из следующих событий:</p><ul> <li> Здоровая клетка с по крайней мере $$$2$$$ зараженными соседями становится зараженной. </li><li> Зараженная клетка с по крайней мере $$$2$$$ здоровыми соседями становится здоровой. </li></ul><p>Если такой клетки нет, то процесс выздоровления останавливается. Пациент считается выздоровевшим, если процесс выздоровления остановлен и все клетки здоровы.</p><p>Нас интересует <span class="tex-font-style-bf">худший</span> сценарий: возможно ли, что пациент никогда не выздоровеет, или, если это невозможно, какова максимально возможная продолжительность процесса выздоровления?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$n$$$ $$$(1 \leq n \leq 250000)$$$ — количество зараженных ячеек. </p><p>В $$$i$$$-й из следующих $$$n$$$ строк содержится два разделенных пробелами целых числа $$$x_i$$$ и $$$y_i$$$ $$$(0 \leq x_i, y_i < 500)$$$, что означает, что ячейка $$$(x_i, y_i)$$$ заражена. Все ячейки $$$(x_i, y_i)$$$ попарно различны, а все остальные клетки считаются здоровыми. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если может случиться так, что организм никогда полностью не выздоровеет после болезни, выведите <span class="tex-font-style-tt">SICK</span>. В противном случае выведите <span class="tex-font-style-tt">RECOVERED</span> и в следующей строке целое число $$$k$$$ — максимально возможную продолжительность процесса выздоровления, по модулю $$$998244353$$$. </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 0
1 0
2 0
0 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
RECOVERED
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 0
3 0
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
SICK
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого примера следующие рисунки описывают самый длительный возможный процесс восстановления. Можно доказать, что нет периодов восстановления длиной $$$5$$$ и более, и что организм всегда восстанавливается.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/4304fadee8c661b22d927b71c678b25bd460c1e6.png" style="max-width: 100.0%;max-height: 100.0%;" /> $$$\hspace{40pt} \downarrow$$$ <img class="tex-graphics" src="https://espresso.codeforces.com/21514f93fd2b06586e1ba1ef6cc8c69410535449.png" style="max-width: 100.0%;max-height: 100.0%;" /> $$$\hspace{40pt} \downarrow$$$ <img class="tex-graphics" src="https://espresso.codeforces.com/931a4509a081717d40280e678fd458f5e8985cfd.png" style="max-width: 100.0%;max-height: 100.0%;" /> $$$\hspace{40pt} \downarrow$$$ <img class="tex-graphics" src="https://espresso.codeforces.com/b4e9b2eebad32bf9f83186b7ebfe0f4ca686a5e3.png" style="max-width: 100.0%;max-height: 100.0%;" /> $$$\hspace{40pt} \downarrow$$$</p><p>$$$\hspace{15pt}$$$ RECOVERED</p><p>Для второго теста можно заразить клетки $$$(2, 0)$$$, $$$(2, 1)$$$, $$$(0, 1)$$$. После этого ни одна клетка не может изменить свое состояние, поэтому ответ <span class="tex-font-style-tt">SICK</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:16: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:'8124b3517da83aa1',t:'MTY5NjY2NjU3MC42MjEwMDA='};_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\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"] | ["\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", "*3500"] | ||
1446F | 1446 | F | ru | F. Расстояние до прямой | <div class="problem-statement"><div class="header"><div class="title">F. Расстояние до прямой</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7.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>Вам даны целое число $$$k$$$ и $$$n$$$ попарно различных точек с целочисленными координатами на евклидовой плоскости, $$$i$$$-я точка имеет координаты $$$(x_i, y_i)$$$.</p><p>Рассмотрим список всех $$$\frac{n(n - 1)}{2}$$$ пар точек $$$((x_i, y_i), (x_j, y_j))$$$ ($$$1 \le i < j \le n$$$). Для каждой такой пары выпишем расстояние от прямой, проходящей через эти две точки, до начала координат $$$(0, 0)$$$.</p><p>Ваша задача — вычислить $$$k$$$-е наименьшее число среди всех этих расстояний.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le k \le \frac{n(n - 1)}{2}$$$).</p><p>В $$$i$$$-й из следующих строк $$$n$$$ находятся два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — координаты $$$i$$$-й точки. Гарантируется, что все заданные точки попарно различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести одно число — $$$k$$$-е наименьшее расстояние до начала координат. Ваш ответ будет считаться правильным, если его абсолютная или относительная ошибка не превосходит $$$10^{-6}$$$.</p><p>Формально, пусть ваш ответ равен $$$a$$$, а ответ жюри равен $$$b$$$. Ваш ответ будет зачтен, если и только если $$$\frac{|a - b|}{\max{(1, |b|)}} \le 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>
4 3
2 1
-2 -1
0 -1
-2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0.707106780737
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Есть $$$6$$$ пар точек: </p><ul> <li> Прямая $$$1-2$$$ : расстояние $$$0$$$ от начала координат </li><li> Прямая $$$1-3$$$ : расстояние $$$\frac{\sqrt{2}}{2} \approx 0.707106781$$$ от начала координат </li><li> Прямая $$$1-4$$$ : расстояние $$$2$$$ от начала координат </li><li> Прямая $$$2-3$$$ : расстояние $$$1$$$ от начала координат </li><li> Прямая $$$2-4$$$ : расстояние $$$2$$$ от начала координат </li><li> Прямая $$$3-4$$$ : расстояние $$$\frac{2}{\sqrt{29}} \approx 0.371390676$$$ от начала координат </li></ul> Третье по возрастанию расстояние среди них составляет примерно $$$0.707106781$$$.</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="db3307932ee663fb2d372f450c9e60a4"/>
<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="44cb692c6a24e8e464e5021070fc7ec89a7c9686"/>
<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='db3307932ee663fb2d372f450c9e60a4'> </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%2F1446%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='db3307932ee663fb2d372f450c9e60a4'/>
<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/1446">Codeforces Round 683 (Div. 1, by Meet IT)</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='db3307932ee663fb2d372f450c9e60a4'/>
<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/1446/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='db3307932ee663fb2d372f450c9e60a4'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797261"/>
<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='db3307932ee663fb2d372f450c9e60a4'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797261"/>
<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/83967" title="Codeforces Round #683 by Meet IT (Div1, Div2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12349" resourceName="Codeforces Round #683 by Meet IT (Div1, Div2)"
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/82067" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12350" resourceName="E"
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/1446">Задачи</a></li>
<li><a
href="/contest/1446/submit">Отослать</a></li>
<li><a
href="/contest/1446/my">Мои посылки</a></li>
<li><a
href="/contest/1446/status">Статус</a></li>
<li><a
href="/contest/1446/hacks">Взломы</a></li>
<li><a
href="/contest/1446/room/1">Комната</a></li>
<li><a
href="/contest/1446/standings">Положение</a></li>
<li><a
href="/contest/1446/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_d16d8f5e539f427d8d0585f35542e706ac13f28a">
<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>7.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>Вам даны целое число $$$k$$$ и $$$n$$$ попарно различных точек с целочисленными координатами на евклидовой плоскости, $$$i$$$-я точка имеет координаты $$$(x_i, y_i)$$$.</p><p>Рассмотрим список всех $$$\frac{n(n - 1)}{2}$$$ пар точек $$$((x_i, y_i), (x_j, y_j))$$$ ($$$1 \le i < j \le n$$$). Для каждой такой пары выпишем расстояние от прямой, проходящей через эти две точки, до начала координат $$$(0, 0)$$$.</p><p>Ваша задача — вычислить $$$k$$$-е наименьшее число среди всех этих расстояний.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le k \le \frac{n(n - 1)}{2}$$$).</p><p>В $$$i$$$-й из следующих строк $$$n$$$ находятся два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$-10^4 \le x_i, y_i \le 10^4$$$) — координаты $$$i$$$-й точки. Гарантируется, что все заданные точки попарно различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести одно число — $$$k$$$-е наименьшее расстояние до начала координат. Ваш ответ будет считаться правильным, если его абсолютная или относительная ошибка не превосходит $$$10^{-6}$$$.</p><p>Формально, пусть ваш ответ равен $$$a$$$, а ответ жюри равен $$$b$$$. Ваш ответ будет зачтен, если и только если $$$\frac{|a - b|}{\max{(1, |b|)}} \le 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>
4 3
2 1
-2 -1
0 -1
-2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0.707106780737
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Есть $$$6$$$ пар точек: </p><ul> <li> Прямая $$$1-2$$$ : расстояние $$$0$$$ от начала координат </li><li> Прямая $$$1-3$$$ : расстояние $$$\frac{\sqrt{2}}{2} \approx 0.707106781$$$ от начала координат </li><li> Прямая $$$1-4$$$ : расстояние $$$2$$$ от начала координат </li><li> Прямая $$$2-3$$$ : расстояние $$$1$$$ от начала координат </li><li> Прямая $$$2-4$$$ : расстояние $$$2$$$ от начала координат </li><li> Прямая $$$3-4$$$ : расстояние $$$\frac{2}{\sqrt{29}} \approx 0.371390676$$$ от начала координат </li></ul> Третье по возрастанию расстояние среди них составляет примерно $$$0.707106781$$$.</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:16: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:'8124b35a0cfb1628',t:'MTY5NjY2NjU3MS45NTkwMDA='};_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", "\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", "\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3200"] | ||
1447A | 1447 | 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$$$ пакетов с конфетами, изначально $$$i$$$-й пакет содержит $$$i$$$ конфет. Вы хотите, чтобы в конце все пакеты содержали одинаковое количество конфет. </p><p>Чтобы добиться этого, вы:</p><ul><li> <p>Выберете $$$m$$$, удовлетворяющее $$$1 \le m \le 1000$$$.</p></li><li><p>Выполните $$$m$$$ операций. В $$$j$$$-ю операцию вы выберете один из пакетов и добавите по $$$j$$$ конфет во все пакеты, кроме выбранного.</p></li></ul><p>Ваша цель — найти подходящую последовательность операций, после которой все пакеты будут содержать равное количество конфет. </p><ul><li><p>Можно доказать, что при заданных ограничениях такая последовательность всегда существует.</p></li><li><p>Вы <span class="tex-font-style-bf">не</span> должны минимизировать $$$m$$$.</p></li><li><p>Если есть несколько подходящих последовательностей, вы можете вывести <span class="tex-font-style-bf">любую</span>.</p></li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных.</p><p>В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая и единственная строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \le n\le 100$$$). </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки с вашим ответом. </p><p>В первой строке выведите $$$m$$$ ($$$1\le m \le 1000$$$) — количество операций, которые вы хотите выполнить. </p><p>Во второй строке выведите $$$m$$$ положительных целых чисел $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$), где $$$a_j$$$ — это номер пакета, который вы выбрали в $$$j$$$-ю операцию.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
2
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
5
3 3 3 1 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, добавив $$$1$$$ конфету во все мешки кроме второго, получаем конфигурацию с $$$[2, 2]$$$ конфетами.</p><p>Во втором наборе входных данных сначала вы используете первые три операции, чтобы добавить $$$1+2+3=6$$$ конфет в сумме к каждому мешку кроме третьего, что дает вам $$$[7, 8, 3]$$$. После этого вы добавляете $$$4$$$ конфеты во второй и третий мешки, таким образом получая $$$[7, 12, 7]$$$, а потом по $$$5$$$ конфет в первый и третий мешки — в результате получая $$$[12, 12, 12]$$$.</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="e59c2768eb3a7c7cb58ec995ab90fe7f"/>
<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="6b61ecdb9d4aba92dc230e2a67468230909b70f9"/>
<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='e59c2768eb3a7c7cb58ec995ab90fe7f'> </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%2F1447%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='e59c2768eb3a7c7cb58ec995ab90fe7f'/>
<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/1447">Codeforces Round 683 (Div. 2, by Meet IT)</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='e59c2768eb3a7c7cb58ec995ab90fe7f'/>
<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/1447/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='e59c2768eb3a7c7cb58ec995ab90fe7f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797262"/>
<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='e59c2768eb3a7c7cb58ec995ab90fe7f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797262"/>
<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/82067" title="Meet IT Codeforces Round Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12351" resourceName="Meet IT Codeforces Round 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/1447">Задачи</a></li>
<li><a
href="/contest/1447/submit">Отослать</a></li>
<li><a
href="/contest/1447/my">Мои посылки</a></li>
<li><a
href="/contest/1447/status">Статус</a></li>
<li><a
href="/contest/1447/hacks">Взломы</a></li>
<li><a
href="/contest/1447/room/1">Комната</a></li>
<li><a
href="/contest/1447/standings">Положение</a></li>
<li><a
href="/contest/1447/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_42554d3640eab30f719c411e4bf4e759277e5b35">
<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$$$ пакетов с конфетами, изначально $$$i$$$-й пакет содержит $$$i$$$ конфет. Вы хотите, чтобы в конце все пакеты содержали одинаковое количество конфет. </p><p>Чтобы добиться этого, вы:</p><ul><li> <p>Выберете $$$m$$$, удовлетворяющее $$$1 \le m \le 1000$$$.</p></li><li><p>Выполните $$$m$$$ операций. В $$$j$$$-ю операцию вы выберете один из пакетов и добавите по $$$j$$$ конфет во все пакеты, кроме выбранного.</p></li></ul><p>Ваша цель — найти подходящую последовательность операций, после которой все пакеты будут содержать равное количество конфет. </p><ul><li><p>Можно доказать, что при заданных ограничениях такая последовательность всегда существует.</p></li><li><p>Вы <span class="tex-font-style-bf">не</span> должны минимизировать $$$m$$$.</p></li><li><p>Если есть несколько подходящих последовательностей, вы можете вывести <span class="tex-font-style-bf">любую</span>.</p></li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных.</p><p>В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая и единственная строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$2 \le n\le 100$$$). </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите две строки с вашим ответом. </p><p>В первой строке выведите $$$m$$$ ($$$1\le m \le 1000$$$) — количество операций, которые вы хотите выполнить. </p><p>Во второй строке выведите $$$m$$$ положительных целых чисел $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$), где $$$a_j$$$ — это номер пакета, который вы выбрали в $$$j$$$-ю операцию.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
2
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
5
3 3 3 1 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, добавив $$$1$$$ конфету во все мешки кроме второго, получаем конфигурацию с $$$[2, 2]$$$ конфетами.</p><p>Во втором наборе входных данных сначала вы используете первые три операции, чтобы добавить $$$1+2+3=6$$$ конфет в сумме к каждому мешку кроме третьего, что дает вам $$$[7, 8, 3]$$$. После этого вы добавляете $$$4$$$ конфеты во второй и третий мешки, таким образом получая $$$[7, 12, 7]$$$, а потом по $$$5$$$ конфет в первый и третий мешки — в результате получая $$$[12, 12, 12]$$$.</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:16: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:'8124b362685016fe',t:'MTY5NjY2NjU3My4zNDYwMDA='};_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", "*800"] | ||
1447B | 1447 | 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$$$ строками и $$$m$$$ столбцами. В ячейке, расположенной на $$$i$$$-й строке сверху и $$$j$$$-м столбце слева, записано значение $$$a_{ij}$$$.</p><p>Вы можете выполнить следующую операцию любое количество раз (возможно, ноль):</p><ul> <li> Выберите любые две соседние ячейки и умножьте значения в них на $$$-1$$$. Две ячейки называются соседними, если они имеют общую сторону. </li></ul><p>Обратите внимание, что одну и ту же ячейку можно использовать несколько раз при различных операциях.</p><p>Вас интересует $$$X$$$, <span class="tex-font-style-bf">сумма</span> всех чисел в сетке. </p><p>Какое максимально возможное $$$X$$$ вы можете получить с помощью данных операций?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$,$$$m$$$ ($$$2 \le n$$$, $$$m \le 10$$$). </p><p>Каждая из следующих $$$n$$$ строк содержит по $$$m$$$ целых чисел, $$$j$$$-й элемент в $$$i$$$-й строке — $$$a_{ij}$$$ ($$$-100\leq a_{ij}\le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое $$$X$$$ — максимально возможную сумму всех значений в сетке после применения операции столько раз, сколько вам нужно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
2 2
-1 1
1 1
3 4
0 -1 -2 -3
-1 -2 -3 -4
-2 -3 -4 -5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
30
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных всегда будет как минимум одна $$$-1$$$, так что ответ равен $$$2$$$. </p><p>Во втором наборе входных данных можно шесть раз использовать операцию для элементов, соседних по горизонтали, и сделать все числа неотрицательными. Так что ответ: $$$2\times 1 + 3\times2 + 3\times 3 + 2\times 4 + 1\times 5 = 30$$$.</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="68bdd5002eba27ffe20f69358989235f"/>
<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="6b61ecdb9d4aba92dc230e2a67468230909b70f9"/>
<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='68bdd5002eba27ffe20f69358989235f'> </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%2F1447%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='68bdd5002eba27ffe20f69358989235f'/>
<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/1447">Codeforces Round 683 (Div. 2, by Meet IT)</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='68bdd5002eba27ffe20f69358989235f'/>
<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/1447/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='68bdd5002eba27ffe20f69358989235f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797263"/>
<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='68bdd5002eba27ffe20f69358989235f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797263"/>
<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/82067" title="Meet IT Codeforces Round Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12351" resourceName="Meet IT Codeforces Round 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/1447">Задачи</a></li>
<li><a
href="/contest/1447/submit">Отослать</a></li>
<li><a
href="/contest/1447/my">Мои посылки</a></li>
<li><a
href="/contest/1447/status">Статус</a></li>
<li><a
href="/contest/1447/hacks">Взломы</a></li>
<li><a
href="/contest/1447/room/1">Комната</a></li>
<li><a
href="/contest/1447/standings">Положение</a></li>
<li><a
href="/contest/1447/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_61f1cc4e1b7d0161f26e5aaf68bfaba7d3a4cad8">
<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$$$ строками и $$$m$$$ столбцами. В ячейке, расположенной на $$$i$$$-й строке сверху и $$$j$$$-м столбце слева, записано значение $$$a_{ij}$$$.</p><p>Вы можете выполнить следующую операцию любое количество раз (возможно, ноль):</p><ul> <li> Выберите любые две соседние ячейки и умножьте значения в них на $$$-1$$$. Две ячейки называются соседними, если они имеют общую сторону. </li></ul><p>Обратите внимание, что одну и ту же ячейку можно использовать несколько раз при различных операциях.</p><p>Вас интересует $$$X$$$, <span class="tex-font-style-bf">сумма</span> всех чисел в сетке. </p><p>Какое максимально возможное $$$X$$$ вы можете получить с помощью данных операций?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит несколько наборов входных данных. В первой строке указано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$,$$$m$$$ ($$$2 \le n$$$, $$$m \le 10$$$). </p><p>Каждая из следующих $$$n$$$ строк содержит по $$$m$$$ целых чисел, $$$j$$$-й элемент в $$$i$$$-й строке — $$$a_{ij}$$$ ($$$-100\leq a_{ij}\le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое $$$X$$$ — максимально возможную сумму всех значений в сетке после применения операции столько раз, сколько вам нужно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
2 2
-1 1
1 1
3 4
0 -1 -2 -3
-1 -2 -3 -4
-2 -3 -4 -5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
30
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных всегда будет как минимум одна $$$-1$$$, так что ответ равен $$$2$$$. </p><p>Во втором наборе входных данных можно шесть раз использовать операцию для элементов, соседних по горизонтали, и сделать все числа неотрицательными. Так что ответ: $$$2\times 1 + 3\times2 + 3\times 3 + 2\times 4 + 1\times 5 = 30$$$.</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:16: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:'8124b36b19ed1640',t:'MTY5NjY2NjU3NC42MzIwMDA='};_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", "*1000"] | ||
1447C | 1447 | 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>У вас есть рюкзак вместимостью $$$W$$$. У вас также есть $$$n$$$ предметов, вес $$$i$$$-го из них равен $$$w_i$$$. </p><p>Вы хотите поместить некоторые из этих предметов в рюкзак таким образом, чтобы их общий вес $$$C$$$ составлял как минимум половину его вместимости, но (очевидно) не превышал ее. Формально, $$$C$$$ должно удовлетворять: $$$\lceil \frac{W}{2}\rceil \le C \le W$$$. </p><p>Выведите список предметов, которые вы поместите в рюкзак, или определите, что удовлетворить условиям невозможно. </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 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целые числа $$$n$$$ и $$$W$$$ ($$$1 \le n \le 200\,000$$$, $$$1\le W \le 10^{18}$$$). </p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^9$$$) — веса элементов.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$200\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если нет решения, выведите одно целое число $$$-1$$$. </p><p>Если есть решение, состоящее из $$$m$$$ предметов, выведите $$$m$$$ в первой строке и $$$m$$$ целых чисел $$$j_1$$$, $$$j_2$$$, ..., $$$j_m$$$ ($$$1 \le j_i \le n$$$, <span class="tex-font-style-bf">где все $$$j_i$$$ попарно различны</span>) во второй строке — индексы предметов, которые вы хотели бы упаковать в рюкзак.</p><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>
3
1 3
3
6 2
19 8 19 69 9 4
7 12
1 1 1 17 1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1
-1
6
1 2 3 5 6 7</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, вы можете взять предмет весом $$$3$$$ и полностью заполнить рюкзак.</p><p>Во втором наборе входных данных, все предметы больше, чем рюкзак. Следовательно, ответ $$$-1$$$.</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="8341195e5fe0500fd95b3981210305d6"/>
<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="6b61ecdb9d4aba92dc230e2a67468230909b70f9"/>
<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='8341195e5fe0500fd95b3981210305d6'> </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%2F1447%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='8341195e5fe0500fd95b3981210305d6'/>
<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/1447">Codeforces Round 683 (Div. 2, by Meet IT)</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='8341195e5fe0500fd95b3981210305d6'/>
<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/1447/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='8341195e5fe0500fd95b3981210305d6'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797264"/>
<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='8341195e5fe0500fd95b3981210305d6'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797264"/>
<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/82067" title="Meet IT Codeforces Round Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12351" resourceName="Meet IT Codeforces Round 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/1447">Задачи</a></li>
<li><a
href="/contest/1447/submit">Отослать</a></li>
<li><a
href="/contest/1447/my">Мои посылки</a></li>
<li><a
href="/contest/1447/status">Статус</a></li>
<li><a
href="/contest/1447/hacks">Взломы</a></li>
<li><a
href="/contest/1447/room/1">Комната</a></li>
<li><a
href="/contest/1447/standings">Положение</a></li>
<li><a
href="/contest/1447/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_864c07a13a68fba5219078bb2f07b07c49fd0810">
<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>У вас есть рюкзак вместимостью $$$W$$$. У вас также есть $$$n$$$ предметов, вес $$$i$$$-го из них равен $$$w_i$$$. </p><p>Вы хотите поместить некоторые из этих предметов в рюкзак таким образом, чтобы их общий вес $$$C$$$ составлял как минимум половину его вместимости, но (очевидно) не превышал ее. Формально, $$$C$$$ должно удовлетворять: $$$\lceil \frac{W}{2}\rceil \le C \le W$$$. </p><p>Выведите список предметов, которые вы поместите в рюкзак, или определите, что удовлетворить условиям невозможно. </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 10^4$$$). Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целые числа $$$n$$$ и $$$W$$$ ($$$1 \le n \le 200\,000$$$, $$$1\le W \le 10^{18}$$$). </p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le 10^9$$$) — веса элементов.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$200\,000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если нет решения, выведите одно целое число $$$-1$$$. </p><p>Если есть решение, состоящее из $$$m$$$ предметов, выведите $$$m$$$ в первой строке и $$$m$$$ целых чисел $$$j_1$$$, $$$j_2$$$, ..., $$$j_m$$$ ($$$1 \le j_i \le n$$$, <span class="tex-font-style-bf">где все $$$j_i$$$ попарно различны</span>) во второй строке — индексы предметов, которые вы хотели бы упаковать в рюкзак.</p><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>
3
1 3
3
6 2
19 8 19 69 9 4
7 12
1 1 1 17 1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1
-1
6
1 2 3 5 6 7</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, вы можете взять предмет весом $$$3$$$ и полностью заполнить рюкзак.</p><p>Во втором наборе входных данных, все предметы больше, чем рюкзак. Следовательно, ответ $$$-1$$$.</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:16: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:'8124b37318f57b3b',t:'MTY5NjY2NjU3NS45MjIwMDA='};_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", "*1300"] | ||
1447D | 1447 | 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>Вам даны две строки $$$A$$$ и $$$B$$$, представляющие эссе двух учеников, которые подозреваются в мошенничестве. Для любых двух строк $$$C$$$, $$$D$$$ мы определяем оценку их сходства $$$S(C,D)$$$ как $$$4\cdot LCS(C,D) - |C| - |D|$$$, где $$$LCS(C,D)$$$ обозначает длину наибольшей общей <span class="tex-font-style-bf">подпоследовательности</span> строк $$$C$$$ и $$$D$$$. </p><p>Вы считаете, что могла быть скопирована только часть эссе, поэтому вас интересуют их <span class="tex-font-style-bf">подстроки</span>.</p><p>Вычислите максимальную оценку сходства по всем парам подстрок. Более формально, выведите максимальное значение $$$S(C, D)$$$, по всем парам $$$(C, D)$$$, где $$$C$$$ — некоторая подстрока $$$A$$$, а $$$D$$$ — некоторая подстрока $$$B$$$. </p><p>Если $$$X$$$ — строка, то $$$|X|$$$ обозначает ее длину.</p><p>Строка $$$a$$$ является <span class="tex-font-style-bf">подстрокой</span> строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p><p>Строка $$$a$$$ является <span class="tex-font-style-bf">подпоследовательностью</span> строки $$$b$$$, если $$$a$$$ можно получить из $$$b$$$ путем удаления нескольких (возможно, нуля или всех) символов. </p><p>Обратите внимание на разницу между <span class="tex-font-style-bf">подстрокой</span> и <span class="tex-font-style-bf">подпоследовательностью</span>, так как оба термина встречаются в условии задачи. </p><p>Возможно, вам будет интересно прочитать страницу <a href="https://ru.wikipedia.org/wiki/Наибольшая_общая_подпоследовательность">Википедии о наибольшей общей подпоследовательности</a>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два положительных целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 5000$$$) — длины двух строк $$$A$$$ и $$$B$$$. </p><p>Вторая строка содержит строку, состоящую из $$$n$$$ строчных латинских букв — строку $$$A$$$.</p><p>В третьей строке находится строка, состоящая из $$$m$$$ строчных латинских букв — строку $$$B$$$. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите максимальное значение $$$S(C, D)$$$, по всем парам $$$(C, D)$$$, где $$$C$$$ — некоторая подстрока $$$A$$$, а $$$D$$$ — некоторая подстрока $$$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 5
abba
babab
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8 10
bbbbabab
bbbabaaaaa
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 7
uiibwws
qhtkxcn
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере:</p><p><span class="tex-font-style-tt">abb</span> из первой строки и <span class="tex-font-style-tt">abab</span> из второй строки имеют LCS равный <span class="tex-font-style-tt">abb</span>.</p><p>Результат равен $$$S(abb, abab) = (4 \cdot |abb|$$$) - $$$|abb|$$$ - $$$|abab|$$$ = $$$4 \cdot 3 - 3 - 4 = 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="9bcbd1a81cb1bb02f13e6fc910c846b7"/>
<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="6b61ecdb9d4aba92dc230e2a67468230909b70f9"/>
<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='9bcbd1a81cb1bb02f13e6fc910c846b7'> </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%2F1447%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='9bcbd1a81cb1bb02f13e6fc910c846b7'/>
<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/1447">Codeforces Round 683 (Div. 2, by Meet IT)</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='9bcbd1a81cb1bb02f13e6fc910c846b7'/>
<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/1447/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="Сложность">
*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='9bcbd1a81cb1bb02f13e6fc910c846b7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797265"/>
<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='9bcbd1a81cb1bb02f13e6fc910c846b7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797265"/>
<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/82067" title="Meet IT Codeforces Round Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12351" resourceName="Meet IT Codeforces Round 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/1447">Задачи</a></li>
<li><a
href="/contest/1447/submit">Отослать</a></li>
<li><a
href="/contest/1447/my">Мои посылки</a></li>
<li><a
href="/contest/1447/status">Статус</a></li>
<li><a
href="/contest/1447/hacks">Взломы</a></li>
<li><a
href="/contest/1447/room/1">Комната</a></li>
<li><a
href="/contest/1447/standings">Положение</a></li>
<li><a
href="/contest/1447/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_fc458a00c67dc8949417be7097a96db68bbc7de5">
<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>Вам даны две строки $$$A$$$ и $$$B$$$, представляющие эссе двух учеников, которые подозреваются в мошенничестве. Для любых двух строк $$$C$$$, $$$D$$$ мы определяем оценку их сходства $$$S(C,D)$$$ как $$$4\cdot LCS(C,D) - |C| - |D|$$$, где $$$LCS(C,D)$$$ обозначает длину наибольшей общей <span class="tex-font-style-bf">подпоследовательности</span> строк $$$C$$$ и $$$D$$$. </p><p>Вы считаете, что могла быть скопирована только часть эссе, поэтому вас интересуют их <span class="tex-font-style-bf">подстроки</span>.</p><p>Вычислите максимальную оценку сходства по всем парам подстрок. Более формально, выведите максимальное значение $$$S(C, D)$$$, по всем парам $$$(C, D)$$$, где $$$C$$$ — некоторая подстрока $$$A$$$, а $$$D$$$ — некоторая подстрока $$$B$$$. </p><p>Если $$$X$$$ — строка, то $$$|X|$$$ обозначает ее длину.</p><p>Строка $$$a$$$ является <span class="tex-font-style-bf">подстрокой</span> строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p><p>Строка $$$a$$$ является <span class="tex-font-style-bf">подпоследовательностью</span> строки $$$b$$$, если $$$a$$$ можно получить из $$$b$$$ путем удаления нескольких (возможно, нуля или всех) символов. </p><p>Обратите внимание на разницу между <span class="tex-font-style-bf">подстрокой</span> и <span class="tex-font-style-bf">подпоследовательностью</span>, так как оба термина встречаются в условии задачи. </p><p>Возможно, вам будет интересно прочитать страницу <a href="https://ru.wikipedia.org/wiki/Наибольшая_общая_подпоследовательность">Википедии о наибольшей общей подпоследовательности</a>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два положительных целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 5000$$$) — длины двух строк $$$A$$$ и $$$B$$$. </p><p>Вторая строка содержит строку, состоящую из $$$n$$$ строчных латинских букв — строку $$$A$$$.</p><p>В третьей строке находится строка, состоящая из $$$m$$$ строчных латинских букв — строку $$$B$$$. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите максимальное значение $$$S(C, D)$$$, по всем парам $$$(C, D)$$$, где $$$C$$$ — некоторая подстрока $$$A$$$, а $$$D$$$ — некоторая подстрока $$$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 5
abba
babab
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8 10
bbbbabab
bbbabaaaaa
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 7
uiibwws
qhtkxcn
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере:</p><p><span class="tex-font-style-tt">abb</span> из первой строки и <span class="tex-font-style-tt">abab</span> из второй строки имеют LCS равный <span class="tex-font-style-tt">abb</span>.</p><p>Результат равен $$$S(abb, abab) = (4 \cdot |abb|$$$) - $$$|abb|$$$ - $$$|abab|$$$ = $$$4 \cdot 3 - 3 - 4 = 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:16: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:'8124b37b2dcd3a9b',t:'MTY5NjY2NjU3Ny4yMzMwMDA='};_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\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", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1800"] | ||
1447E | 1447 | 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> неотрицательных целых чисел $$$(b_1, b_2, \dots, b_k)$$$ мы определяем, является ли она <span class="tex-font-style-bf">хорошей</span> следующим образом:</p><ul> <li> Рассмотрим граф на $$$k$$$ вершинах, на которых написаны числа от $$$b_1$$$ до $$$b_k$$$.</li><li> Для каждого $$$i$$$ от $$$1$$$ до $$$k$$$ мы находим такое $$$j$$$ ($$$1 \le j \le k$$$, $$$j\neq i$$$), для которого значение $$$(b_i \oplus b_j)$$$ <span class="tex-font-style-bf">минимально</span> среди всех таких $$$j$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>. После этого мы проводим <span class="tex-font-style-bf">неориентированное</span> ребро между вершинами с числами $$$b_i$$$ и $$$b_j$$$.</li><li> Последовательность называется <span class="tex-font-style-bf">хорошей</span>, если и только если получившийся граф является <span class="tex-font-style-bf">деревом</span> (то есть он связан и не имеет простых циклов). </li></ul><p>Возможно, что для некоторых чисел $$$b_i$$$ и $$$b_j$$$ вы попробуете добавить ребро между ними дважды. Тем не менее вы добавите это ребро только один раз.</p><p>Ниже приведен пример (рисунок, соответствующий первому примеру). </p><p>Последовательность $$$(0, 1, 5, 2, 6)$$$ <span class="tex-font-style-bf">не</span> хорошая, так как мы <span class="tex-font-style-bf">не можем</span> достичь $$$1$$$ из $$$5$$$.</p><p>Однако, последовательность $$$(0, 1, 5, 2)$$$ <span class="tex-font-style-bf">является</span> хорошей. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d4a5328470cb773b91ddbc5e425b978c856acbdf.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Вам дана последовательность $$$(a_1, a_2, \dots, a_n)$$$ из <span class="tex-font-style-bf">попарно различных</span> неотрицательных целых чисел. Вы хотите удалить из нее некоторые элементы (возможно, ни одного), чтобы сделать <span class="tex-font-style-bf">оставшуюся</span> последовательность хорошей. Какое минимально возможное количество удалений необходимо для достижения этой цели?</p><p>Можно показать, что для любой последовательности можно удалить некоторое количество элементов, оставив как минимум $$$2$$$, так, что оставшаяся последовательность будет хорошей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$2 \le n \le 200,000$$$) — длину последовательности.</p><p>Во второй строке находится $$$n$$$ <span class="tex-font-style-bf">попарно различных</span> неотрицательных целых чисел $$$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>Необходимо вывести ровно одно целое число — минимально возможное количество элементов, которые нужно удалить, чтобы сделать оставшуюся последовательность хорошей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
0 1 5 2 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7
6 9 8 7 3 5 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обратите внимание, что числа, которые вы удаляете, <span class="tex-font-style-bf">не</span> влияют на процедуру проверки, является ли хорошей оставшаяся последовательность.</p><p>Возможно, что для некоторых чисел $$$b_i$$$ и $$$b_j$$$ вы попробуете добавить ребро между ними дважды. Тем не менее вы добавите это ребро только один раз.</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="9fcbba2df6d83b1a2cd94a4937409e40"/>
<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="6b61ecdb9d4aba92dc230e2a67468230909b70f9"/>
<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='9fcbba2df6d83b1a2cd94a4937409e40'> </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%2F1447%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='9fcbba2df6d83b1a2cd94a4937409e40'/>
<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/1447">Codeforces Round 683 (Div. 2, by Meet IT)</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='9fcbba2df6d83b1a2cd94a4937409e40'/>
<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/1447/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="Сложность">
*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='9fcbba2df6d83b1a2cd94a4937409e40'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797266"/>
<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='9fcbba2df6d83b1a2cd94a4937409e40'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797266"/>
<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/82067" title="Meet IT Codeforces Round Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12351" resourceName="Meet IT Codeforces Round 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/1447">Задачи</a></li>
<li><a
href="/contest/1447/submit">Отослать</a></li>
<li><a
href="/contest/1447/my">Мои посылки</a></li>
<li><a
href="/contest/1447/status">Статус</a></li>
<li><a
href="/contest/1447/hacks">Взломы</a></li>
<li><a
href="/contest/1447/room/1">Комната</a></li>
<li><a
href="/contest/1447/standings">Положение</a></li>
<li><a
href="/contest/1447/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_3e248512727e4c731d9c8bb01160524adf443da5">
<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> неотрицательных целых чисел $$$(b_1, b_2, \dots, b_k)$$$ мы определяем, является ли она <span class="tex-font-style-bf">хорошей</span> следующим образом:</p><ul> <li> Рассмотрим граф на $$$k$$$ вершинах, на которых написаны числа от $$$b_1$$$ до $$$b_k$$$.</li><li> Для каждого $$$i$$$ от $$$1$$$ до $$$k$$$ мы находим такое $$$j$$$ ($$$1 \le j \le k$$$, $$$j\neq i$$$), для которого значение $$$(b_i \oplus b_j)$$$ <span class="tex-font-style-bf">минимально</span> среди всех таких $$$j$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>. После этого мы проводим <span class="tex-font-style-bf">неориентированное</span> ребро между вершинами с числами $$$b_i$$$ и $$$b_j$$$.</li><li> Последовательность называется <span class="tex-font-style-bf">хорошей</span>, если и только если получившийся граф является <span class="tex-font-style-bf">деревом</span> (то есть он связан и не имеет простых циклов). </li></ul><p>Возможно, что для некоторых чисел $$$b_i$$$ и $$$b_j$$$ вы попробуете добавить ребро между ними дважды. Тем не менее вы добавите это ребро только один раз.</p><p>Ниже приведен пример (рисунок, соответствующий первому примеру). </p><p>Последовательность $$$(0, 1, 5, 2, 6)$$$ <span class="tex-font-style-bf">не</span> хорошая, так как мы <span class="tex-font-style-bf">не можем</span> достичь $$$1$$$ из $$$5$$$.</p><p>Однако, последовательность $$$(0, 1, 5, 2)$$$ <span class="tex-font-style-bf">является</span> хорошей. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d4a5328470cb773b91ddbc5e425b978c856acbdf.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Вам дана последовательность $$$(a_1, a_2, \dots, a_n)$$$ из <span class="tex-font-style-bf">попарно различных</span> неотрицательных целых чисел. Вы хотите удалить из нее некоторые элементы (возможно, ни одного), чтобы сделать <span class="tex-font-style-bf">оставшуюся</span> последовательность хорошей. Какое минимально возможное количество удалений необходимо для достижения этой цели?</p><p>Можно показать, что для любой последовательности можно удалить некоторое количество элементов, оставив как минимум $$$2$$$, так, что оставшаяся последовательность будет хорошей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$2 \le n \le 200,000$$$) — длину последовательности.</p><p>Во второй строке находится $$$n$$$ <span class="tex-font-style-bf">попарно различных</span> неотрицательных целых чисел $$$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>Необходимо вывести ровно одно целое число — минимально возможное количество элементов, которые нужно удалить, чтобы сделать оставшуюся последовательность хорошей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
0 1 5 2 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7
6 9 8 7 3 5 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обратите внимание, что числа, которые вы удаляете, <span class="tex-font-style-bf">не</span> влияют на процедуру проверки, является ли хорошей оставшаяся последовательность.</p><p>Возможно, что для некоторых чисел $$$b_i$$$ и $$$b_j$$$ вы попробуете добавить ребро между ними дважды. Тем не менее вы добавите это ребро только один раз.</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:16: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:'8124b3835ccd16a3',t:'MTY5NjY2NjU3OC41MjEwMDA='};_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", "\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", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\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"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u0442\u0440\u043e\u043a\u043e\u0432\u044b\u0435 \u0441\u0443\u0444\u0444. \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b", "*2100"] | ||
1447F1 | 1447 | F1 | ru | F1. Задача о частотах (простая версия) | <div class="problem-statement"><div class="header"><div class="title">F1. Задача о частотах (простая версия)</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>Вам дан массив $$$[a_1, a_2, \dots, a_n]$$$. </p><p>Ваша цель — найти длину самого длинного подмассива этого массива такого, в котором наиболее часто встречающееся значение <span class="tex-font-style-bf">не</span> единственно. Другими словами, вы ищете подмассив такой, что если в этом подмассиве наиболее часто встречающееся значение встречается $$$f$$$ раз, то как минимум $$$2$$$ разных значения должны встречаться в нем ровно $$$f$$$ раз.</p><p>Массив $$$c$$$ является подмассивом массива $$$d$$$, если $$$c$$$ может быть получен из $$$d$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — длину массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le min(n, 100)$$$) — элементы массива.</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
1 1 2 2 3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 1 1 5 4 1 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подмассив $$$[1, 1, 2, 2, 3, 3]$$$ хороший, но $$$[1, 1, 2, 2, 3, 3, 3]$$$ нет: во втором число $$$3$$$ встречается $$$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="ecc343263bb6d2faa71caede96952a99"/>
<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="Задача - F1 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="6b61ecdb9d4aba92dc230e2a67468230909b70f9"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F1 - 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='ecc343263bb6d2faa71caede96952a99'> </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%2F1447%2Fproblem%2FF1%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='ecc343263bb6d2faa71caede96952a99'/>
<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/1447">Codeforces Round 683 (Div. 2, by Meet IT)</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='ecc343263bb6d2faa71caede96952a99'/>
<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/1447/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="Сложность">
*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='ecc343263bb6d2faa71caede96952a99'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797267"/>
<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='ecc343263bb6d2faa71caede96952a99'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797267"/>
<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/82067" title="Meet IT Codeforces Round Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12351" resourceName="Meet IT Codeforces Round 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/1447">Задачи</a></li>
<li><a
href="/contest/1447/submit">Отослать</a></li>
<li><a
href="/contest/1447/my">Мои посылки</a></li>
<li><a
href="/contest/1447/status">Статус</a></li>
<li><a
href="/contest/1447/hacks">Взломы</a></li>
<li><a
href="/contest/1447/room/1">Комната</a></li>
<li><a
href="/contest/1447/standings">Положение</a></li>
<li><a
href="/contest/1447/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="F1" data-uuid="ps_334989f5c35c479bc37a4e3d369f13e6063d08f0">
<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">F1. Задача о частотах (простая версия)</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>Вам дан массив $$$[a_1, a_2, \dots, a_n]$$$. </p><p>Ваша цель — найти длину самого длинного подмассива этого массива такого, в котором наиболее часто встречающееся значение <span class="tex-font-style-bf">не</span> единственно. Другими словами, вы ищете подмассив такой, что если в этом подмассиве наиболее часто встречающееся значение встречается $$$f$$$ раз, то как минимум $$$2$$$ разных значения должны встречаться в нем ровно $$$f$$$ раз.</p><p>Массив $$$c$$$ является подмассивом массива $$$d$$$, если $$$c$$$ может быть получен из $$$d$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — длину массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le min(n, 100)$$$) — элементы массива.</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
1 1 2 2 3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 1 1 5 4 1 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подмассив $$$[1, 1, 2, 2, 3, 3]$$$ хороший, но $$$[1, 1, 2, 2, 3, 3, 3]$$$ нет: во втором число $$$3$$$ встречается $$$3$$$ раза, и ни один другой элемент не встречается $$$3$$$ раза.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F1]");
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:16: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:'8124b38b6c7100b4',t:'MTY5NjY2NjU3OS44MTkwMDA='};_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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2600"] | ||
1447F2 | 1447 | F2 | ru | F2. Задача о частотах (сложная версия) | <div class="problem-statement"><div class="header"><div class="title">F2. Задача о частотах (сложная версия)</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>Вам дан массив $$$[a_1, a_2, \dots, a_n]$$$. </p><p>Ваша цель — найти длину самого длинного подмассива этого массива такого, в котором наиболее часто встречающееся значение <span class="tex-font-style-bf">не</span> единственно. Другими словами, вы ищете подмассив такой, что если в этом подмассиве наиболее часто встречающееся значение встречается $$$f$$$ раз, то как минимум $$$2$$$ разные значения должны встречаться в нем ровно $$$f$$$ раз.</p><p>Массив $$$c$$$ является подмассивом массива $$$d$$$, если $$$c$$$ может быть получен из $$$d$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — длину массива.</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>Необходимо вывести ровно одно целое число — длину самого длинного подмассива массива, наиболее частое значение которого не является единственным. Если такого подмассива нет, выведите $$$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
1 1 2 2 3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 1 1 5 4 1 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подмассив $$$[1, 1, 2, 2, 3, 3]$$$ хороший, но $$$[1, 1, 2, 2, 3, 3, 3]$$$ нет: во втором число $$$3$$$ встречается $$$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="fe3af8a43bac472cceeb7378cdc9519d"/>
<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="Задача - F2 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="6b61ecdb9d4aba92dc230e2a67468230909b70f9"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - F2 - 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='fe3af8a43bac472cceeb7378cdc9519d'> </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%2F1447%2Fproblem%2FF2%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='fe3af8a43bac472cceeb7378cdc9519d'/>
<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/1447">Codeforces Round 683 (Div. 2, by Meet IT)</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='fe3af8a43bac472cceeb7378cdc9519d'/>
<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/1447/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="Сложность">
*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='fe3af8a43bac472cceeb7378cdc9519d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="797268"/>
<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='fe3af8a43bac472cceeb7378cdc9519d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="797268"/>
<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/82067" title="Meet IT Codeforces Round Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12351" resourceName="Meet IT Codeforces Round 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/1447">Задачи</a></li>
<li><a
href="/contest/1447/submit">Отослать</a></li>
<li><a
href="/contest/1447/my">Мои посылки</a></li>
<li><a
href="/contest/1447/status">Статус</a></li>
<li><a
href="/contest/1447/hacks">Взломы</a></li>
<li><a
href="/contest/1447/room/1">Комната</a></li>
<li><a
href="/contest/1447/standings">Положение</a></li>
<li><a
href="/contest/1447/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="F2" data-uuid="ps_d6ac3e7f85aba13154b6ad6a7240b95e0703d47d">
<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">F2. Задача о частотах (сложная версия)</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>Вам дан массив $$$[a_1, a_2, \dots, a_n]$$$. </p><p>Ваша цель — найти длину самого длинного подмассива этого массива такого, в котором наиболее часто встречающееся значение <span class="tex-font-style-bf">не</span> единственно. Другими словами, вы ищете подмассив такой, что если в этом подмассиве наиболее часто встречающееся значение встречается $$$f$$$ раз, то как минимум $$$2$$$ разные значения должны встречаться в нем ровно $$$f$$$ раз.</p><p>Массив $$$c$$$ является подмассивом массива $$$d$$$, если $$$c$$$ может быть получен из $$$d$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит единственное целое число $$$n$$$ ($$$1 \le n \le 200\,000$$$) — длину массива.</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>Необходимо вывести ровно одно целое число — длину самого длинного подмассива массива, наиболее частое значение которого не является единственным. Если такого подмассива нет, выведите $$$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
1 1 2 2 3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 1 1 5 4 1 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подмассив $$$[1, 1, 2, 2, 3, 3]$$$ хороший, но $$$[1, 1, 2, 2, 3, 3, 3]$$$ нет: во втором число $$$3$$$ встречается $$$3$$$ раза, и ни один другой элемент не встречается $$$3$$$ раза.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=F2]");
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:16: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:'8124b393af4f3a5f',t:'MTY5NjY2NjU4MS4xMzUwMDA='};_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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3000"] | ||
1450A | 1450 | A | ru | A. Избежать Trygub | <div class="problem-statement"><div class="header"><div class="title">A. Избежать Trygub</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>Строка $$$b$$$ является подпоследовательностью строки $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нескольких (возможно нуля или всех) символов. Например, «<span class="tex-font-style-tt">xy</span>» подпоследовательность «<span class="tex-font-style-tt">xzyw</span>» и «<span class="tex-font-style-tt">xy</span>», но не «<span class="tex-font-style-tt">yx</span>».</p><p>Вам дана строка $$$a$$$. Ваша задача переставить символы $$$a$$$, так что «<span class="tex-font-style-tt">trygub</span>» не будет подпоследовательностью получившейся строки.</p><p>Другими словами, вы должны найти строку $$$b$$$, которая является перестановкой символов строки $$$a$$$ и «<span class="tex-font-style-tt">trygub</span>» не является подпоследовательностью $$$b$$$.</p><p>У нас есть замечательное, верное доказательство того, что любая строка может быть переупорядочена так, чтобы не содержать «<span class="tex-font-style-tt">trygub</span>» в качестве подпоследовательности, но условие этой задачи слишком короткое для его изложения.</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 200$$$) — длина $$$a$$$.</p><p>В следующей строке находится строка $$$a$$$ длины $$$n$$$, состоящая из строчных символов латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку $$$b$$$ длины $$$n$$$, которая является перестановкой символов строки $$$a$$$ и «<span class="tex-font-style-tt">trygub</span>» не является ее подпоследовательностью.</p><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>
3
11
antontrygub
15
bestcoordinator
19
trywatchinggurabruh
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
bugyrtnotna
bestcoordinator
bruhtrywatchinggura
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных «<span class="tex-font-style-tt">bugyrtnotna</span>» не содержит «<span class="tex-font-style-tt">trygub</span>» как подпоследовательность. Она содержит все символы «<span class="tex-font-style-tt">trygub</span>», но не в правильном порядке, поэтому это не подпоследовательность.</p><p>Во втором наборе входных данных мы можем не менять порядок символов, потому что это не требуется.</p><p>В третьем наборе входных данных «<span class="tex-font-style-tt">bruhtrywatchinggura</span>» содержит «<span class="tex-font-style-tt">trygu</span>» как подпоследовательность, но не содержит «<span class="tex-font-style-tt">trygub</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="e6179070eb403c4e87256e9307c2fbdf"/>
<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="69278a83140138beed0a38d33f76b679b59f1fce"/>
<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='e6179070eb403c4e87256e9307c2fbdf'> </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%2F1450%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='e6179070eb403c4e87256e9307c2fbdf'/>
<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/1450">Codeforces Global Round 12</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='e6179070eb403c4e87256e9307c2fbdf'/>
<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/1450/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='e6179070eb403c4e87256e9307c2fbdf'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821291"/>
<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='e6179070eb403c4e87256e9307c2fbdf'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821291"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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_60b3a3ab681633cb4668ca463eaee662d22c0300">
<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. Избежать Trygub</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>Строка $$$b$$$ является подпоследовательностью строки $$$a$$$, если $$$b$$$ может быть получена из $$$a$$$ удалением нескольких (возможно нуля или всех) символов. Например, «<span class="tex-font-style-tt">xy</span>» подпоследовательность «<span class="tex-font-style-tt">xzyw</span>» и «<span class="tex-font-style-tt">xy</span>», но не «<span class="tex-font-style-tt">yx</span>».</p><p>Вам дана строка $$$a$$$. Ваша задача переставить символы $$$a$$$, так что «<span class="tex-font-style-tt">trygub</span>» не будет подпоследовательностью получившейся строки.</p><p>Другими словами, вы должны найти строку $$$b$$$, которая является перестановкой символов строки $$$a$$$ и «<span class="tex-font-style-tt">trygub</span>» не является подпоследовательностью $$$b$$$.</p><p>У нас есть замечательное, верное доказательство того, что любая строка может быть переупорядочена так, чтобы не содержать «<span class="tex-font-style-tt">trygub</span>» в качестве подпоследовательности, но условие этой задачи слишком короткое для его изложения.</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 200$$$) — длина $$$a$$$.</p><p>В следующей строке находится строка $$$a$$$ длины $$$n$$$, состоящая из строчных символов латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите строку $$$b$$$ длины $$$n$$$, которая является перестановкой символов строки $$$a$$$ и «<span class="tex-font-style-tt">trygub</span>» не является ее подпоследовательностью.</p><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>
3
11
antontrygub
15
bestcoordinator
19
trywatchinggurabruh
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
bugyrtnotna
bestcoordinator
bruhtrywatchinggura
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных «<span class="tex-font-style-tt">bugyrtnotna</span>» не содержит «<span class="tex-font-style-tt">trygub</span>» как подпоследовательность. Она содержит все символы «<span class="tex-font-style-tt">trygub</span>», но не в правильном порядке, поэтому это не подпоследовательность.</p><p>Во втором наборе входных данных мы можем не менять порядок символов, потому что это не требуется.</p><p>В третьем наборе входных данных «<span class="tex-font-style-tt">bruhtrywatchinggura</span>» содержит «<span class="tex-font-style-tt">trygu</span>» как подпоследовательность, но не содержит «<span class="tex-font-style-tt">trygub</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:16: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:'8124b39bbdd215ee',t:'MTY5NjY2NjU4Mi41MTkwMDA='};_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\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"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*800"] | ||
1450B | 1450 | 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$$$ <span class="tex-font-style-bf">различных</span> точек $$$(x_1, y_1),\ldots,(x_n,y_n)$$$ на плоскости и неотрицательное целое число $$$k$$$. Каждая точка представляет собой микроскопический стальной шарик, а $$$k$$$ — это его сила притяжения, когда он заряжен. Сила притяжения одинакова для всех шариков.</p><p>За одну операцию вы можете выбрать шарик $$$i$$$ и зарядить его. После этого <span class="tex-font-style-bf">все</span> шарики на манхеттенском расстоянии не более $$$k$$$ от шарика $$$i$$$ перемещаются в позицию шарика $$$i$$$. После этой операции несколько различных шариков могут оказаться в одной точке.</p><p>Более формально, для всех шариков $$$j$$$ таких, что $$$|x_i - x_j| + |y_i - y_j| \le k$$$, мы присваиваем $$$x_j:=x_i$$$ и $$$y_j:=y_i$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/aed2054391a4b56a0664b19ad6028bb7125277ec.png" style="max-width: 100.0%;max-height: 100.0%;"/> Пример операции. После зарядки шарика в центре два других шарика перемещаются в его позицию. На правой картинке красная точка в центре — это общее положение этих шариков после операции. </center><p>Ваша задача — найти минимальное количество операций, нужное для того, чтобы переместить все шарики в одну точку, или сообщить, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится два целых числа $$$n$$$, $$$k$$$ ($$$2 \le n \le 100$$$, $$$0 \le k \le 10^6$$$) — количество шариков и сила притяжения каждого шарика, соответственно.</p><p>Следующие $$$n$$$ строк описывают координаты шариков. В $$$i$$$-й из этих строк находится два целых числа $$$x_i$$$, $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^5$$$) — координаты $$$i$$$-о шарика.</p><p>Гарантируется, что все точки <span class="tex-font-style-bf">различны</span>.</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>
3
3 2
0 0
3 3
1 1
3 3
6 7
8 8
6 9
4 1
0 0
0 1
0 2
0 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
1
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных три шарика находятся в $$$(0, 0)$$$, $$$(3, 3)$$$, и $$$(1, 1)$$$ и сила притяжения равна $$$2$$$. Можно переместить два шарика в одну точку за одну операцию, но невозможно переместить все три шарика в одну точку за любое количество операций.</p><p>Во втором наборе входных данных три шарика находятся шарика в $$$(6, 7)$$$, $$$(8, 8)$$$, и $$$(6, 9)$$$ и сила притяжения равна $$$3$$$. Если мы зарядим любой шарик, другие два переместятся в его позицию, поэтому нам достаточно одной операции.</p><p>В третьем наборе входных данных четыре шарика находятся в $$$(0, 0)$$$, $$$(0, 1)$$$, $$$(0, 2)$$$ и $$$(0, 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="ad9f003e112393cd7cfaed622d544a9c"/>
<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="69278a83140138beed0a38d33f76b679b59f1fce"/>
<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='ad9f003e112393cd7cfaed622d544a9c'> </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%2F1450%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='ad9f003e112393cd7cfaed622d544a9c'/>
<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/1450">Codeforces Global Round 12</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='ad9f003e112393cd7cfaed622d544a9c'/>
<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/1450/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="Сложность">
*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='ad9f003e112393cd7cfaed622d544a9c'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821292"/>
<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='ad9f003e112393cd7cfaed622d544a9c'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821292"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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_b0a9e2ed21b3b7c5c3130f151cbfd3318f62f1f4">
<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$$$ <span class="tex-font-style-bf">различных</span> точек $$$(x_1, y_1),\ldots,(x_n,y_n)$$$ на плоскости и неотрицательное целое число $$$k$$$. Каждая точка представляет собой микроскопический стальной шарик, а $$$k$$$ — это его сила притяжения, когда он заряжен. Сила притяжения одинакова для всех шариков.</p><p>За одну операцию вы можете выбрать шарик $$$i$$$ и зарядить его. После этого <span class="tex-font-style-bf">все</span> шарики на манхеттенском расстоянии не более $$$k$$$ от шарика $$$i$$$ перемещаются в позицию шарика $$$i$$$. После этой операции несколько различных шариков могут оказаться в одной точке.</p><p>Более формально, для всех шариков $$$j$$$ таких, что $$$|x_i - x_j| + |y_i - y_j| \le k$$$, мы присваиваем $$$x_j:=x_i$$$ и $$$y_j:=y_i$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/aed2054391a4b56a0664b19ad6028bb7125277ec.png" style="max-width: 100.0%;max-height: 100.0%;" /> Пример операции. После зарядки шарика в центре два других шарика перемещаются в его позицию. На правой картинке красная точка в центре — это общее положение этих шариков после операции. </center><p>Ваша задача — найти минимальное количество операций, нужное для того, чтобы переместить все шарики в одну точку, или сообщить, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится два целых числа $$$n$$$, $$$k$$$ ($$$2 \le n \le 100$$$, $$$0 \le k \le 10^6$$$) — количество шариков и сила притяжения каждого шарика, соответственно.</p><p>Следующие $$$n$$$ строк описывают координаты шариков. В $$$i$$$-й из этих строк находится два целых числа $$$x_i$$$, $$$y_i$$$ ($$$0 \le x_i, y_i \le 10^5$$$) — координаты $$$i$$$-о шарика.</p><p>Гарантируется, что все точки <span class="tex-font-style-bf">различны</span>.</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>
3
3 2
0 0
3 3
1 1
3 3
6 7
8 8
6 9
4 1
0 0
0 1
0 2
0 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
1
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных три шарика находятся в $$$(0, 0)$$$, $$$(3, 3)$$$, и $$$(1, 1)$$$ и сила притяжения равна $$$2$$$. Можно переместить два шарика в одну точку за одну операцию, но невозможно переместить все три шарика в одну точку за любое количество операций.</p><p>Во втором наборе входных данных три шарика находятся шарика в $$$(6, 7)$$$, $$$(8, 8)$$$, и $$$(6, 9)$$$ и сила притяжения равна $$$3$$$. Если мы зарядим любой шарик, другие два переместятся в его позицию, поэтому нам достаточно одной операции.</p><p>В третьем наборе входных данных четыре шарика находятся в $$$(0, 0)$$$, $$$(0, 1)$$$, $$$(0, 2)$$$ и $$$(0, 3)$$$ и сила притяжения равна $$$1$$$. Можно показать, что невозможно переместить все шарики в одну и ту же точку какой-то последовательностью операций.</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:16: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:'8124b3a46ec69db1',t:'MTY5NjY2NjU4My44MzgwMDA='};_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", "\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"] | ["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1000"] | ||
1450C1 | 1450 | C1 | ru | C1. Крестики Нолики Errichto (простая версия) | <div class="problem-statement"><div class="header"><div class="title">C1. Крестики Нолики Errichto (простая версия)</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 class="tex-font-style-tt">O</span> не встречается во входных данных простой версии.</span></p><p><span class="tex-font-style-it">Errichto бросил Monogon-у следующий вызов, чтобы запугать его и не дать занять первое место по вкладу на Codeforces.</span></p><p>В таблице для игры в крестики нолики есть $$$n$$$ строк и $$$n$$$ столбцов. Каждая клетка таблицы либо пустая, либо содержит фишку. Всего есть два типа фишек: <span class="tex-font-style-tt">X</span> и <span class="tex-font-style-tt">O</span>. Если есть три фишки одного типа, последовательные в какой-то строке или в каком-то столбце, то это выигрышная конфигурация. Иначе это ничейная конфигурация.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b9526a9dff5705c0ff53feb867221db11fb2c5b3.png" style="max-width: 100.0%;max-height: 100.0%;"/> Примеры в первой строке это выигрышные конфигурации. Примеры во второй строке это ничейные конфигурации. </center><p>За одну операцию вы можете поменять фишку <span class="tex-font-style-tt">X</span> на <span class="tex-font-style-tt">O</span> или фишку <span class="tex-font-style-tt">O</span> на <span class="tex-font-style-tt">X</span>. Обозначим за $$$k$$$ общее количество фишек в таблице. Ваша задача сделать таблицу <span class="tex-font-style-bf">ничейной</span> за не более $$$\lfloor \frac{k}{3}\rfloor$$$ (округление вниз) операций.</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 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1\le n\le 300$$$) — размер таблицы.</p><p>В следующих $$$n$$$ строках находятся строки, состоящие из $$$n$$$ символов, задающие изначальную таблицу. Символ в $$$i$$$-й строке и $$$j$$$-м столбце это '<span class="tex-font-style-tt">.</span>', если клетка пустая, иначе он совпадает с типом фишки, содержащейся в этой клетке таблицы: '<span class="tex-font-style-tt">X</span>' или '<span class="tex-font-style-tt">O</span>'.</p><p>Гарантируется, что не все клетки пустые.</p><p>В простой версии, символ '<span class="tex-font-style-tt">O</span>' не встречается во входных данных.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$300$$$.</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>
3
3
.X.
XXX
.X.
6
XX.XXX
XXXXXX
XXX.XX
XXXXXX
XX.X.X
XXXXXX
5
XXX.X
.X..X
XXX.X
..X..
..X..
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
.X.
XOX
.X.
XX.XXO
XOXXOX
OXX.XX
XOOXXO
XX.X.X
OXXOXX
XOX.X
.X..X
XXO.O
..X..
..X..
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть изначально три '<span class="tex-font-style-tt">X</span>' последовательных во второй строке и во втором столбце. Изменив фишку посередине на '<span class="tex-font-style-tt">O</span>' мы получим ничейную конфигурацию. При этом мы поменяли $$$1\le \lfloor 5/3\rfloor$$$ фишку.</p><p>Во втором наборе входных данных мы изменяем $$$9\le \lfloor 32/3\rfloor$$$ фишек и после этого не существует трех '<span class="tex-font-style-tt">X</span>' или '<span class="tex-font-style-tt">O</span>', последовательных в одной строке или одном столбце, поэтому это ничейная конфигурация.</p><p>В третьем наборе входных данных мы изменяем $$$3\le \lfloor 12/3\rfloor$$$ фишки и получившаяся конфигурация будет ничейной.</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="ed9c46c72b1562bd682531633d331dd3"/>
<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="Задача - C1 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="69278a83140138beed0a38d33f76b679b59f1fce"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C1 - 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='ed9c46c72b1562bd682531633d331dd3'> </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%2F1450%2Fproblem%2FC1%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='ed9c46c72b1562bd682531633d331dd3'/>
<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/1450">Codeforces Global Round 12</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='ed9c46c72b1562bd682531633d331dd3'/>
<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/1450/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="Сложность">
*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='ed9c46c72b1562bd682531633d331dd3'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821293"/>
<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='ed9c46c72b1562bd682531633d331dd3'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821293"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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="C1" data-uuid="ps_1c698f53f3bef0583fd4794b607b990c82364042">
<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">C1. Крестики Нолики Errichto (простая версия)</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 class="tex-font-style-tt">O</span> не встречается во входных данных простой версии.</span></p><p><span class="tex-font-style-it">Errichto бросил Monogon-у следующий вызов, чтобы запугать его и не дать занять первое место по вкладу на Codeforces.</span></p><p>В таблице для игры в крестики нолики есть $$$n$$$ строк и $$$n$$$ столбцов. Каждая клетка таблицы либо пустая, либо содержит фишку. Всего есть два типа фишек: <span class="tex-font-style-tt">X</span> и <span class="tex-font-style-tt">O</span>. Если есть три фишки одного типа, последовательные в какой-то строке или в каком-то столбце, то это выигрышная конфигурация. Иначе это ничейная конфигурация.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b9526a9dff5705c0ff53feb867221db11fb2c5b3.png" style="max-width: 100.0%;max-height: 100.0%;" /> Примеры в первой строке это выигрышные конфигурации. Примеры во второй строке это ничейные конфигурации. </center><p>За одну операцию вы можете поменять фишку <span class="tex-font-style-tt">X</span> на <span class="tex-font-style-tt">O</span> или фишку <span class="tex-font-style-tt">O</span> на <span class="tex-font-style-tt">X</span>. Обозначим за $$$k$$$ общее количество фишек в таблице. Ваша задача сделать таблицу <span class="tex-font-style-bf">ничейной</span> за не более $$$\lfloor \frac{k}{3}\rfloor$$$ (округление вниз) операций.</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 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1\le n\le 300$$$) — размер таблицы.</p><p>В следующих $$$n$$$ строках находятся строки, состоящие из $$$n$$$ символов, задающие изначальную таблицу. Символ в $$$i$$$-й строке и $$$j$$$-м столбце это '<span class="tex-font-style-tt">.</span>', если клетка пустая, иначе он совпадает с типом фишки, содержащейся в этой клетке таблицы: '<span class="tex-font-style-tt">X</span>' или '<span class="tex-font-style-tt">O</span>'.</p><p>Гарантируется, что не все клетки пустые.</p><p>В простой версии, символ '<span class="tex-font-style-tt">O</span>' не встречается во входных данных.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$300$$$.</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>
3
3
.X.
XXX
.X.
6
XX.XXX
XXXXXX
XXX.XX
XXXXXX
XX.X.X
XXXXXX
5
XXX.X
.X..X
XXX.X
..X..
..X..
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
.X.
XOX
.X.
XX.XXO
XOXXOX
OXX.XX
XOOXXO
XX.X.X
OXXOXX
XOX.X
.X..X
XXO.O
..X..
..X..
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть изначально три '<span class="tex-font-style-tt">X</span>' последовательных во второй строке и во втором столбце. Изменив фишку посередине на '<span class="tex-font-style-tt">O</span>' мы получим ничейную конфигурацию. При этом мы поменяли $$$1\le \lfloor 5/3\rfloor$$$ фишку.</p><p>Во втором наборе входных данных мы изменяем $$$9\le \lfloor 32/3\rfloor$$$ фишек и после этого не существует трех '<span class="tex-font-style-tt">X</span>' или '<span class="tex-font-style-tt">O</span>', последовательных в одной строке или одном столбце, поэтому это ничейная конфигурация.</p><p>В третьем наборе входных данных мы изменяем $$$3\le \lfloor 12/3\rfloor$$$ фишки и получившаяся конфигурация будет ничейной.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C1]");
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:16:25</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:'8124b3acbbea7a71',t:'MTY5NjY2NjU4NS4yNDkwMDA='};_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", "*2100"] | ||
1450C2 | 1450 | C2 | ru | C2. Крестики Нолики Errichto (сложная версия) | <div class="problem-statement"><div class="header"><div class="title">C2. Крестики Нолики Errichto (сложная версия)</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 class="tex-font-style-tt">O</span> не встречается во входных данных простой версии.</span></p><p><span class="tex-font-style-it">Errichto бросил Monogon-у следующий вызов, чтобы запугать его и не дать занять первое место по вкладу на Codeforces.</span></p><p>В таблице для игры в крестики нолики есть $$$n$$$ строк и $$$n$$$ столбцов. Каждая клетка таблицы либо пустая, либо содержит фишку. Всего есть два типа фишек: <span class="tex-font-style-tt">X</span> и <span class="tex-font-style-tt">O</span>. Если есть три фишки одного типа, последовательные в какой-то строке или в каком-то столбце, то это выигрышная конфигурация. Иначе это ничейная конфигурация.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b9526a9dff5705c0ff53feb867221db11fb2c5b3.png" style="max-width: 100.0%;max-height: 100.0%;"/> Примеры в первой строке это выигрышные конфигурации. Примеры во второй строке это ничейные конфигурации. </center><p>За одну операцию вы можете поменять фишку <span class="tex-font-style-tt">X</span> на <span class="tex-font-style-tt">O</span> или фишку <span class="tex-font-style-tt">O</span> на <span class="tex-font-style-tt">X</span>. Обозначим за $$$k$$$ общее количество фишек в таблице. Ваша задача сделать таблицу <span class="tex-font-style-bf">ничейной</span> за не более $$$\lfloor \frac{k}{3}\rfloor$$$ (округление вниз) операций.</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 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1\le n\le 300$$$) — размер таблицы.</p><p>В следующих $$$n$$$ строках находятся строки, состоящие из $$$n$$$ символов, задающие изначальную таблицу. Символ в $$$i$$$-й строке и $$$j$$$-м столбце это '<span class="tex-font-style-tt">.</span>', если клетка пустая, иначе он совпадает с типом фишки, содержащейся в этой клетке таблицы: '<span class="tex-font-style-tt">X</span>' или '<span class="tex-font-style-tt">O</span>'.</p><p>Гарантируется, что не все клетки пустые.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$300$$$.</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>
3
3
.O.
OOO
.O.
6
XXXOOO
XXXOOO
XX..OO
OO..XX
OOOXXX
OOOXXX
5
.OOO.
OXXXO
OXXXO
OXXXO
.OOO.
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
.O.
OXO
.O.
OXXOOX
XOXOXO
XX..OO
OO..XX
OXOXOX
XOOXXO
.OXO.
OOXXO
XXOXX
OXXOO
.OXO.</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть изначально три '<span class="tex-font-style-tt">O</span>' последовательных во второй строке и во втором столбце. Изменив фишку посередине на '<span class="tex-font-style-tt">X</span>' мы получим ничейную конфигурацию. При этом мы поменяли $$$1\le \lfloor 5/3\rfloor$$$ фишку.</p><p>Во втором наборе входных данных итоговая конфигурация ничейная. Мы поменяли $$$8\le \lfloor 32/3\rfloor$$$ фишек.</p><p>В третьем наборе входных данных итоговая конфигурация ничейная. Мы поменяли $$$7\le \lfloor 21/3\rfloor$$$ фишек.</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="2893ccfe3bd57513303956ac55319d47"/>
<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="Задача - C2 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="69278a83140138beed0a38d33f76b679b59f1fce"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - C2 - 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='2893ccfe3bd57513303956ac55319d47'> </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%2F1450%2Fproblem%2FC2%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='2893ccfe3bd57513303956ac55319d47'/>
<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/1450">Codeforces Global Round 12</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='2893ccfe3bd57513303956ac55319d47'/>
<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/1450/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='2893ccfe3bd57513303956ac55319d47'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821294"/>
<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='2893ccfe3bd57513303956ac55319d47'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821294"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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="C2" data-uuid="ps_5e9a6300878d5f8684664b6497f54a5ccf9af8de">
<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">C2. Крестики Нолики Errichto (сложная версия)</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 class="tex-font-style-tt">O</span> не встречается во входных данных простой версии.</span></p><p><span class="tex-font-style-it">Errichto бросил Monogon-у следующий вызов, чтобы запугать его и не дать занять первое место по вкладу на Codeforces.</span></p><p>В таблице для игры в крестики нолики есть $$$n$$$ строк и $$$n$$$ столбцов. Каждая клетка таблицы либо пустая, либо содержит фишку. Всего есть два типа фишек: <span class="tex-font-style-tt">X</span> и <span class="tex-font-style-tt">O</span>. Если есть три фишки одного типа, последовательные в какой-то строке или в каком-то столбце, то это выигрышная конфигурация. Иначе это ничейная конфигурация.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b9526a9dff5705c0ff53feb867221db11fb2c5b3.png" style="max-width: 100.0%;max-height: 100.0%;" /> Примеры в первой строке это выигрышные конфигурации. Примеры во второй строке это ничейные конфигурации. </center><p>За одну операцию вы можете поменять фишку <span class="tex-font-style-tt">X</span> на <span class="tex-font-style-tt">O</span> или фишку <span class="tex-font-style-tt">O</span> на <span class="tex-font-style-tt">X</span>. Обозначим за $$$k$$$ общее количество фишек в таблице. Ваша задача сделать таблицу <span class="tex-font-style-bf">ничейной</span> за не более $$$\lfloor \frac{k}{3}\rfloor$$$ (округление вниз) операций.</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 100$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1\le n\le 300$$$) — размер таблицы.</p><p>В следующих $$$n$$$ строках находятся строки, состоящие из $$$n$$$ символов, задающие изначальную таблицу. Символ в $$$i$$$-й строке и $$$j$$$-м столбце это '<span class="tex-font-style-tt">.</span>', если клетка пустая, иначе он совпадает с типом фишки, содержащейся в этой клетке таблицы: '<span class="tex-font-style-tt">X</span>' или '<span class="tex-font-style-tt">O</span>'.</p><p>Гарантируется, что не все клетки пустые.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$300$$$.</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>
3
3
.O.
OOO
.O.
6
XXXOOO
XXXOOO
XX..OO
OO..XX
OOOXXX
OOOXXX
5
.OOO.
OXXXO
OXXXO
OXXXO
.OOO.
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
.O.
OXO
.O.
OXXOOX
XOXOXO
XX..OO
OO..XX
OXOXOX
XOOXXO
.OXO.
OOXXO
XXOXX
OXXOO
.OXO.</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть изначально три '<span class="tex-font-style-tt">O</span>' последовательных во второй строке и во втором столбце. Изменив фишку посередине на '<span class="tex-font-style-tt">X</span>' мы получим ничейную конфигурацию. При этом мы поменяли $$$1\le \lfloor 5/3\rfloor$$$ фишку.</p><p>Во втором наборе входных данных итоговая конфигурация ничейная. Мы поменяли $$$8\le \lfloor 32/3\rfloor$$$ фишек.</p><p>В третьем наборе входных данных итоговая конфигурация ничейная. Мы поменяли $$$7\le \lfloor 21/3\rfloor$$$ фишек.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C2]");
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:16: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:'8124b3b55b0d1667',t:'MTY5NjY2NjU4Ni41NTgwMDA='};_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", "*2300"] | ||
1450D | 1450 | 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>На платформе CodeCook для соревнований по спортивному программированию у каждого человека есть график его рейтинга, описываемый массивом целых чисел $$$a$$$ длины $$$n$$$. Вы обновляете инфраструктуру, поэтому вы создали программу, сжимающую эти графики.</p><p>Программа работает следующим образом. Задается целое число $$$k$$$. Программа берет минимум на каждом последовательном подмассиве длины $$$k$$$ в массиве $$$a$$$.</p><p>Более формально, для массива $$$a$$$ длины $$$n$$$ и целого числа $$$k$$$, определим $$$k$$$-сжатие массива $$$a$$$ как массив $$$b$$$ длины $$$n-k+1$$$, такой что $$$$$$b_j =\min_{j\le i\le j+k-1}a_i$$$$$$</p><p>Например, $$$3$$$-сжатие массива $$$[1, 3, 4, 5, 2]$$$ это $$$[\min\{1, 3, 4\}, \min\{3, 4, 5\}, \min\{4, 5, 2\}]=[1, 3, 2].$$$</p><p>Перестановка длины $$$m$$$ это массив, состоящий из $$$m$$$ различных целых чисел от $$$1$$$ до $$$m$$$ в некотором порядке. Например, $$$[2,3,1,5,4]$$$ это перестановка, но $$$[1,2,2]$$$ это не перестановка ($$$2$$$ встречается дважды в массиве) и $$$[1,3,4]$$$ это тоже не перестановка ($$$m=3$$$, но в массиве есть число $$$4$$$).</p><p>$$$k$$$-сжатие массива рейтинга сделает пользователей CodeCook счастливыми, если оно будет перестановкой. Вам дан массив $$$a$$$, определите для всех $$$1\leq k\leq n$$$ будут ли счастливы пользователи CodeCook после $$$k$$$-сжатия этого массива или нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1\leq t\leq 10^4$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1\leq n\leq 3\cdot 10^5$$$) — длина массива.</p><p>Во второй строке описания каждого набора входных данных находится $$$n$$$ целых чисел $$$a_1,\ldots,a_n$$$ ($$$1\leq a_i\leq n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$3\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите бинарную строку длины $$$n$$$.</p><p>$$$k$$$-й символ строки должен быть $$$1$$$, если пользователи CodeCook будут счастливы после $$$k$$$-сжатия массива $$$a$$$ и $$$0$$$, иначе.</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 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10111
0001
00111
1111111111
000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$a=[1, 5, 3, 4, 2]$$$.</p><ul> <li> $$$1$$$-сжатие массива $$$a$$$ будет $$$[1, 5, 3, 4, 2]$$$ и это перестановка. </li><li> $$$2$$$-сжатие массива $$$a$$$ будет $$$[1, 3, 3, 2]$$$ и это не перестановка, потому что $$$3$$$ встречается дважды. </li><li> $$$3$$$-сжатие массива $$$a$$$ будет $$$[1, 3, 2]$$$ и это перестановка. </li><li> $$$4$$$-сжатие массива $$$a$$$ будет $$$[1, 2]$$$ и это перестановка. </li><li> $$$5$$$-сжатие массива $$$a$$$ будет $$$[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="e70f40637000fd27ce7fe275b8bdec25"/>
<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="69278a83140138beed0a38d33f76b679b59f1fce"/>
<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='e70f40637000fd27ce7fe275b8bdec25'> </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%2F1450%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='e70f40637000fd27ce7fe275b8bdec25'/>
<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/1450">Codeforces Global Round 12</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='e70f40637000fd27ce7fe275b8bdec25'/>
<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/1450/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="Сложность">
*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='e70f40637000fd27ce7fe275b8bdec25'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821295"/>
<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='e70f40637000fd27ce7fe275b8bdec25'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821295"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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_c516662454cc3a6392c33e5763585d25b0683773">
<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>На платформе CodeCook для соревнований по спортивному программированию у каждого человека есть график его рейтинга, описываемый массивом целых чисел $$$a$$$ длины $$$n$$$. Вы обновляете инфраструктуру, поэтому вы создали программу, сжимающую эти графики.</p><p>Программа работает следующим образом. Задается целое число $$$k$$$. Программа берет минимум на каждом последовательном подмассиве длины $$$k$$$ в массиве $$$a$$$.</p><p>Более формально, для массива $$$a$$$ длины $$$n$$$ и целого числа $$$k$$$, определим $$$k$$$-сжатие массива $$$a$$$ как массив $$$b$$$ длины $$$n-k+1$$$, такой что $$$$$$b_j =\min_{j\le i\le j+k-1}a_i$$$$$$</p><p>Например, $$$3$$$-сжатие массива $$$[1, 3, 4, 5, 2]$$$ это $$$[\min\{1, 3, 4\}, \min\{3, 4, 5\}, \min\{4, 5, 2\}]=[1, 3, 2].$$$</p><p>Перестановка длины $$$m$$$ это массив, состоящий из $$$m$$$ различных целых чисел от $$$1$$$ до $$$m$$$ в некотором порядке. Например, $$$[2,3,1,5,4]$$$ это перестановка, но $$$[1,2,2]$$$ это не перестановка ($$$2$$$ встречается дважды в массиве) и $$$[1,3,4]$$$ это тоже не перестановка ($$$m=3$$$, но в массиве есть число $$$4$$$).</p><p>$$$k$$$-сжатие массива рейтинга сделает пользователей CodeCook счастливыми, если оно будет перестановкой. Вам дан массив $$$a$$$, определите для всех $$$1\leq k\leq n$$$ будут ли счастливы пользователи CodeCook после $$$k$$$-сжатия этого массива или нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1\leq t\leq 10^4$$$) — количество наборов входных данных.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1\leq n\leq 3\cdot 10^5$$$) — длина массива.</p><p>Во второй строке описания каждого набора входных данных находится $$$n$$$ целых чисел $$$a_1,\ldots,a_n$$$ ($$$1\leq a_i\leq n$$$) — элементы массива.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$3\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите бинарную строку длины $$$n$$$.</p><p>$$$k$$$-й символ строки должен быть $$$1$$$, если пользователи CodeCook будут счастливы после $$$k$$$-сжатия массива $$$a$$$ и $$$0$$$, иначе.</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 5 3 4 2
4
1 3 2 1
5
1 3 3 3 2
10
1 2 3 4 5 6 7 8 9 10
3
3 3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10111
0001
00111
1111111111
000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$a=[1, 5, 3, 4, 2]$$$.</p><ul> <li> $$$1$$$-сжатие массива $$$a$$$ будет $$$[1, 5, 3, 4, 2]$$$ и это перестановка. </li><li> $$$2$$$-сжатие массива $$$a$$$ будет $$$[1, 3, 3, 2]$$$ и это не перестановка, потому что $$$3$$$ встречается дважды. </li><li> $$$3$$$-сжатие массива $$$a$$$ будет $$$[1, 3, 2]$$$ и это перестановка. </li><li> $$$4$$$-сжатие массива $$$a$$$ будет $$$[1, 2]$$$ и это перестановка. </li><li> $$$5$$$-сжатие массива $$$a$$$ будет $$$[1]$$$ и это перестановка. </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:16: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:'8124b3bdbcad16cb',t:'MTY5NjY2NjU4Ny44OTAwMDA='};_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", "\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"] | ["\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", "\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", "*1800"] | ||
1450E | 1450 | 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>Общество может быть представлено как связный, неориентированный граф с $$$n$$$ вершинами и $$$m$$$ ребрами. Вершины соответствуют людям, а ребро $$$(i,j)$$$ обозначает дружбу между людьми $$$i$$$ и $$$j$$$.</p><p>В этом обществе доход $$$i$$$-о человека равен $$$a_i$$$. Человек $$$i$$$ завидует человеку $$$j$$$, если $$$a_j=a_i+1$$$. То есть человек $$$j$$$ имеет ровно на $$$1$$$ больше дохода, чем человек $$$i$$$.</p><p>Общество называется <span class="tex-font-style-bf">капиталистическим</span>, если для всех пар друзей один из друзей завидует другому. Для некоторых пар друзей вы знаете, какой из друзей завидует другому. Для остальных пар, вы не знаете кто кому завидует.</p><p><span class="tex-font-style-bf">Неравенство доходов</span> общества определяется как $$$\max\limits_{1 \leq i \leq n} a_i - \min\limits_{1 \leq i \leq n} a_i$$$.</p><p>Вы знаете про все существующие пары друзей, но не знаете доходы людей. Если это общество не может быть капиталистическим ни при каких доходах людей, сообщите об этом. Иначе, вы должны найти возможные доходы для всех людей такие, чтобы общество было капиталистическим и неравенство доходов было максимальным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$, $$$m$$$ ($$$1\le n\le 200$$$, $$$n-1\le m\le 2000$$$) — количество людей и пар друзей, соответственно.</p><p>Следующие $$$m$$$ строк описывают пары друзей. Каждая пара друзей описывается тремя целыми числами $$$i$$$, $$$j$$$, $$$b$$$ ($$$1\le i, j\le n, i\ne j, 0\le b\le 1$$$). Это описание означает, что люди $$$i$$$ и $$$j$$$ друзья. Если $$$b=1$$$, то человек $$$i$$$ завидует человеку $$$j$$$. Если $$$b=0$$$, то один из двух друзей должен завидовать другому, но неизвестно кто именно кому.</p><p>Существует не более одной дружбы между любой парой людей. Гарантируется, что если рассмотреть все пары друзей как неориентированные ребра, получившийся граф будет связным.</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><p>Если ответ «<span class="tex-font-style-tt">YES</span>» вы должны вывести еще две строки. В первой строке выведите максимальное возможное неравенство доходов. В следующей строке вы должны вывести $$$n$$$ целых чисел $$$a_1,\ldots, a_n$$$ ($$$0\le a_i\le 10^6$$$), где $$$a_i$$$ это доход $$$i$$$-о человека.</p><p>Можно доказать, что если решение существует, то существует решение, в котором $$$0\le a_i\le 10^6$$$ для всех $$$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>
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
3
3 2 1 3 1 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 4
1 2 1
2 3 0
3 4 1
4 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
0
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте можно показать, что для заданного общества не может быть неравенство доходов, большее чем $$$3$$$. В приведенном ответе с неравенством доходов, равным $$$3$$$:</p><ul> <li> Человек $$$2$$$ завидует человеку $$$1$$$. </li><li> Человек $$$3$$$ завидует человеку $$$2$$$. </li><li> Человек $$$5$$$ завидует человеку $$$2$$$. </li><li> Человек $$$6$$$ завидует человеку $$$5$$$ (удовлетворено условие на то, кто из друзей завидует другому). </li><li> Человек $$$6$$$ завидует человеку $$$3$$$. </li><li> Человек $$$2$$$ завидует человеку $$$4$$$ (удовлетворено условие на то, кто из друзей завидует другому). </li></ul><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="114a3dc035db60225838657417f27203"/>
<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="69278a83140138beed0a38d33f76b679b59f1fce"/>
<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='114a3dc035db60225838657417f27203'> </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%2F1450%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='114a3dc035db60225838657417f27203'/>
<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/1450">Codeforces Global Round 12</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='114a3dc035db60225838657417f27203'/>
<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/1450/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="Сложность">
*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='114a3dc035db60225838657417f27203'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821297"/>
<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='114a3dc035db60225838657417f27203'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821297"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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_e171862241e62a3d55eacf15a6983bcbfc4fc041">
<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>Общество может быть представлено как связный, неориентированный граф с $$$n$$$ вершинами и $$$m$$$ ребрами. Вершины соответствуют людям, а ребро $$$(i,j)$$$ обозначает дружбу между людьми $$$i$$$ и $$$j$$$.</p><p>В этом обществе доход $$$i$$$-о человека равен $$$a_i$$$. Человек $$$i$$$ завидует человеку $$$j$$$, если $$$a_j=a_i+1$$$. То есть человек $$$j$$$ имеет ровно на $$$1$$$ больше дохода, чем человек $$$i$$$.</p><p>Общество называется <span class="tex-font-style-bf">капиталистическим</span>, если для всех пар друзей один из друзей завидует другому. Для некоторых пар друзей вы знаете, какой из друзей завидует другому. Для остальных пар, вы не знаете кто кому завидует.</p><p><span class="tex-font-style-bf">Неравенство доходов</span> общества определяется как $$$\max\limits_{1 \leq i \leq n} a_i - \min\limits_{1 \leq i \leq n} a_i$$$.</p><p>Вы знаете про все существующие пары друзей, но не знаете доходы людей. Если это общество не может быть капиталистическим ни при каких доходах людей, сообщите об этом. Иначе, вы должны найти возможные доходы для всех людей такие, чтобы общество было капиталистическим и неравенство доходов было максимальным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$, $$$m$$$ ($$$1\le n\le 200$$$, $$$n-1\le m\le 2000$$$) — количество людей и пар друзей, соответственно.</p><p>Следующие $$$m$$$ строк описывают пары друзей. Каждая пара друзей описывается тремя целыми числами $$$i$$$, $$$j$$$, $$$b$$$ ($$$1\le i, j\le n, i\ne j, 0\le b\le 1$$$). Это описание означает, что люди $$$i$$$ и $$$j$$$ друзья. Если $$$b=1$$$, то человек $$$i$$$ завидует человеку $$$j$$$. Если $$$b=0$$$, то один из двух друзей должен завидовать другому, но неизвестно кто именно кому.</p><p>Существует не более одной дружбы между любой парой людей. Гарантируется, что если рассмотреть все пары друзей как неориентированные ребра, получившийся граф будет связным.</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><p>Если ответ «<span class="tex-font-style-tt">YES</span>» вы должны вывести еще две строки. В первой строке выведите максимальное возможное неравенство доходов. В следующей строке вы должны вывести $$$n$$$ целых чисел $$$a_1,\ldots, a_n$$$ ($$$0\le a_i\le 10^6$$$), где $$$a_i$$$ это доход $$$i$$$-о человека.</p><p>Можно доказать, что если решение существует, то существует решение, в котором $$$0\le a_i\le 10^6$$$ для всех $$$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>
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
3
3 2 1 3 1 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 4
1 2 1
2 3 0
3 4 1
4 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
0
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте можно показать, что для заданного общества не может быть неравенство доходов, большее чем $$$3$$$. В приведенном ответе с неравенством доходов, равным $$$3$$$:</p><ul> <li> Человек $$$2$$$ завидует человеку $$$1$$$. </li><li> Человек $$$3$$$ завидует человеку $$$2$$$. </li><li> Человек $$$5$$$ завидует человеку $$$2$$$. </li><li> Человек $$$6$$$ завидует человеку $$$5$$$ (удовлетворено условие на то, кто из друзей завидует другому). </li><li> Человек $$$6$$$ завидует человеку $$$3$$$. </li><li> Человек $$$2$$$ завидует человеку $$$4$$$ (удовлетворено условие на то, кто из друзей завидует другому). </li></ul><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:16: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:'8124b3c5fd394975',t:'MTY5NjY2NjU4OS4yNjUwMDA='};_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", "\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", "\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", "*2700"] | ||
1450F | 1450 | F | ru | F. Борющийся участник | <div class="problem-statement"><div class="header"><div class="title">F. Борющийся участник</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>Чтобы помочь тем участникам, которые испытывают трудности в большинстве контестов, основатели Codeforces решили ввести Дивизион 5. В этом новом дивизионе теги всех задач будут анонсированы перед началом раунда, чтобы помочь его участникам.</p><p>Контест состоит из $$$n$$$ задач, где тег $$$i$$$-й задачи определяется целым числом $$$a_i$$$.</p><p>Вы хотите совершить AK (All Kill, решить все задачи). Чтобы это сделать, вы должны решить все задачи в некотором порядке. Чтобы было веселее писать контест, вы задали себе дополнительные ограничения. Вы не хотите подряд решать две задачи с одинаковым тегом, потому что это скучно. Также, вы боитесь больших прыжков в сложности во время решения задач, поэтому вы хотите минимизировать количество раз, когда вы подряд решаете две задачи, не соседние в порядке задач контеста.</p><p>Более формально, ваш порядок решения задач может быть задан перестановкой $$$p$$$ длины $$$n$$$. <span class="tex-font-style-bf">Цена</span> перестановки определяется как количество индексов $$$i$$$ ($$$1\le i<n$$$), таких что $$$|p_{i+1}-p_i|>1$$$. У вас есть требование, что $$$a_{p_i}\ne a_{p_{i+1}}$$$ для всех $$$1\le i< n$$$.</p><p>Вы хотите найти минимальную возможную цену перестановки, которая удовлетворяет этому требованию. Если не существует перестановок, которые ему удовлетворяют, сообщите об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1\leq t\leq 10^4$$$) — количество наборов входных данных.</p><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><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</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>
4
6
2 1 2 3 1 1
5
1 1 1 2 2
8
7 7 2 7 7 1 8 7
10
1 2 3 4 1 1 2 3 4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
3
-1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных рассмотрим $$$p=[5, 4, 3, 2, 1, 6]$$$. Цена этой перестановки будет $$$1$$$, потому что мы прыгаем с $$$p_5=1$$$ на $$$p_6=6$$$ и $$$|6-1|>1$$$. Эта перестановка удовлетворяет требованию, потому что мы не решаем подряд две задачи с одинаковым тегом. Невозможно получить цену, меньшую чем $$$1$$$.</p><p>Во втором наборе входных данных рассмотрим $$$p=[1,5,2,4,3]$$$. Цена этой перестановки будет $$$3$$$, потому что $$$|p_2-p_1|>1$$$, $$$|p_3-p_2|>1$$$ и $$$|p_4-p_3|>1$$$. Эта перестановка удовлетворяет требованию, потому что мы не решаем подряд две задачи с одинаковым тегом. Невозможно получить цену, меньшую чем $$$3$$$.</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="320dde98cbd2757eb24684284775618d"/>
<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="69278a83140138beed0a38d33f76b679b59f1fce"/>
<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='320dde98cbd2757eb24684284775618d'> </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%2F1450%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='320dde98cbd2757eb24684284775618d'/>
<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/1450">Codeforces Global Round 12</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='320dde98cbd2757eb24684284775618d'/>
<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/1450/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="Сложность">
*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='320dde98cbd2757eb24684284775618d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821296"/>
<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='320dde98cbd2757eb24684284775618d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821296"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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_1f212e4195135d54036d41def57244cdd09598b6">
<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>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>Чтобы помочь тем участникам, которые испытывают трудности в большинстве контестов, основатели Codeforces решили ввести Дивизион 5. В этом новом дивизионе теги всех задач будут анонсированы перед началом раунда, чтобы помочь его участникам.</p><p>Контест состоит из $$$n$$$ задач, где тег $$$i$$$-й задачи определяется целым числом $$$a_i$$$.</p><p>Вы хотите совершить AK (All Kill, решить все задачи). Чтобы это сделать, вы должны решить все задачи в некотором порядке. Чтобы было веселее писать контест, вы задали себе дополнительные ограничения. Вы не хотите подряд решать две задачи с одинаковым тегом, потому что это скучно. Также, вы боитесь больших прыжков в сложности во время решения задач, поэтому вы хотите минимизировать количество раз, когда вы подряд решаете две задачи, не соседние в порядке задач контеста.</p><p>Более формально, ваш порядок решения задач может быть задан перестановкой $$$p$$$ длины $$$n$$$. <span class="tex-font-style-bf">Цена</span> перестановки определяется как количество индексов $$$i$$$ ($$$1\le i<n$$$), таких что $$$|p_{i+1}-p_i|>1$$$. У вас есть требование, что $$$a_{p_i}\ne a_{p_{i+1}}$$$ для всех $$$1\le i< n$$$.</p><p>Вы хотите найти минимальную возможную цену перестановки, которая удовлетворяет этому требованию. Если не существует перестановок, которые ему удовлетворяют, сообщите об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1\leq t\leq 10^4$$$) — количество наборов входных данных.</p><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><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</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>
4
6
2 1 2 3 1 1
5
1 1 1 2 2
8
7 7 2 7 7 1 8 7
10
1 2 3 4 1 1 2 3 4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
3
-1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных рассмотрим $$$p=[5, 4, 3, 2, 1, 6]$$$. Цена этой перестановки будет $$$1$$$, потому что мы прыгаем с $$$p_5=1$$$ на $$$p_6=6$$$ и $$$|6-1|>1$$$. Эта перестановка удовлетворяет требованию, потому что мы не решаем подряд две задачи с одинаковым тегом. Невозможно получить цену, меньшую чем $$$1$$$.</p><p>Во втором наборе входных данных рассмотрим $$$p=[1,5,2,4,3]$$$. Цена этой перестановки будет $$$3$$$, потому что $$$|p_2-p_1|>1$$$, $$$|p_3-p_2|>1$$$ и $$$|p_4-p_3|>1$$$. Эта перестановка удовлетворяет требованию, потому что мы не решаем подряд две задачи с одинаковым тегом. Невозможно получить цену, меньшую чем $$$3$$$.</p><p>В третьем наборе входных данных для любого порядка решения задач мы будем подряд решать хотя бы одну пару задач с одинаковым тегом, поэтому ответ $$$-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:16: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:'8124b3ce7976169b',t:'MTY5NjY2NjU5MC41NzgwMDA='};_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", "\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", "*2400"] | ||
1450G | 1450 | G | ru | G. Коммунизм | <div class="problem-statement"><div class="header"><div class="title">G. Коммунизм</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>32 мегабайта</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><span class="tex-font-style-it">В параллельной вселенной сатану звали «Trygub». По этой причине символы из его имени были удалены из алфавита еще в древние времена.</span></p><p>В правительстве есть $$$n$$$ работников, стоящих в ряд и пронумерованных целыми числами от $$$1$$$ до $$$n$$$ слева направо. Категории их работы могут быть описаны строкой $$$s$$$ длины $$$n$$$, в которой символ $$$s_i$$$ обозначает категорию работы $$$i$$$-о работника.</p><p>Новый закон был принят для того, чтобы увеличить равенство между всеми работниками. Правительство решило сделать так, чтобы все работники имели одинаковую категорию работы, делая следующую операцию любое количество раз (возможно ноль).</p><p>Есть зафиксированный <span class="tex-font-style-bf">рациональный</span> параметр $$$k=\frac ab$$$, обозначающий то, насколько просто убедить общественность. Он будет использоваться для того, чтобы определить успешность операции.</p><p>За одну операцию правительство сначала выбирает категорию работы $$$x$$$, такую что существует хотя бы один работник этой категории в текущий момент. Обозначим за $$$i_1,\ldots, i_m$$$ ($$$i_1<\ldots<i_m$$$) позиции всех работников с категорией работы $$$x$$$. Если $$$k\cdot (i_m-i_1+1)\le m$$$, то правительство может выбрать любую категорию работы $$$y$$$, для которой существует хотя бы один работник этой категории в текущий момент и поменять категорию <span class="tex-font-style-bf">всех</span> работников с категорией работы $$$x$$$ на $$$y$$$.</p><p>Если можно сделать так, чтобы все работники имели категорию работы $$$x$$$, мы называем категорию работы $$$x$$$ достижимой. Можете ли вы сказать правительству множество достижимых категорий работы?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится три целых числа $$$n, a, b$$$ ($$$1 \le n \le 5000$$$, $$$1\le a\le b\le 10^5$$$) — количество работников, числитель и знаменатель параметра $$$k$$$, соответственно.</p><p>Во второй строке находится строка $$$s$$$ длины $$$n$$$, состоящая из прописных символов латинского алфавита — категории работы всех работников. <span class="tex-font-style-bf">Символы '<span class="tex-font-style-tt">t</span>', '<span class="tex-font-style-tt">r</span>', '<span class="tex-font-style-tt">y</span>', '<span class="tex-font-style-tt">g</span>', '<span class="tex-font-style-tt">u</span>' и '<span class="tex-font-style-tt">b</span>' не встречаются в строке $$$s$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите целое число $$$c$$$, равное количеству достижимых категорий работы и затем $$$c$$$ символов, разделенных пробелами — достижимые категории работы в лексикографическом порядке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7 1 2
comicom
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 c m o
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первая операция обязана выбрать категорию работы '<span class="tex-font-style-tt">i</span>', потому что все другие категории работы не удовлетворяют условию. Поэтому '<span class="tex-font-style-tt">i</span>' не будет достижимой.</p><p>Ниже показано, как достичь '<span class="tex-font-style-tt">c</span>', '<span class="tex-font-style-tt">m</span>' и '<span class="tex-font-style-tt">o</span>'. Квадратные скобки обозначают отрезок, содержащий всех работников выбранной категории. Красный цвет выделяет эту категорию, синий цвет выделяет новую категорию после операции.</p><ul><li> Получение '<span class="tex-font-style-tt">c</span>': <ol> <li> ($$$\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[o]}}\texttt{com}$$$) </li><li> ($$$\texttt{c}\color{red}{\texttt{[o}}\texttt{m}\color{red}{\texttt{o}}\texttt{c}\color{red}{\texttt{o]}}\texttt{m} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[m}}\texttt{m}\color{#1E90FF}{\texttt{m}}\texttt{c}\color{#1E90FF}{\texttt{m]}}\texttt{m}$$$) </li><li> ($$$\texttt{c}\color{red}{\texttt{[mmm}}\texttt{c}\color{red}{\texttt{mm]}} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[ccc}}\texttt{c}\color{#1E90FF}{\texttt{cc]}}$$$) </li></ol></li><li> Получение '<span class="tex-font-style-tt">m</span>': <ol> <li> ($$$\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[o]}}\texttt{com}$$$) </li><li> ($$$\texttt{c}\color{red}{\texttt{[o}}\texttt{m}\color{red}{\texttt{o}}\texttt{c}\color{red}{\texttt{o]}}\texttt{m} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[c}}\texttt{m}\color{#1E90FF}{\texttt{c}}\texttt{c}\color{#1E90FF}{\texttt{c]}}\texttt{m}$$$) </li><li> ($$$\color{red}{\texttt{[cc}}\texttt{m}\color{red}{\texttt{ccc]}}\texttt{m} \rightarrow \color{#1E90FF}{\texttt{[mm}}\texttt{m}\color{#1E90FF}{\texttt{mmm]}}\texttt{m}$$$) </li></ol></li><li> Получение '<span class="tex-font-style-tt">o</span>': <ol> <li> ($$$\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[c]}}\texttt{com}$$$) </li><li> ($$$\color{red}{\texttt{[c}}\texttt{om}\color{red}{\texttt{cc]}}\texttt{om} \rightarrow \color{#1E90FF}{\texttt{[m}}\texttt{om}\color{#1E90FF}{\texttt{mm]}}\texttt{om}$$$) </li><li> ($$$\color{red}{\texttt{[m}}\texttt{o}\color{red}{\texttt{mmm}}\texttt{o}\color{red}{\texttt{m]}} \rightarrow \color{#1E90FF}{\texttt{[o}}\texttt{o}\color{#1E90FF}{\texttt{ooo}}\texttt{o}\color{#1E90FF}{\texttt{o]}}$$$) </li></ol></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="8b46c602915dead39b40e4fe4d168efa"/>
<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="69278a83140138beed0a38d33f76b679b59f1fce"/>
<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='8b46c602915dead39b40e4fe4d168efa'> </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%2F1450%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='8b46c602915dead39b40e4fe4d168efa'/>
<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/1450">Codeforces Global Round 12</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='8b46c602915dead39b40e4fe4d168efa'/>
<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/1450/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="Сложность">
*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='8b46c602915dead39b40e4fe4d168efa'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821298"/>
<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='8b46c602915dead39b40e4fe4d168efa'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821298"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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_82c4743d15314ea320a82ca5253380fcaf031587">
<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>1.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>32 мегабайта</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><span class="tex-font-style-it">В параллельной вселенной сатану звали «Trygub». По этой причине символы из его имени были удалены из алфавита еще в древние времена.</span></p><p>В правительстве есть $$$n$$$ работников, стоящих в ряд и пронумерованных целыми числами от $$$1$$$ до $$$n$$$ слева направо. Категории их работы могут быть описаны строкой $$$s$$$ длины $$$n$$$, в которой символ $$$s_i$$$ обозначает категорию работы $$$i$$$-о работника.</p><p>Новый закон был принят для того, чтобы увеличить равенство между всеми работниками. Правительство решило сделать так, чтобы все работники имели одинаковую категорию работы, делая следующую операцию любое количество раз (возможно ноль).</p><p>Есть зафиксированный <span class="tex-font-style-bf">рациональный</span> параметр $$$k=\frac ab$$$, обозначающий то, насколько просто убедить общественность. Он будет использоваться для того, чтобы определить успешность операции.</p><p>За одну операцию правительство сначала выбирает категорию работы $$$x$$$, такую что существует хотя бы один работник этой категории в текущий момент. Обозначим за $$$i_1,\ldots, i_m$$$ ($$$i_1<\ldots<i_m$$$) позиции всех работников с категорией работы $$$x$$$. Если $$$k\cdot (i_m-i_1+1)\le m$$$, то правительство может выбрать любую категорию работы $$$y$$$, для которой существует хотя бы один работник этой категории в текущий момент и поменять категорию <span class="tex-font-style-bf">всех</span> работников с категорией работы $$$x$$$ на $$$y$$$.</p><p>Если можно сделать так, чтобы все работники имели категорию работы $$$x$$$, мы называем категорию работы $$$x$$$ достижимой. Можете ли вы сказать правительству множество достижимых категорий работы?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится три целых числа $$$n, a, b$$$ ($$$1 \le n \le 5000$$$, $$$1\le a\le b\le 10^5$$$) — количество работников, числитель и знаменатель параметра $$$k$$$, соответственно.</p><p>Во второй строке находится строка $$$s$$$ длины $$$n$$$, состоящая из прописных символов латинского алфавита — категории работы всех работников. <span class="tex-font-style-bf">Символы '<span class="tex-font-style-tt">t</span>', '<span class="tex-font-style-tt">r</span>', '<span class="tex-font-style-tt">y</span>', '<span class="tex-font-style-tt">g</span>', '<span class="tex-font-style-tt">u</span>' и '<span class="tex-font-style-tt">b</span>' не встречаются в строке $$$s$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите целое число $$$c$$$, равное количеству достижимых категорий работы и затем $$$c$$$ символов, разделенных пробелами — достижимые категории работы в лексикографическом порядке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7 1 2
comicom
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 c m o
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первая операция обязана выбрать категорию работы '<span class="tex-font-style-tt">i</span>', потому что все другие категории работы не удовлетворяют условию. Поэтому '<span class="tex-font-style-tt">i</span>' не будет достижимой.</p><p>Ниже показано, как достичь '<span class="tex-font-style-tt">c</span>', '<span class="tex-font-style-tt">m</span>' и '<span class="tex-font-style-tt">o</span>'. Квадратные скобки обозначают отрезок, содержащий всех работников выбранной категории. Красный цвет выделяет эту категорию, синий цвет выделяет новую категорию после операции.</p><ul><li> Получение '<span class="tex-font-style-tt">c</span>': <ol> <li> ($$$\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[o]}}\texttt{com}$$$) </li><li> ($$$\texttt{c}\color{red}{\texttt{[o}}\texttt{m}\color{red}{\texttt{o}}\texttt{c}\color{red}{\texttt{o]}}\texttt{m} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[m}}\texttt{m}\color{#1E90FF}{\texttt{m}}\texttt{c}\color{#1E90FF}{\texttt{m]}}\texttt{m}$$$) </li><li> ($$$\texttt{c}\color{red}{\texttt{[mmm}}\texttt{c}\color{red}{\texttt{mm]}} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[ccc}}\texttt{c}\color{#1E90FF}{\texttt{cc]}}$$$) </li></ol></li><li> Получение '<span class="tex-font-style-tt">m</span>': <ol> <li> ($$$\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[o]}}\texttt{com}$$$) </li><li> ($$$\texttt{c}\color{red}{\texttt{[o}}\texttt{m}\color{red}{\texttt{o}}\texttt{c}\color{red}{\texttt{o]}}\texttt{m} \rightarrow \texttt{c}\color{#1E90FF}{\texttt{[c}}\texttt{m}\color{#1E90FF}{\texttt{c}}\texttt{c}\color{#1E90FF}{\texttt{c]}}\texttt{m}$$$) </li><li> ($$$\color{red}{\texttt{[cc}}\texttt{m}\color{red}{\texttt{ccc]}}\texttt{m} \rightarrow \color{#1E90FF}{\texttt{[mm}}\texttt{m}\color{#1E90FF}{\texttt{mmm]}}\texttt{m}$$$) </li></ol></li><li> Получение '<span class="tex-font-style-tt">o</span>': <ol> <li> ($$$\texttt{com}\color{red}{\texttt{[i]}}\texttt{com} \rightarrow \texttt{com}\color{#1E90FF}{\texttt{[c]}}\texttt{com}$$$) </li><li> ($$$\color{red}{\texttt{[c}}\texttt{om}\color{red}{\texttt{cc]}}\texttt{om} \rightarrow \color{#1E90FF}{\texttt{[m}}\texttt{om}\color{#1E90FF}{\texttt{mm]}}\texttt{om}$$$) </li><li> ($$$\color{red}{\texttt{[m}}\texttt{o}\color{red}{\texttt{mmm}}\texttt{o}\color{red}{\texttt{m]}} \rightarrow \color{#1E90FF}{\texttt{[o}}\texttt{o}\color{#1E90FF}{\texttt{ooo}}\texttt{o}\color{#1E90FF}{\texttt{o]}}$$$) </li></ol></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:16: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:'8124b3d6dc2e75ab',t:'MTY5NjY2NjU5MS45MTkwMDA='};_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\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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "*3500"] | ||
1450H1 | 1450 | H1 | ru | H1. Соединение нитями (простая версия) | <div class="problem-statement"><div class="header"><div class="title">H1. Соединение нитями (простая версия)</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$$$ катушек, расположенных вокруг круглого стола. Катушки бывают двух цветов: черного и белого.</p><p>Любые две катушки одного цвета можно соединить нитью-отрезком того же цвета. Определим соответствие как способ соединить катушки так, что каждая катушка будет соединена ровно с одной другой катушкой.</p><p>Раскраска это выбор цветов (белого или черного) для каждой катушки. Раскраска называется <span class="tex-font-style-bf">возможной</span>, если для нее существует хотя бы одно соответствие. Это равносильно тому, что количества черных и белых катушек четные.</p><p>Для соответствия можно посчитать количество раз, которое какая-то белая нить пересекает какую-то черную нить. Мы считаем не количество точек пересечения, а количество пар нитей разных цветов, которые пересекаются, поэтому одна точка пересечения может быть посчитана несколько раз, если несколько пар нитей пересекаются в одной и той же точке. Если $$$c$$$ это возможная раскраска, обозначим за $$$f(c)$$$ минимальное количество пересечений по всем возможным корректным соответствиям для этой раскраски.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d05e79f4188f813e260877906d2e54b3011c71ac.png" style="max-width: 100.0%;max-height: 100.0%;"/> Картинка изображает раскраску <span class="tex-font-style-tt">bwbbbwww</span>. Для нарисованного соответствия есть одно пересечение между нитями разного цвета. Можно показать, что это минимальное возможное количество по всем корректным соответствиям для этой раскраски, поэтому $$$f(\text{bwbbbwww}) = 1$$$. </center><p>Вам дана строка $$$s$$$ описывающая <span class="tex-font-style-bf">незавершенную</span> раскраску с черными, белыми и непокрашенными катушками. Раскраска $$$c$$$ называется $$$s$$$-достижимой, если ее можно получить, раскрасив все непокрашенные катушки в $$$s$$$, не меняя цвета остальных.</p><p>Раскраска $$$c$$$ выбирается случайно равновероятно по всем возможным $$$s$$$-достижимым раскраскам. Найдите <a href="https://ru.wikipedia.org/wiki/Математическое_ожидание">математическое ожидание</a> $$$f(c)$$$. Вы должны найти его по модулю $$$998244353$$$.</p><p>Можно показать, что ответ может быть записан в виде $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ некоторые взаимно простые целые числа и $$$q\not\equiv 0\pmod{998244353}$$$. Тогда ответ по модулю $$$998244353$$$ будет равен $$$(p\cdot q^{-1})$$$ modulo $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$, $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ четное, $$$m=0$$$) — количество катушек и изменений, соответственно. В простой версии задачи изменений нет, поэтому оно всегда равно $$$0$$$.</p><p>Во второй строке находится строка $$$s$$$ длины $$$n$$$ — незавершенная раскраска катушек. $$$i$$$-й символ будет '<span class="tex-font-style-tt">w</span>', '<span class="tex-font-style-tt">b</span>' или '<span class="tex-font-style-tt">?</span>', и будет описывать цвет $$$i$$$-й катушки как белый, черный и непокрашенный, соответственно.</p><p>Гарантируется, что существует хотя бы одна непокрашенная катушка.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите математическое ожидание $$$f(c)$$$ по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
8 0
bwbb?www
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 0
???ww?wb??
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
436731905
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 0
bw?b
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый тест почти соответствует картинке. Нельзя покрасить '<span class="tex-font-style-tt">?</span>' в '<span class="tex-font-style-tt">w</span>', потому что тогда получится не возможная раскраска, потому что количество черных катушек будет нечетным. Тогда единственная достижимая возможная раскраска это '<span class="tex-font-style-tt">bwbbbwww</span>'. Поскольку $$$f(\text{bwbbbwww}) = 1$$$ математическое ожидание равно $$$1$$$.</p><p>Можно показать, что математическое ожидание для второго теста равно $$$\frac{9}{16}$$$.</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="e3588529e380ed4115218aec635c24b9"/>
<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="Задача - H1 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="69278a83140138beed0a38d33f76b679b59f1fce"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - H1 - 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='e3588529e380ed4115218aec635c24b9'> </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%2F1450%2Fproblem%2FH1%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='e3588529e380ed4115218aec635c24b9'/>
<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/1450">Codeforces Global Round 12</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='e3588529e380ed4115218aec635c24b9'/>
<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/1450/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="Сложность">
*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='e3588529e380ed4115218aec635c24b9'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821299"/>
<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='e3588529e380ed4115218aec635c24b9'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821299"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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="H1" data-uuid="ps_353263665038db0ec954c878bc152875312fac68">
<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">H1. Соединение нитями (простая версия)</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$$$ катушек, расположенных вокруг круглого стола. Катушки бывают двух цветов: черного и белого.</p><p>Любые две катушки одного цвета можно соединить нитью-отрезком того же цвета. Определим соответствие как способ соединить катушки так, что каждая катушка будет соединена ровно с одной другой катушкой.</p><p>Раскраска это выбор цветов (белого или черного) для каждой катушки. Раскраска называется <span class="tex-font-style-bf">возможной</span>, если для нее существует хотя бы одно соответствие. Это равносильно тому, что количества черных и белых катушек четные.</p><p>Для соответствия можно посчитать количество раз, которое какая-то белая нить пересекает какую-то черную нить. Мы считаем не количество точек пересечения, а количество пар нитей разных цветов, которые пересекаются, поэтому одна точка пересечения может быть посчитана несколько раз, если несколько пар нитей пересекаются в одной и той же точке. Если $$$c$$$ это возможная раскраска, обозначим за $$$f(c)$$$ минимальное количество пересечений по всем возможным корректным соответствиям для этой раскраски.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d05e79f4188f813e260877906d2e54b3011c71ac.png" style="max-width: 100.0%;max-height: 100.0%;" /> Картинка изображает раскраску <span class="tex-font-style-tt">bwbbbwww</span>. Для нарисованного соответствия есть одно пересечение между нитями разного цвета. Можно показать, что это минимальное возможное количество по всем корректным соответствиям для этой раскраски, поэтому $$$f(\text{bwbbbwww}) = 1$$$. </center><p>Вам дана строка $$$s$$$ описывающая <span class="tex-font-style-bf">незавершенную</span> раскраску с черными, белыми и непокрашенными катушками. Раскраска $$$c$$$ называется $$$s$$$-достижимой, если ее можно получить, раскрасив все непокрашенные катушки в $$$s$$$, не меняя цвета остальных.</p><p>Раскраска $$$c$$$ выбирается случайно равновероятно по всем возможным $$$s$$$-достижимым раскраскам. Найдите <a href="https://ru.wikipedia.org/wiki/Математическое_ожидание">математическое ожидание</a> $$$f(c)$$$. Вы должны найти его по модулю $$$998244353$$$.</p><p>Можно показать, что ответ может быть записан в виде $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ некоторые взаимно простые целые числа и $$$q\not\equiv 0\pmod{998244353}$$$. Тогда ответ по модулю $$$998244353$$$ будет равен $$$(p\cdot q^{-1})$$$ modulo $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$, $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ четное, $$$m=0$$$) — количество катушек и изменений, соответственно. В простой версии задачи изменений нет, поэтому оно всегда равно $$$0$$$.</p><p>Во второй строке находится строка $$$s$$$ длины $$$n$$$ — незавершенная раскраска катушек. $$$i$$$-й символ будет '<span class="tex-font-style-tt">w</span>', '<span class="tex-font-style-tt">b</span>' или '<span class="tex-font-style-tt">?</span>', и будет описывать цвет $$$i$$$-й катушки как белый, черный и непокрашенный, соответственно.</p><p>Гарантируется, что существует хотя бы одна непокрашенная катушка.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите математическое ожидание $$$f(c)$$$ по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
8 0
bwbb?www
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 0
???ww?wb??
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
436731905
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 0
bw?b
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый тест почти соответствует картинке. Нельзя покрасить '<span class="tex-font-style-tt">?</span>' в '<span class="tex-font-style-tt">w</span>', потому что тогда получится не возможная раскраска, потому что количество черных катушек будет нечетным. Тогда единственная достижимая возможная раскраска это '<span class="tex-font-style-tt">bwbbbwww</span>'. Поскольку $$$f(\text{bwbbbwww}) = 1$$$ математическое ожидание равно $$$1$$$.</p><p>Можно показать, что математическое ожидание для второго теста равно $$$\frac{9}{16}$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=H1]");
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:16: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:'8124b3df5f989d51',t:'MTY5NjY2NjU5My4zMTUwMDA='};_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", "\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.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u043f\u0444", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2900"] | ||
1450H2 | 1450 | H2 | ru | H2. Соединение нитями (сложная версия) | <div class="problem-statement"><div class="header"><div class="title">H2. Соединение нитями (сложная версия)</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$$$ катушек, расположенных вокруг круглого стола. Катушки бывают двух цветов: черного и белого.</p><p>Любые две катушки одного цвета можно соединить нитью-отрезком того же цвета. Определим соответствие как способ соединить катушки так, что каждая катушка будет соединена ровно с одной другой катушкой.</p><p>Раскраска это выбор цветов (белого или черного) для каждой катушки. Раскраска называется <span class="tex-font-style-bf">возможной</span>, если для нее существует хотя бы одно соответствие. Это равносильно тому, что количества черных и белых катушек четные.</p><p>Для соответствия можно посчитать количество раз, которое какая-то белая нить пересекает какую-то черную нить. Мы считаем не количество точек пересечения, а количество пар нитей разных цветов, которые пересекаются, поэтому одна точка пересечения может быть посчитана несколько раз, если несколько пар нитей пересекаются в одной и той же точке. Если $$$c$$$ это возможная раскраска, обозначим за $$$f(c)$$$ минимальное количество пересечений по всем возможным корректным соответствиям для этой раскраски.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d05e79f4188f813e260877906d2e54b3011c71ac.png" style="max-width: 100.0%;max-height: 100.0%;"/> Картинка изображает раскраску <span class="tex-font-style-tt">bwbbbwww</span>. Для нарисованного соответствия есть одно пересечение между нитями разного цвета. Можно показать, что это минимальное возможное количество по всем корректным соответствиям для этой раскраски, поэтому $$$f(\text{bwbbbwww}) = 1$$$. </center><p>Вам дана строка $$$s$$$ описывающая <span class="tex-font-style-bf">незавершенную</span> раскраску с черными, белыми и непокрашенными катушками. Раскраска $$$c$$$ называется $$$s$$$-достижимой, если ее можно получить, раскрасив все непокрашенные катушки в $$$s$$$, не меняя цвета остальных.</p><p>Раскраска $$$c$$$ выбирается случайно равновероятно по всем возможным $$$s$$$-достижимым раскраскам. Найдите <a href="https://ru.wikipedia.org/wiki/Математическое_ожидание">математическое ожидание</a> $$$f(c)$$$. Вы должны найти его по модулю $$$998244353$$$.</p><p>Также будет производиться $$$m$$$ изменений одного символа в $$$s$$$. После каждого изменения вы должны посчитать математическое ожидание $$$f(c)$$$ снова.</p><p>Можно показать, что каждый ответ может быть записан в виде $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ некоторые взаимно простые целые числа и $$$q\not\equiv 0\pmod{998244353}$$$. Тогда ответ по модулю $$$998244353$$$ будет равен $$$(p\cdot q^{-1})$$$ modulo $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$, $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ четное, $$$0\le m\le 2\cdot 10^5$$$) — количество катушек и изменений, соответственно.</p><p>Во второй строке находится строка $$$s$$$ длины $$$n$$$ — незавершенная раскраска катушек. $$$i$$$-й символ будет '<span class="tex-font-style-tt">w</span>', '<span class="tex-font-style-tt">b</span>' или '<span class="tex-font-style-tt">?</span>', и будет описывать цвет $$$i$$$-й катушки как белый, черный и непокрашенный, соответственно.</p><p>Каждая из следующих $$$m$$$ строк содержит целое число $$$i$$$ ($$$1 \leq i \leq n$$$) — позицию символа в $$$s$$$, который будет изменен и символ $$$c$$$ ($$$c \in \{\text{w}, \text{b}, \text{?}\}$$$) — новый цвет катушки $$$i$$$ после изменения.</p><p>Гарантируется, что существует хотя бы одна непокрашенная катушка изначально и после каждого изменения.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m+1$$$ строку: математическое ожидание $$$f(c)$$$ изначально и после каждого изменения. Все значения должны быть найдены по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
8 0
bwbb?www
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 3
???ww?wb??
4 ?
5 ?
2 w
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
436731905
218365953
374341633
530317313
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 3
bw?b
1 w
2 b
1 w
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
1
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый тест почти соответствует картинке. Нельзя покрасить '<span class="tex-font-style-tt">?</span>' в '<span class="tex-font-style-tt">w</span>', потому что тогда получится не возможная раскраска, потому что количество черных катушек будет нечетным. Тогда единственная достижимая возможная раскраска это '<span class="tex-font-style-tt">bwbbbwww</span>'. Поскольку $$$f(\text{bwbbbwww}) = 1$$$ математическое ожидание равно $$$1$$$.</p><p>Во втором тесте строка после каждого изменения будет:</p><ol> <li> <span class="tex-font-style-tt">????w?wb??</span> </li><li> <span class="tex-font-style-tt">??????wb??</span> </li><li> <span class="tex-font-style-tt">?w????wb??</span> </li></ol><p>В третьем тесте строка после каждого изменения будет:</p><ol> <li> <span class="tex-font-style-tt">ww?b</span> </li><li> <span class="tex-font-style-tt">wb?b</span> </li><li> <span class="tex-font-style-tt">wb?b</span> </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="049df804e797b0e809563303fcc9ecf0"/>
<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="Задача - H2 - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="69278a83140138beed0a38d33f76b679b59f1fce"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - H2 - 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='049df804e797b0e809563303fcc9ecf0'> </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%2F1450%2Fproblem%2FH2%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='049df804e797b0e809563303fcc9ecf0'/>
<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/1450">Codeforces Global Round 12</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='049df804e797b0e809563303fcc9ecf0'/>
<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/1450/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='049df804e797b0e809563303fcc9ecf0'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821300"/>
<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='049df804e797b0e809563303fcc9ecf0'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821300"/>
<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/85224" title="Codeforces Global Round 12" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12538" resourceName="Codeforces Global Round 12"
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/85348" title="Codeforces Global Round 12 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12551" resourceName="Codeforces Global Round 12 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/1450">Задачи</a></li>
<li><a
href="/contest/1450/submit">Отослать</a></li>
<li><a
href="/contest/1450/my">Мои посылки</a></li>
<li><a
href="/contest/1450/status">Статус</a></li>
<li><a
href="/contest/1450/hacks">Взломы</a></li>
<li><a
href="/contest/1450/room/1">Комната</a></li>
<li><a
href="/contest/1450/standings">Положение</a></li>
<li><a
href="/contest/1450/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="H2" data-uuid="ps_9231ab8be08c051a7985c03c4d42cfcb3c253cbe">
<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">H2. Соединение нитями (сложная версия)</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$$$ катушек, расположенных вокруг круглого стола. Катушки бывают двух цветов: черного и белого.</p><p>Любые две катушки одного цвета можно соединить нитью-отрезком того же цвета. Определим соответствие как способ соединить катушки так, что каждая катушка будет соединена ровно с одной другой катушкой.</p><p>Раскраска это выбор цветов (белого или черного) для каждой катушки. Раскраска называется <span class="tex-font-style-bf">возможной</span>, если для нее существует хотя бы одно соответствие. Это равносильно тому, что количества черных и белых катушек четные.</p><p>Для соответствия можно посчитать количество раз, которое какая-то белая нить пересекает какую-то черную нить. Мы считаем не количество точек пересечения, а количество пар нитей разных цветов, которые пересекаются, поэтому одна точка пересечения может быть посчитана несколько раз, если несколько пар нитей пересекаются в одной и той же точке. Если $$$c$$$ это возможная раскраска, обозначим за $$$f(c)$$$ минимальное количество пересечений по всем возможным корректным соответствиям для этой раскраски.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d05e79f4188f813e260877906d2e54b3011c71ac.png" style="max-width: 100.0%;max-height: 100.0%;" /> Картинка изображает раскраску <span class="tex-font-style-tt">bwbbbwww</span>. Для нарисованного соответствия есть одно пересечение между нитями разного цвета. Можно показать, что это минимальное возможное количество по всем корректным соответствиям для этой раскраски, поэтому $$$f(\text{bwbbbwww}) = 1$$$. </center><p>Вам дана строка $$$s$$$ описывающая <span class="tex-font-style-bf">незавершенную</span> раскраску с черными, белыми и непокрашенными катушками. Раскраска $$$c$$$ называется $$$s$$$-достижимой, если ее можно получить, раскрасив все непокрашенные катушки в $$$s$$$, не меняя цвета остальных.</p><p>Раскраска $$$c$$$ выбирается случайно равновероятно по всем возможным $$$s$$$-достижимым раскраскам. Найдите <a href="https://ru.wikipedia.org/wiki/Математическое_ожидание">математическое ожидание</a> $$$f(c)$$$. Вы должны найти его по модулю $$$998244353$$$.</p><p>Также будет производиться $$$m$$$ изменений одного символа в $$$s$$$. После каждого изменения вы должны посчитать математическое ожидание $$$f(c)$$$ снова.</p><p>Можно показать, что каждый ответ может быть записан в виде $$$\frac{p}{q}$$$, где $$$p$$$ и $$$q$$$ некоторые взаимно простые целые числа и $$$q\not\equiv 0\pmod{998244353}$$$. Тогда ответ по модулю $$$998244353$$$ будет равен $$$(p\cdot q^{-1})$$$ modulo $$$998244353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$, $$$m$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ четное, $$$0\le m\le 2\cdot 10^5$$$) — количество катушек и изменений, соответственно.</p><p>Во второй строке находится строка $$$s$$$ длины $$$n$$$ — незавершенная раскраска катушек. $$$i$$$-й символ будет '<span class="tex-font-style-tt">w</span>', '<span class="tex-font-style-tt">b</span>' или '<span class="tex-font-style-tt">?</span>', и будет описывать цвет $$$i$$$-й катушки как белый, черный и непокрашенный, соответственно.</p><p>Каждая из следующих $$$m$$$ строк содержит целое число $$$i$$$ ($$$1 \leq i \leq n$$$) — позицию символа в $$$s$$$, который будет изменен и символ $$$c$$$ ($$$c \in \{\text{w}, \text{b}, \text{?}\}$$$) — новый цвет катушки $$$i$$$ после изменения.</p><p>Гарантируется, что существует хотя бы одна непокрашенная катушка изначально и после каждого изменения.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m+1$$$ строку: математическое ожидание $$$f(c)$$$ изначально и после каждого изменения. Все значения должны быть найдены по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
8 0
bwbb?www
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 3
???ww?wb??
4 ?
5 ?
2 w
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
436731905
218365953
374341633
530317313
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 3
bw?b
1 w
2 b
1 w
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
1
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый тест почти соответствует картинке. Нельзя покрасить '<span class="tex-font-style-tt">?</span>' в '<span class="tex-font-style-tt">w</span>', потому что тогда получится не возможная раскраска, потому что количество черных катушек будет нечетным. Тогда единственная достижимая возможная раскраска это '<span class="tex-font-style-tt">bwbbbwww</span>'. Поскольку $$$f(\text{bwbbbwww}) = 1$$$ математическое ожидание равно $$$1$$$.</p><p>Во втором тесте строка после каждого изменения будет:</p><ol> <li> <span class="tex-font-style-tt">????w?wb??</span> </li><li> <span class="tex-font-style-tt">??????wb??</span> </li><li> <span class="tex-font-style-tt">?w????wb??</span> </li></ol><p>В третьем тесте строка после каждого изменения будет:</p><ol> <li> <span class="tex-font-style-tt">ww?b</span> </li><li> <span class="tex-font-style-tt">wb?b</span> </li><li> <span class="tex-font-style-tt">wb?b</span> </li></ol></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=H2]");
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:16: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:'8124b3e7ee5b1616',t:'MTY5NjY2NjU5NC44NzYwMDA='};_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\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.", "\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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*3300"] | ||
1451A | 1451 | 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>Ridbit начинает с целого числа $$$n$$$.</p><p>За одну операцию он может выполнить одну из следующих операций: </p><ul> <li> разделить $$$n$$$ на один из его <span class="tex-font-style-bf">собственных</span> делителей, или </li><li> вычесть $$$1$$$ из $$$n$$$, если $$$n$$$ больше $$$1$$$. </li></ul><p>Собственным делителем числа называется любой делитель числа, кроме самого числа. Например, $$$1$$$, $$$2$$$, $$$4$$$, $$$5$$$ и $$$10$$$ — это собственные делители $$$20$$$, но само число $$$20$$$ им не является.</p><p>Какое минимальное количество операций понадобится Ridbit, чтобы превратить $$$n$$$ в $$$1$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное необходимое число операций для превращения $$$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>
6
1
2
3
4
6
9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
2
2
2
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для наборов входных данных тестового примера $$$n$$$ может быть превращено в $$$1$$$, используя следующие операции:</p><p>$$$1$$$</p><p>$$$2 \xrightarrow{} 1$$$</p><p>$$$3 \xrightarrow{} 2 \xrightarrow{} 1$$$</p><p>$$$4 \xrightarrow{} 2 \xrightarrow{} 1$$$</p><p>$$$6 \xrightarrow{} 2 \xrightarrow{} 1$$$</p><p>$$$9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 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="840cbc2bdc6dede9569c32eecdeeb97e"/>
<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="25751f0cb3925f7894f023ef82f20d5dc2faac7f"/>
<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='840cbc2bdc6dede9569c32eecdeeb97e'> </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%2F1451%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='840cbc2bdc6dede9569c32eecdeeb97e'/>
<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/1451">Codeforces Round 685 (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='840cbc2bdc6dede9569c32eecdeeb97e'/>
<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/1451/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='840cbc2bdc6dede9569c32eecdeeb97e'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="804297"/>
<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='840cbc2bdc6dede9569c32eecdeeb97e'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="804297"/>
<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/84812" title="Codeforces Round #685 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12422" resourceName="Codeforces Round #685 (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/84885" title="Editorial — Codeforces Round #685" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12415" resourceName="Editorial — Codeforces Round #685"
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/1451">Задачи</a></li>
<li><a
href="/contest/1451/submit">Отослать</a></li>
<li><a
href="/contest/1451/my">Мои посылки</a></li>
<li><a
href="/contest/1451/status">Статус</a></li>
<li><a
href="/contest/1451/hacks">Взломы</a></li>
<li><a
href="/contest/1451/room/1">Комната</a></li>
<li><a
href="/contest/1451/standings">Положение</a></li>
<li><a
href="/contest/1451/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_ba6e80ca8386526bc0bdf3c2fd32d49a3d2a5406">
<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>Ridbit начинает с целого числа $$$n$$$.</p><p>За одну операцию он может выполнить одну из следующих операций: </p><ul> <li> разделить $$$n$$$ на один из его <span class="tex-font-style-bf">собственных</span> делителей, или </li><li> вычесть $$$1$$$ из $$$n$$$, если $$$n$$$ больше $$$1$$$. </li></ul><p>Собственным делителем числа называется любой делитель числа, кроме самого числа. Например, $$$1$$$, $$$2$$$, $$$4$$$, $$$5$$$ и $$$10$$$ — это собственные делители $$$20$$$, но само число $$$20$$$ им не является.</p><p>Какое минимальное количество операций понадобится Ridbit, чтобы превратить $$$n$$$ в $$$1$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное необходимое число операций для превращения $$$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>
6
1
2
3
4
6
9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
2
2
2
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для наборов входных данных тестового примера $$$n$$$ может быть превращено в $$$1$$$, используя следующие операции:</p><p>$$$1$$$</p><p>$$$2 \xrightarrow{} 1$$$</p><p>$$$3 \xrightarrow{} 2 \xrightarrow{} 1$$$</p><p>$$$4 \xrightarrow{} 2 \xrightarrow{} 1$$$</p><p>$$$6 \xrightarrow{} 2 \xrightarrow{} 1$$$</p><p>$$$9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 1$$$</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:16: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:'8124b3f1bf469d6a',t:'MTY5NjY2NjU5Ni4zMjcwMDA='};_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"] | ||
1451B | 1451 | 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>У Hr0d1y есть $$$q$$$ запросов на бинарной строке $$$s$$$ длины $$$n$$$. Бинарная строка это строка, содержащая только символы «<span class="tex-font-style-tt">0</span>» и «<span class="tex-font-style-tt">1</span>».</p><p>Запрос задается парой целых чисел $$$l_i$$$, $$$r_i$$$ $$$(1 \leq l_i \lt r_i \leq n)$$$. </p><p>Для каждого запроса ему необходимо определить, есть ли хорошая подпоследовательность в строке $$$s$$$, которая равна подстроке $$$s[l_i\ldots r_i]$$$. </p><ul> <li> Подстрока $$$s[i\ldots j]$$$ строки $$$s$$$ — это строка из символов $$$s_i s_{i+1} \ldots s_j$$$.</li><li> Строка $$$a$$$ называются подпоследовательностью строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением некоторых символов, не меняя порядка оставшихся.</li><li> Подпоследовательность называется <span class="tex-font-style-bf">хорошей</span>, если она не последовательная и имеет длину $$$\ge 2$$$. Например, если $$$s$$$ равна «<span class="tex-font-style-tt">1100110</span>», то подпоследовательности $$$s_1s_2s_4$$$ («<span class="tex-font-style-tt"><span class="tex-font-style-bf">11</span>0<span class="tex-font-style-bf">0</span>110</span>») и $$$s_1s_5s_7$$$ («<span class="tex-font-style-tt"><span class="tex-font-style-bf">1</span>100<span class="tex-font-style-bf">1</span>1<span class="tex-font-style-bf">0</span></span>») являются хорошими, а $$$s_1s_2s_3$$$ («<span class="tex-font-style-tt"><span class="tex-font-style-bf">110</span>0110</span>») не является. </li></ul><p>Можете ли вы помочь Hr0d1y ответить на каждый запрос?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1\leq t \leq 100$$$) — количество наборов входных данных.</p><p>Далее идут описания наборов входных данных.</p><p>В первой строке записаны два целых числа $$$n$$$ ($$$2 \leq n \leq 100$$$) и $$$q$$$ ($$$1\leq q \leq 100$$$) — длина строки и число запросов. </p><p>Во второй строке записана строка $$$s$$$.</p><p>В $$$i$$$-й из следующих $$$q$$$ строк записаны два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \leq l_i \lt r_i \leq n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$q$$$ строк. В $$$i$$$-й строке ответа на каждый набор входных данных должно быть записано «<span class="tex-font-style-tt">YES</span>», если есть хорошая подпоследовательность, равная подстроке $$$s[l_i...r_i]$$$, и «<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>
2
6 3
001000
2 4
1 3
3 5
4 2
1111
1 4
2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
YES
NO
YES
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных:</p><ul> <li> $$$s[2\ldots 4] = $$$ «<span class="tex-font-style-tt">010</span>». В этом случае $$$s_1s_3s_5$$$ («<span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">0</span>0</span>») и $$$s_2s_3s_6$$$ («<span class="tex-font-style-tt">0<span class="tex-font-style-bf">0</span><span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">0</span></span>») являются подходящими хорошими подпоследовательностями, а $$$s_2s_3s_4$$$ («<span class="tex-font-style-tt">0<span class="tex-font-style-bf">0</span><span class="tex-font-style-bf">1</span><span class="tex-font-style-bf">0</span>00</span>») — нет. </li><li> $$$s[1\ldots 3] = $$$ «<span class="tex-font-style-tt">001</span>». Нет подходящей хорошей подпоследовательности. </li><li> $$$s[3\ldots 5] = $$$ «<span class="tex-font-style-tt">100</span>». В этом случае $$$s_3s_5s_6$$$ («<span class="tex-font-style-tt">00<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">00</span></span>») — это подходящая хорошая подпоследовательность. </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="c2b620bbabfa1cba083087a4bc73a10b"/>
<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="25751f0cb3925f7894f023ef82f20d5dc2faac7f"/>
<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='c2b620bbabfa1cba083087a4bc73a10b'> </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%2F1451%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='c2b620bbabfa1cba083087a4bc73a10b'/>
<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/1451">Codeforces Round 685 (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='c2b620bbabfa1cba083087a4bc73a10b'/>
<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/1451/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="Сложность">
*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='c2b620bbabfa1cba083087a4bc73a10b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="804298"/>
<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='c2b620bbabfa1cba083087a4bc73a10b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="804298"/>
<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/84812" title="Codeforces Round #685 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12422" resourceName="Codeforces Round #685 (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/84885" title="Editorial — Codeforces Round #685" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12415" resourceName="Editorial — Codeforces Round #685"
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/1451">Задачи</a></li>
<li><a
href="/contest/1451/submit">Отослать</a></li>
<li><a
href="/contest/1451/my">Мои посылки</a></li>
<li><a
href="/contest/1451/status">Статус</a></li>
<li><a
href="/contest/1451/hacks">Взломы</a></li>
<li><a
href="/contest/1451/room/1">Комната</a></li>
<li><a
href="/contest/1451/standings">Положение</a></li>
<li><a
href="/contest/1451/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_9f884df47d7df7e914372002888f57481d01b0fe">
<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>У Hr0d1y есть $$$q$$$ запросов на бинарной строке $$$s$$$ длины $$$n$$$. Бинарная строка это строка, содержащая только символы «<span class="tex-font-style-tt">0</span>» и «<span class="tex-font-style-tt">1</span>».</p><p>Запрос задается парой целых чисел $$$l_i$$$, $$$r_i$$$ $$$(1 \leq l_i \lt r_i \leq n)$$$. </p><p>Для каждого запроса ему необходимо определить, есть ли хорошая подпоследовательность в строке $$$s$$$, которая равна подстроке $$$s[l_i\ldots r_i]$$$. </p><ul> <li> Подстрока $$$s[i\ldots j]$$$ строки $$$s$$$ — это строка из символов $$$s_i s_{i+1} \ldots s_j$$$.</li><li> Строка $$$a$$$ называются подпоследовательностью строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением некоторых символов, не меняя порядка оставшихся.</li><li> Подпоследовательность называется <span class="tex-font-style-bf">хорошей</span>, если она не последовательная и имеет длину $$$\ge 2$$$. Например, если $$$s$$$ равна «<span class="tex-font-style-tt">1100110</span>», то подпоследовательности $$$s_1s_2s_4$$$ («<span class="tex-font-style-tt"><span class="tex-font-style-bf">11</span>0<span class="tex-font-style-bf">0</span>110</span>») и $$$s_1s_5s_7$$$ («<span class="tex-font-style-tt"><span class="tex-font-style-bf">1</span>100<span class="tex-font-style-bf">1</span>1<span class="tex-font-style-bf">0</span></span>») являются хорошими, а $$$s_1s_2s_3$$$ («<span class="tex-font-style-tt"><span class="tex-font-style-bf">110</span>0110</span>») не является. </li></ul><p>Можете ли вы помочь Hr0d1y ответить на каждый запрос?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1\leq t \leq 100$$$) — количество наборов входных данных.</p><p>Далее идут описания наборов входных данных.</p><p>В первой строке записаны два целых числа $$$n$$$ ($$$2 \leq n \leq 100$$$) и $$$q$$$ ($$$1\leq q \leq 100$$$) — длина строки и число запросов. </p><p>Во второй строке записана строка $$$s$$$.</p><p>В $$$i$$$-й из следующих $$$q$$$ строк записаны два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \leq l_i \lt r_i \leq n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$q$$$ строк. В $$$i$$$-й строке ответа на каждый набор входных данных должно быть записано «<span class="tex-font-style-tt">YES</span>», если есть хорошая подпоследовательность, равная подстроке $$$s[l_i...r_i]$$$, и «<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>
2
6 3
001000
2 4
1 3
3 5
4 2
1111
1 4
2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
YES
NO
YES
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных:</p><ul> <li> $$$s[2\ldots 4] = $$$ «<span class="tex-font-style-tt">010</span>». В этом случае $$$s_1s_3s_5$$$ («<span class="tex-font-style-tt"><span class="tex-font-style-bf">0</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">0</span>0</span>») и $$$s_2s_3s_6$$$ («<span class="tex-font-style-tt">0<span class="tex-font-style-bf">0</span><span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">0</span></span>») являются подходящими хорошими подпоследовательностями, а $$$s_2s_3s_4$$$ («<span class="tex-font-style-tt">0<span class="tex-font-style-bf">0</span><span class="tex-font-style-bf">1</span><span class="tex-font-style-bf">0</span>00</span>») — нет. </li><li> $$$s[1\ldots 3] = $$$ «<span class="tex-font-style-tt">001</span>». Нет подходящей хорошей подпоследовательности. </li><li> $$$s[3\ldots 5] = $$$ «<span class="tex-font-style-tt">100</span>». В этом случае $$$s_3s_5s_6$$$ («<span class="tex-font-style-tt">00<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">00</span></span>») — это подходящая хорошая подпоследовательность. </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:16: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:'8124b3fab8e77b23',t:'MTY5NjY2NjU5Ny44MDkwMDA='};_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", "\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", "\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", "*900"] | ||
1451C | 1451 | 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>У Ashish есть две строки $$$a$$$ и $$$b$$$ длины $$$n$$$ и целое число $$$k$$$. Строки содержат только строчные буквы латинского алфавита.</p><p>Он хочет превратить строку $$$a$$$ в строку $$$b$$$, исполнив несколько (возможно, ноль) операций над $$$a$$$.</p><p>За одну операцию он может сделать одно из двух возможных действий: </p><ul> <li> выбрать индекс $$$i$$$ ($$$1 \leq i\leq n-1$$$) и поменять местами $$$a_i$$$ и $$$a_{i+1}$$$, или </li><li> выбрать индекс $$$i$$$ ($$$1 \leq i \leq n-k+1$$$) и, если <span class="tex-font-style-bf">все</span> символы среди $$$a_i, a_{i+1}, \ldots, a_{i+k-1}$$$ <span class="tex-font-style-bf">равны</span> какому-то символу $$$c$$$ ($$$c \neq$$$ «<span class="tex-font-style-tt">z</span>»), заменить каждый из них на символ $$$(c+1)$$$, таким образом, «<span class="tex-font-style-tt">a</span>» заменяется на «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">b</span>» заменяется на «<span class="tex-font-style-tt">c</span>» и так далее. </li></ul><p>Обратите внимание, что он может исполнить любое число операций, и операции можно выполнять только на строке $$$a$$$. </p><p>Помогите Ashish определить, возможно ли превратить $$$a$$$ в $$$b$$$, сделав несколько (возможно, ноль) операций на ней.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>В первой строке каждого набора входных данных записаны два целых числа $$$n$$$ ($$$2 \leq n \leq 10^6$$$) и $$$k$$$ ($$$1 \leq k \leq n$$$).</p><p>Во второй строке записана одна строка $$$a$$$ длины $$$n$$$, состоящая только из строчных букв латинского алфавита.</p><p>В третьей строке записана одна строка $$$b$$$ длины $$$n$$$, состоящая только из строчных букв латинского алфавита.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Yes</span>», если Ashish может превратить $$$a$$$ в $$$b$$$ после некоторого числа операций, иначе выведите «<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
3 3
abc
bcd
4 2
abba
azza
2 1
zz
aa
6 2
aaabba
ddddcc
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
Yes
No
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно доказать, что невозможно превратить $$$a$$$ в $$$b$$$.</p><p>Во втором наборе входных данных</p><p>«<span class="tex-font-style-tt">a<span class="tex-font-style-bf">bb</span>a</span>» $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">a<span class="tex-font-style-bf">cc</span>a</span>» $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">azza</span>».</p><p>Здесь «swap» обозначает операцию первого типа, а «inc» обозначает операцию второго типа.</p><p>В третьем наборе входных данных</p><p>«<span class="tex-font-style-tt">aaab<span class="tex-font-style-bf">ba</span></span>» $$$\xrightarrow{\text{swap}}$$$ «<span class="tex-font-style-tt">aaa<span class="tex-font-style-bf">ba</span>b</span>» $$$\xrightarrow{\text{swap}}$$$ «<span class="tex-font-style-tt"><span class="tex-font-style-bf">aa</span>aabb</span>» $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">dd<span class="tex-font-style-bf">aa</span>bb</span>» $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">dddd<span class="tex-font-style-bf">bb</span></span>» $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">ddddcc</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="786b262de1edc12bee58a915d56278ed"/>
<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="25751f0cb3925f7894f023ef82f20d5dc2faac7f"/>
<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='786b262de1edc12bee58a915d56278ed'> </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%2F1451%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='786b262de1edc12bee58a915d56278ed'/>
<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/1451">Codeforces Round 685 (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='786b262de1edc12bee58a915d56278ed'/>
<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/1451/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="Сложность">
*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='786b262de1edc12bee58a915d56278ed'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="804299"/>
<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='786b262de1edc12bee58a915d56278ed'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="804299"/>
<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/84812" title="Codeforces Round #685 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12422" resourceName="Codeforces Round #685 (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/84885" title="Editorial — Codeforces Round #685" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12415" resourceName="Editorial — Codeforces Round #685"
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/1451">Задачи</a></li>
<li><a
href="/contest/1451/submit">Отослать</a></li>
<li><a
href="/contest/1451/my">Мои посылки</a></li>
<li><a
href="/contest/1451/status">Статус</a></li>
<li><a
href="/contest/1451/hacks">Взломы</a></li>
<li><a
href="/contest/1451/room/1">Комната</a></li>
<li><a
href="/contest/1451/standings">Положение</a></li>
<li><a
href="/contest/1451/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_0b08f8ec7cb746fce25ad7761af0413e9a0d1960">
<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>У Ashish есть две строки $$$a$$$ и $$$b$$$ длины $$$n$$$ и целое число $$$k$$$. Строки содержат только строчные буквы латинского алфавита.</p><p>Он хочет превратить строку $$$a$$$ в строку $$$b$$$, исполнив несколько (возможно, ноль) операций над $$$a$$$.</p><p>За одну операцию он может сделать одно из двух возможных действий: </p><ul> <li> выбрать индекс $$$i$$$ ($$$1 \leq i\leq n-1$$$) и поменять местами $$$a_i$$$ и $$$a_{i+1}$$$, или </li><li> выбрать индекс $$$i$$$ ($$$1 \leq i \leq n-k+1$$$) и, если <span class="tex-font-style-bf">все</span> символы среди $$$a_i, a_{i+1}, \ldots, a_{i+k-1}$$$ <span class="tex-font-style-bf">равны</span> какому-то символу $$$c$$$ ($$$c \neq$$$ «<span class="tex-font-style-tt">z</span>»), заменить каждый из них на символ $$$(c+1)$$$, таким образом, «<span class="tex-font-style-tt">a</span>» заменяется на «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">b</span>» заменяется на «<span class="tex-font-style-tt">c</span>» и так далее. </li></ul><p>Обратите внимание, что он может исполнить любое число операций, и операции можно выполнять только на строке $$$a$$$. </p><p>Помогите Ashish определить, возможно ли превратить $$$a$$$ в $$$b$$$, сделав несколько (возможно, ноль) операций на ней.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>В первой строке каждого набора входных данных записаны два целых числа $$$n$$$ ($$$2 \leq n \leq 10^6$$$) и $$$k$$$ ($$$1 \leq k \leq n$$$).</p><p>Во второй строке записана одна строка $$$a$$$ длины $$$n$$$, состоящая только из строчных букв латинского алфавита.</p><p>В третьей строке записана одна строка $$$b$$$ длины $$$n$$$, состоящая только из строчных букв латинского алфавита.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите «<span class="tex-font-style-tt">Yes</span>», если Ashish может превратить $$$a$$$ в $$$b$$$ после некоторого числа операций, иначе выведите «<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
3 3
abc
bcd
4 2
abba
azza
2 1
zz
aa
6 2
aaabba
ddddcc
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
Yes
No
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно доказать, что невозможно превратить $$$a$$$ в $$$b$$$.</p><p>Во втором наборе входных данных</p><p>«<span class="tex-font-style-tt">a<span class="tex-font-style-bf">bb</span>a</span>» $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">a<span class="tex-font-style-bf">cc</span>a</span>» $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">azza</span>».</p><p>Здесь «swap» обозначает операцию первого типа, а «inc» обозначает операцию второго типа.</p><p>В третьем наборе входных данных</p><p>«<span class="tex-font-style-tt">aaab<span class="tex-font-style-bf">ba</span></span>» $$$\xrightarrow{\text{swap}}$$$ «<span class="tex-font-style-tt">aaa<span class="tex-font-style-bf">ba</span>b</span>» $$$\xrightarrow{\text{swap}}$$$ «<span class="tex-font-style-tt"><span class="tex-font-style-bf">aa</span>aabb</span>» $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">dd<span class="tex-font-style-bf">aa</span>bb</span>» $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">dddd<span class="tex-font-style-bf">bb</span></span>» $$$\xrightarrow{\text{inc}}$$$ $$$\ldots$$$ $$$\xrightarrow{\text{inc}}$$$ «<span class="tex-font-style-tt">ddddcc</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:16: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:'8124b403f9839da2',t:'MTY5NjY2NjU5OS4xMzYwMDA='};_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", "\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.", "\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", "\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", "\u0445\u044d\u0448\u0438", "*1400"] | ||
1451D | 1451 | 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>Utkarsh снова заставили играть в игры Ashish. Игроки ходят по очереди, Ashish ходит <span class="tex-font-style-bf">первым</span>.</p><p>Рассмотрим плоскость. На нем стоит фишка, исходно в точке <span class="tex-font-style-bf">$$$(0,0)$$$</span>. За один ход игрок может увеличить либо $$$x$$$ координату, либо $$$y$$$ координату фишки <span class="tex-font-style-bf">ровно</span> на $$$k$$$. Делая эти операции, игрок должен убедиться, что фишка остается в пределах (Евклидового) расстояния $$$d$$$ от $$$(0,0)$$$.</p><p>Иначе говоря, если после хода координаты фишки $$$(p,q)$$$, должно быть выполнено $$$p^2 + q^2 \leq d^2$$$.</p><p>Игра кончается, когда текущий игрок не может сделать ход. Можно доказать, что игра закончится за конечное число ходов. Определите, кто выигрывает при правильной игре обоих игроков.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$d$$$ ($$$1 \leq d \leq 10^5$$$) и $$$k$$$ ($$$1 \leq k \leq d$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если выигрывает первый игрок, выведите «<span class="tex-font-style-tt">Ashish</span>». Иначе выведите «<span class="tex-font-style-tt">Utkarsh</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
2 1
5 2
10 3
25 4
15441 33
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Utkarsh
Ashish
Utkarsh
Utkarsh
Ashish
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможная последовательность действий для первого набора входных данных:</p><p>$$$(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2)$$$.</p><p>Ashish не может сделать ход, так что Utkarsh выигрывает.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/80d946a98e228026f161f95ccc0eb747bbe67ff8.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="ca257092e170a9ab7af3ba4b00716fa0"/>
<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="25751f0cb3925f7894f023ef82f20d5dc2faac7f"/>
<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='ca257092e170a9ab7af3ba4b00716fa0'> </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%2F1451%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='ca257092e170a9ab7af3ba4b00716fa0'/>
<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/1451">Codeforces Round 685 (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='ca257092e170a9ab7af3ba4b00716fa0'/>
<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/1451/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='ca257092e170a9ab7af3ba4b00716fa0'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="804300"/>
<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='ca257092e170a9ab7af3ba4b00716fa0'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="804300"/>
<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/84812" title="Codeforces Round #685 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12422" resourceName="Codeforces Round #685 (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/84885" title="Editorial — Codeforces Round #685" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12415" resourceName="Editorial — Codeforces Round #685"
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/1451">Задачи</a></li>
<li><a
href="/contest/1451/submit">Отослать</a></li>
<li><a
href="/contest/1451/my">Мои посылки</a></li>
<li><a
href="/contest/1451/status">Статус</a></li>
<li><a
href="/contest/1451/hacks">Взломы</a></li>
<li><a
href="/contest/1451/room/1">Комната</a></li>
<li><a
href="/contest/1451/standings">Положение</a></li>
<li><a
href="/contest/1451/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_27b42db16e7b650f354fcbabbcf44c0abb5cc878">
<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>Utkarsh снова заставили играть в игры Ashish. Игроки ходят по очереди, Ashish ходит <span class="tex-font-style-bf">первым</span>.</p><p>Рассмотрим плоскость. На нем стоит фишка, исходно в точке <span class="tex-font-style-bf">$$$(0,0)$$$</span>. За один ход игрок может увеличить либо $$$x$$$ координату, либо $$$y$$$ координату фишки <span class="tex-font-style-bf">ровно</span> на $$$k$$$. Делая эти операции, игрок должен убедиться, что фишка остается в пределах (Евклидового) расстояния $$$d$$$ от $$$(0,0)$$$.</p><p>Иначе говоря, если после хода координаты фишки $$$(p,q)$$$, должно быть выполнено $$$p^2 + q^2 \leq d^2$$$.</p><p>Игра кончается, когда текущий игрок не может сделать ход. Можно доказать, что игра закончится за конечное число ходов. Определите, кто выигрывает при правильной игре обоих игроков.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$d$$$ ($$$1 \leq d \leq 10^5$$$) и $$$k$$$ ($$$1 \leq k \leq d$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если выигрывает первый игрок, выведите «<span class="tex-font-style-tt">Ashish</span>». Иначе выведите «<span class="tex-font-style-tt">Utkarsh</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
2 1
5 2
10 3
25 4
15441 33
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Utkarsh
Ashish
Utkarsh
Utkarsh
Ashish
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможная последовательность действий для первого набора входных данных:</p><p>$$$(0, 0) \xrightarrow{\text{Ashish }} (0, 1) \xrightarrow{\text{Utkarsh }} (0, 2)$$$.</p><p>Ashish не может сделать ход, так что Utkarsh выигрывает.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/80d946a98e228026f161f95ccc0eb747bbe67ff8.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:16: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:'8124b40c4b2900b0',t:'MTY5NjY2NjYwMC40NTQwMDA='};_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\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\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", "\u0438\u0433\u0440\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1700"] | ||
1451E1 | 1451 | E1 | ru | E1. Битовые запросы (упрощенная версия) | <div class="problem-statement"><div class="header"><div class="title">E1. Битовые запросы (упрощенная версия)</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 class="tex-font-style-bf">Это упрощенная версия задачи. Две версии отличаются ограничением на число запросов. Вы можете взламывать по этой задаче только если обе версии решены.</span> </span> <span class="tex-font-style-it">Это интерактивная задача.</span></p><p>У Ridbit есть массив $$$a$$$ из $$$n$$$ целых хочет, и он хочет, чтобы Ashish его отгадал. $$$n$$$ является <span class="tex-font-style-bf">степенью двойки</span>. Ashish может спрашивать запросы трех видов. Они могут быть вида </p><ul> <li> <span class="tex-font-style-tt">AND</span> $$$i$$$ $$$j$$$ — узнать побитовое И элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li><li> <span class="tex-font-style-tt">OR</span> $$$i$$$ $$$j$$$ — узнать побитовое ИЛИ элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li><li> <span class="tex-font-style-tt">XOR</span> $$$i$$$ $$$j$$$ — узнать побитовое исключающее ИЛИ элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li></ul><p>Можете ли вы помочь Ashish определить элементы массива?</p><p><span class="tex-font-style-bf">В этой версии, каждый элемент имеет значение из отрезка $$$[0, n-1]$$$ (включительно) и Ashish может спросить не более $$$n+2$$$ запросов.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(4 \le n \le 2^{16})$$$ — длина массива. Гарантируется, что $$$n$$$ — <span class="tex-font-style-bf">степень двойки</span>.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы сделать запрос, выведите одну из следующих строк (без кавычек): </p><ul> <li> «<span class="tex-font-style-tt">AND i j</span>»; </li><li> «<span class="tex-font-style-tt">OR i j</span>»; </li><li> «<span class="tex-font-style-tt">XOR i j</span>»; </li></ul> где $$$i$$$ и $$$j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ обозначают индексы запроса.<p>На каждый запрос вы получите в ответ одно целое число $$$x$$$, которое означает значение ответа на ваш вопрос. Если ваш запрос некорректный, вы получите в ответ $$$x = -1$$$. В таком случае вам требуется закончить выполнение программы.</p><p>Когда вы угадали элементы массива, вам требуется вывести одну строку, содержащую «<span class="tex-font-style-tt">!</span>» (без кавычек), после чего должны идти $$$n$$$ разделенных пробелами целых чисел — элементы массива.</p><p>Отгадывание массива <span class="tex-font-style-bf">не</span> считается в числе сделанных запросов.</p><p><span class="tex-font-style-bf">Интерактор не является адаптивным.</span> Массив $$$a$$$ не меняется с запросами.</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$$$ $$$(4 \le n \le 2^{16})$$$ — длину массива. Она должна быть степенью двойки. В следующий строке должны быть записаны $$$n$$$ разделенных пробелами целых чисел из отрезка $$$[0, n-1]$$$ — массив $$$a$$$.</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
2
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
OR 1 2
OR 2 3
XOR 2 4
! 0 0 2 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Массив $$$a$$$ в первом примере это $$$[0, 0, 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="bbdb03a4e5b4162358839d4422498c8f"/>
<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="25751f0cb3925f7894f023ef82f20d5dc2faac7f"/>
<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='bbdb03a4e5b4162358839d4422498c8f'> </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%2F1451%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='bbdb03a4e5b4162358839d4422498c8f'/>
<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/1451">Codeforces Round 685 (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='bbdb03a4e5b4162358839d4422498c8f'/>
<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/1451/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='bbdb03a4e5b4162358839d4422498c8f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="804801"/>
<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='bbdb03a4e5b4162358839d4422498c8f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="804801"/>
<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/84812" title="Codeforces Round #685 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12422" resourceName="Codeforces Round #685 (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/84885" title="Editorial — Codeforces Round #685" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12415" resourceName="Editorial — Codeforces Round #685"
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/1451">Задачи</a></li>
<li><a
href="/contest/1451/submit">Отослать</a></li>
<li><a
href="/contest/1451/my">Мои посылки</a></li>
<li><a
href="/contest/1451/status">Статус</a></li>
<li><a
href="/contest/1451/hacks">Взломы</a></li>
<li><a
href="/contest/1451/room/1">Комната</a></li>
<li><a
href="/contest/1451/standings">Положение</a></li>
<li><a
href="/contest/1451/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_4b73805f4c52f7174bb593def820858fab15518c">
<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>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 class="tex-font-style-bf">Это упрощенная версия задачи. Две версии отличаются ограничением на число запросов. Вы можете взламывать по этой задаче только если обе версии решены.</span> </span> <span class="tex-font-style-it">Это интерактивная задача.</span></p><p>У Ridbit есть массив $$$a$$$ из $$$n$$$ целых хочет, и он хочет, чтобы Ashish его отгадал. $$$n$$$ является <span class="tex-font-style-bf">степенью двойки</span>. Ashish может спрашивать запросы трех видов. Они могут быть вида </p><ul> <li> <span class="tex-font-style-tt">AND</span> $$$i$$$ $$$j$$$ — узнать побитовое И элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li><li> <span class="tex-font-style-tt">OR</span> $$$i$$$ $$$j$$$ — узнать побитовое ИЛИ элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li><li> <span class="tex-font-style-tt">XOR</span> $$$i$$$ $$$j$$$ — узнать побитовое исключающее ИЛИ элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li></ul><p>Можете ли вы помочь Ashish определить элементы массива?</p><p><span class="tex-font-style-bf">В этой версии, каждый элемент имеет значение из отрезка $$$[0, n-1]$$$ (включительно) и Ashish может спросить не более $$$n+2$$$ запросов.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(4 \le n \le 2^{16})$$$ — длина массива. Гарантируется, что $$$n$$$ — <span class="tex-font-style-bf">степень двойки</span>.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы сделать запрос, выведите одну из следующих строк (без кавычек): </p><ul> <li> «<span class="tex-font-style-tt">AND i j</span>»; </li><li> «<span class="tex-font-style-tt">OR i j</span>»; </li><li> «<span class="tex-font-style-tt">XOR i j</span>»; </li></ul> где $$$i$$$ и $$$j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ обозначают индексы запроса.<p>На каждый запрос вы получите в ответ одно целое число $$$x$$$, которое означает значение ответа на ваш вопрос. Если ваш запрос некорректный, вы получите в ответ $$$x = -1$$$. В таком случае вам требуется закончить выполнение программы.</p><p>Когда вы угадали элементы массива, вам требуется вывести одну строку, содержащую «<span class="tex-font-style-tt">!</span>» (без кавычек), после чего должны идти $$$n$$$ разделенных пробелами целых чисел — элементы массива.</p><p>Отгадывание массива <span class="tex-font-style-bf">не</span> считается в числе сделанных запросов.</p><p><span class="tex-font-style-bf">Интерактор не является адаптивным.</span> Массив $$$a$$$ не меняется с запросами.</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$$$ $$$(4 \le n \le 2^{16})$$$ — длину массива. Она должна быть степенью двойки. В следующий строке должны быть записаны $$$n$$$ разделенных пробелами целых чисел из отрезка $$$[0, n-1]$$$ — массив $$$a$$$.</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
2
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
OR 1 2
OR 2 3
XOR 2 4
! 0 0 2 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Массив $$$a$$$ в первом примере это $$$[0, 0, 2, 3]$$$.</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:16: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:'8124b4148ee91687',t:'MTY5NjY2NjYwMS44NzMwMDA='};_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", "*2000"] | ||
1451E2 | 1451 | E2 | ru | E2. Битовые запросы (усложенная версия) | <div class="problem-statement"><div class="header"><div class="title">E2. Битовые запросы (усложенная версия)</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 class="tex-font-style-bf">Это усложненная версия задачи. Две версии отличаются ограничением на число запросов. Вы можете взламывать по этой задаче только если обе версии решены.</span> </span></p><p><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>У Ridbit есть массив $$$a$$$ из $$$n$$$ целых хочет, и он хочет, чтобы Ashish его отгадал. $$$n$$$ является <span class="tex-font-style-bf">степенью двойки</span>. Ashish может спрашивать запросы трех видов. Они могут быть вида </p><ul> <li> <span class="tex-font-style-tt">AND</span> $$$i$$$ $$$j$$$ — узнать побитовое И элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li><li> <span class="tex-font-style-tt">OR</span> $$$i$$$ $$$j$$$ — узнать побитовое ИЛИ элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li><li> <span class="tex-font-style-tt">XOR</span> $$$i$$$ $$$j$$$ — узнать побитовое исключающее ИЛИ элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li></ul><p>Можете ли вы помочь Ashish определить элементы массива?</p><p><span class="tex-font-style-bf">В этой версии, каждый элемент имеет значение из отрезка $$$[0, n-1]$$$ (включительно) и Ashish может спросить не более $$$n+1$$$ запросов.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(4 \le n \le 2^{16})$$$ — длина массива. Гарантируется, что $$$n$$$ — <span class="tex-font-style-bf">степень двойки</span>.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы сделать запрос, выведите одну из следующих строк (без кавычек): </p><ul> <li> «<span class="tex-font-style-tt">AND i j</span>»; </li><li> «<span class="tex-font-style-tt">OR i j</span>»; </li><li> «<span class="tex-font-style-tt">XOR i j</span>»; </li></ul> где $$$i$$$ и $$$j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ обозначают индексы запроса.<p>На каждый запрос вы получите в ответ одно целое число $$$x$$$, которое означает значение ответа на ваш вопрос. Если ваш запрос некорректный, вы получите в ответ $$$x = -1$$$. В таком случае вам требуется закончить выполнение программы.</p><p>Когда вы угадали элементы массива, вам требуется вывести одну строку, содержащую «<span class="tex-font-style-tt">!</span>» (без кавычек), после чего должны идти $$$n$$$ разделенных пробелами целых чисел — элементы массива.</p><p>Отгадывание массива <span class="tex-font-style-bf">не</span> считается в числе сделанных запросов.</p><p><span class="tex-font-style-bf">Интерактор не является адаптивным.</span> Массив $$$a$$$ не меняется с запросами.</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$$$ $$$(4 \le n \le 2^{16})$$$ — длину массива. Она должна быть степенью двойки. В следующий строке должны быть записаны $$$n$$$ разделенных пробелами целых чисел из отрезка $$$[0, n-1]$$$ — массив $$$a$$$.</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
2
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
OR 1 2
OR 2 3
XOR 2 4
! 0 0 2 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Массив $$$a$$$ в первом примере это $$$[0, 0, 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="9e1c1efcf9f170aa5a30364db406d292"/>
<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="25751f0cb3925f7894f023ef82f20d5dc2faac7f"/>
<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='9e1c1efcf9f170aa5a30364db406d292'> </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%2F1451%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='9e1c1efcf9f170aa5a30364db406d292'/>
<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/1451">Codeforces Round 685 (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='9e1c1efcf9f170aa5a30364db406d292'/>
<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/1451/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='9e1c1efcf9f170aa5a30364db406d292'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="804302"/>
<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='9e1c1efcf9f170aa5a30364db406d292'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="804302"/>
<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/84812" title="Codeforces Round #685 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12422" resourceName="Codeforces Round #685 (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/84885" title="Editorial — Codeforces Round #685" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12415" resourceName="Editorial — Codeforces Round #685"
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/1451">Задачи</a></li>
<li><a
href="/contest/1451/submit">Отослать</a></li>
<li><a
href="/contest/1451/my">Мои посылки</a></li>
<li><a
href="/contest/1451/status">Статус</a></li>
<li><a
href="/contest/1451/hacks">Взломы</a></li>
<li><a
href="/contest/1451/room/1">Комната</a></li>
<li><a
href="/contest/1451/standings">Положение</a></li>
<li><a
href="/contest/1451/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_c79576641abe916a174b69059a5398b2a708727d">
<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>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 class="tex-font-style-bf">Это усложненная версия задачи. Две версии отличаются ограничением на число запросов. Вы можете взламывать по этой задаче только если обе версии решены.</span> </span></p><p><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>У Ridbit есть массив $$$a$$$ из $$$n$$$ целых хочет, и он хочет, чтобы Ashish его отгадал. $$$n$$$ является <span class="tex-font-style-bf">степенью двойки</span>. Ashish может спрашивать запросы трех видов. Они могут быть вида </p><ul> <li> <span class="tex-font-style-tt">AND</span> $$$i$$$ $$$j$$$ — узнать побитовое И элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li><li> <span class="tex-font-style-tt">OR</span> $$$i$$$ $$$j$$$ — узнать побитовое ИЛИ элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li><li> <span class="tex-font-style-tt">XOR</span> $$$i$$$ $$$j$$$ — узнать побитовое исключающее ИЛИ элементов $$$a_i$$$ и $$$a_j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ </li></ul><p>Можете ли вы помочь Ashish определить элементы массива?</p><p><span class="tex-font-style-bf">В этой версии, каждый элемент имеет значение из отрезка $$$[0, n-1]$$$ (включительно) и Ashish может спросить не более $$$n+1$$$ запросов.</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(4 \le n \le 2^{16})$$$ — длина массива. Гарантируется, что $$$n$$$ — <span class="tex-font-style-bf">степень двойки</span>.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы сделать запрос, выведите одну из следующих строк (без кавычек): </p><ul> <li> «<span class="tex-font-style-tt">AND i j</span>»; </li><li> «<span class="tex-font-style-tt">OR i j</span>»; </li><li> «<span class="tex-font-style-tt">XOR i j</span>»; </li></ul> где $$$i$$$ и $$$j$$$ $$$(1 \leq i, j \le n$$$, $$$i \neq j)$$$ обозначают индексы запроса.<p>На каждый запрос вы получите в ответ одно целое число $$$x$$$, которое означает значение ответа на ваш вопрос. Если ваш запрос некорректный, вы получите в ответ $$$x = -1$$$. В таком случае вам требуется закончить выполнение программы.</p><p>Когда вы угадали элементы массива, вам требуется вывести одну строку, содержащую «<span class="tex-font-style-tt">!</span>» (без кавычек), после чего должны идти $$$n$$$ разделенных пробелами целых чисел — элементы массива.</p><p>Отгадывание массива <span class="tex-font-style-bf">не</span> считается в числе сделанных запросов.</p><p><span class="tex-font-style-bf">Интерактор не является адаптивным.</span> Массив $$$a$$$ не меняется с запросами.</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$$$ $$$(4 \le n \le 2^{16})$$$ — длину массива. Она должна быть степенью двойки. В следующий строке должны быть записаны $$$n$$$ разделенных пробелами целых чисел из отрезка $$$[0, n-1]$$$ — массив $$$a$$$.</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
2
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
OR 1 2
OR 2 3
XOR 2 4
! 0 0 2 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Массив $$$a$$$ в первом примере это $$$[0, 0, 2, 3]$$$.</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:16: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:'8124b41d58c89dab',t:'MTY5NjY2NjYwMy4xODgwMDA='};_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", "*2300"] | ||
1451F | 1451 | 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>Jeel и Ashish играют в игру на матрице $$$n \times m$$$. Строки пронумерованы от $$$1$$$ до $$$n$$$ сверху вниз, а столбцы пронумерованы от $$$1$$$ до $$$m$$$ слева направо. Они ходят по очереди. Ashish ходит <span class="tex-font-style-bf">первым</span>.</p><p>Исходно каждая клетка матрицы содержит неотрицательное целое число. На каждом ходу игрок должен выполнить <span class="tex-font-style-bf">все</span> следующие операции по порядку. </p><ul> <li> Выбрать стартовую клетку $$$(r_1, c_1)$$$ с <span class="tex-font-style-bf">ненулевым</span> значением. </li><li> Выбрать финишную клетку $$$(r_2, c_2)$$$ так, что $$$r_1 \leq r_2$$$ и $$$c_1 \leq c_2$$$. </li><li> Уменьшить значение в стартовой клетке на положительное целое число. </li><li> Выбрать любой кратчайший путь между двумя клетками и уменьшить/увеличить/не изменить все клетки на этом пути. Обратите внимание, что: <ul> <li> кратчайший путь это путь, который проходит по наименьшему числу клеток; </li><li> все клетки на этом пути <span class="tex-font-style-bf">не включают</span> стартовую клетку, но финишная клетка может быть изменена; </li><li> итоговое значение каждой клетки должно быть неотрицательным целым числом; </li><li> клетки изменяются независимо, не обязательно на одно и то же число. </li></ul> </li></ul><p>Если стартовая и финишная клетки совпадают, то, следуя правилам, значение этой клетки уменьшается. Никаких других операций не выполняется.</p><p>Игра заканчивается, когда значения всех клеток равны нулю. Игрок, который не может сделать ход, проигрывает. Можно показать, что при оптимальной игре обоих игроков игра закончится за конечное количество ходов.</p><p>Для данной матрицы, если оба игрока играют оптимально, можете ли вы узнать, кто выиграет?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 10$$$) — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>В первой строке каждого набора входных данных записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 100$$$) — размерности матрицы.</p><p>В каждой из следующих $$$n$$$ строк записаны $$$m$$$ разделенных пробелами целых чисел $$$a_{i,j}$$$ ($$$0 \leq a_{i,j} \leq 10^6$$$) — значения клеток матрицы.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если первый игрок выиграет, выведите «<span class="tex-font-style-tt">Ashish</span>». Иначе выведите «<span class="tex-font-style-tt">Jeel</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 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Jeel
Ashish
Jeel
Ashish
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных единственная клетка матрицы это 0, первый игрок не может сделать хода. Jeel побеждает.</p><p>Во втором наборе входных данных Ashish может выбрать $$$(r_1, c_1) = (r_2, c_2) = (1,3)$$$ и уменьшить значение клетки до $$$0$$$, оставляя $$$[0, 0, 0]$$$. Jeel не может сделать хода. Ashish побеждает.</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="519f266ace23757762426cf9420b01f1"/>
<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="25751f0cb3925f7894f023ef82f20d5dc2faac7f"/>
<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='519f266ace23757762426cf9420b01f1'> </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%2F1451%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='519f266ace23757762426cf9420b01f1'/>
<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/1451">Codeforces Round 685 (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='519f266ace23757762426cf9420b01f1'/>
<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/1451/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="Сложность">
*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='519f266ace23757762426cf9420b01f1'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="804303"/>
<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='519f266ace23757762426cf9420b01f1'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="804303"/>
<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/84812" title="Codeforces Round #685 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12422" resourceName="Codeforces Round #685 (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/84885" title="Editorial — Codeforces Round #685" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12415" resourceName="Editorial — Codeforces Round #685"
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/1451">Задачи</a></li>
<li><a
href="/contest/1451/submit">Отослать</a></li>
<li><a
href="/contest/1451/my">Мои посылки</a></li>
<li><a
href="/contest/1451/status">Статус</a></li>
<li><a
href="/contest/1451/hacks">Взломы</a></li>
<li><a
href="/contest/1451/room/1">Комната</a></li>
<li><a
href="/contest/1451/standings">Положение</a></li>
<li><a
href="/contest/1451/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_46be5bdec2a10bd6cbe8759355112560e77e83de">
<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>Jeel и Ashish играют в игру на матрице $$$n \times m$$$. Строки пронумерованы от $$$1$$$ до $$$n$$$ сверху вниз, а столбцы пронумерованы от $$$1$$$ до $$$m$$$ слева направо. Они ходят по очереди. Ashish ходит <span class="tex-font-style-bf">первым</span>.</p><p>Исходно каждая клетка матрицы содержит неотрицательное целое число. На каждом ходу игрок должен выполнить <span class="tex-font-style-bf">все</span> следующие операции по порядку. </p><ul> <li> Выбрать стартовую клетку $$$(r_1, c_1)$$$ с <span class="tex-font-style-bf">ненулевым</span> значением. </li><li> Выбрать финишную клетку $$$(r_2, c_2)$$$ так, что $$$r_1 \leq r_2$$$ и $$$c_1 \leq c_2$$$. </li><li> Уменьшить значение в стартовой клетке на положительное целое число. </li><li> Выбрать любой кратчайший путь между двумя клетками и уменьшить/увеличить/не изменить все клетки на этом пути. Обратите внимание, что: <ul> <li> кратчайший путь это путь, который проходит по наименьшему числу клеток; </li><li> все клетки на этом пути <span class="tex-font-style-bf">не включают</span> стартовую клетку, но финишная клетка может быть изменена; </li><li> итоговое значение каждой клетки должно быть неотрицательным целым числом; </li><li> клетки изменяются независимо, не обязательно на одно и то же число. </li></ul> </li></ul><p>Если стартовая и финишная клетки совпадают, то, следуя правилам, значение этой клетки уменьшается. Никаких других операций не выполняется.</p><p>Игра заканчивается, когда значения всех клеток равны нулю. Игрок, который не может сделать ход, проигрывает. Можно показать, что при оптимальной игре обоих игроков игра закончится за конечное количество ходов.</p><p>Для данной матрицы, если оба игрока играют оптимально, можете ли вы узнать, кто выиграет?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 10$$$) — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>В первой строке каждого набора входных данных записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 100$$$) — размерности матрицы.</p><p>В каждой из следующих $$$n$$$ строк записаны $$$m$$$ разделенных пробелами целых чисел $$$a_{i,j}$$$ ($$$0 \leq a_{i,j} \leq 10^6$$$) — значения клеток матрицы.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если первый игрок выиграет, выведите «<span class="tex-font-style-tt">Ashish</span>». Иначе выведите «<span class="tex-font-style-tt">Jeel</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 1
0
1 3
0 0 5
2 2
0 1
1 0
3 3
1 2 3
4 5 6
7 8 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Jeel
Ashish
Jeel
Ashish
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных единственная клетка матрицы это 0, первый игрок не может сделать хода. Jeel побеждает.</p><p>Во втором наборе входных данных Ashish может выбрать $$$(r_1, c_1) = (r_2, c_2) = (1,3)$$$ и уменьшить значение клетки до $$$0$$$, оставляя $$$[0, 0, 0]$$$. Jeel не может сделать хода. Ashish побеждает.</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:16: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:'8124b42599f97a79',t:'MTY5NjY2NjYwNC42MjYwMDA='};_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\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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0438\u0433\u0440\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*2700"] | ||
1452A | 1452 | 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>В клетке $$$(0, 0)$$$ 2-мерной решетки стоит робот. Он хочет достичь клетки $$$(x, y)$$$. Вот список команд, которые он может выполнять:</p><ul> <li> пойти на север из клетки $$$(i, j)$$$ в $$$(i, j + 1)$$$; </li><li> пойти на восток из клетки $$$(i, j)$$$ в $$$(i + 1, j)$$$; </li><li> пойти на юг из клетки $$$(i, j)$$$ в $$$(i, j - 1)$$$; </li><li> пойти на запад из клетки $$$(i, j)$$$ в $$$(i - 1, j)$$$; </li><li> остаться в клетке $$$(i, j)$$$. </li></ul><p>Робот хочет достичь клетку $$$(x, y)$$$ за как можно меньшее количество команд. Однако, он не может выполнять одну и ту же команду два или более раза подряд.</p><p>Какое минимальное количество команд необходимо, чтобы достичь $$$(x, y)$$$ из $$$(0, 0)$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В каждой из следующих $$$t$$$ строк записаны по два целых числа $$$x$$$ и $$$y$$$ ($$$0 \le x, y \le 10^4$$$) — координаты клетки назначения робота.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно целое число — минимальное необходимое количество команд, чтобы робот достиг $$$(x, y)$$$ из $$$(0, 0)$$$, если никакую команду нельзя выполнять два или более раза подряд.</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 5
3 4
7 1
0 0
2 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
7
13
0
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение теста из условия:</p><p>Мы используем символы <span class="tex-font-style-tt">N</span>, <span class="tex-font-style-tt">E</span>, <span class="tex-font-style-tt">S</span>, <span class="tex-font-style-tt">W</span> и <span class="tex-font-style-tt">0</span> для обозначения действий «пойти на север», «пойти на восток», «пойти на юг», «пойти на запад» и «остаться на месте», соответственно.</p><p>В первом наборе входных данных робот может использовать следующую последовательность команд: <span class="tex-font-style-tt">NENENENENE</span>.</p><p>Во втором наборе входных данных робот может использовать следующую последовательность команд: <span class="tex-font-style-tt">NENENEN</span>.</p><p>В третьем наборе входных данных робот может использовать следующую последовательность команд: <span class="tex-font-style-tt">ESENENE0ENESE</span>.</p><p>В четвертом наборе входных данных роботу не нужно никуда идти.</p><p>В пятом наборе входных данных робот может использовать следующую последовательность команд: <span class="tex-font-style-tt">E0E</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="841fdda373254c1e0ae629387e0c0416"/>
<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="664af618891471d339d5e2b70e31be7a305d90e1"/>
<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='841fdda373254c1e0ae629387e0c0416'> </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%2F1452%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='841fdda373254c1e0ae629387e0c0416'/>
<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/1452">Educational Codeforces Round 98 (рейтинговый для Див. 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='841fdda373254c1e0ae629387e0c0416'/>
<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/1452/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='841fdda373254c1e0ae629387e0c0416'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="802104"/>
<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='841fdda373254c1e0ae629387e0c0416'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="802104"/>
<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/84758" title="Educational Codeforces Round 98 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12386:12387" 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/84847" title="84847" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12398:12399" 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/1452">Задачи</a></li>
<li><a
href="/contest/1452/submit">Отослать</a></li>
<li><a
href="/contest/1452/my">Мои посылки</a></li>
<li><a
href="/contest/1452/status">Статус</a></li>
<li><a
href="/contest/1452/hacks">Взломы</a></li>
<li><a
href="/contest/1452/standings">Положение</a></li>
<li><a
href="/contest/1452/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_263948ffe727fcd81830f8ab803ec56263ffde47">
<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>В клетке $$$(0, 0)$$$ 2-мерной решетки стоит робот. Он хочет достичь клетки $$$(x, y)$$$. Вот список команд, которые он может выполнять:</p><ul> <li> пойти на север из клетки $$$(i, j)$$$ в $$$(i, j + 1)$$$; </li><li> пойти на восток из клетки $$$(i, j)$$$ в $$$(i + 1, j)$$$; </li><li> пойти на юг из клетки $$$(i, j)$$$ в $$$(i, j - 1)$$$; </li><li> пойти на запад из клетки $$$(i, j)$$$ в $$$(i - 1, j)$$$; </li><li> остаться в клетке $$$(i, j)$$$. </li></ul><p>Робот хочет достичь клетку $$$(x, y)$$$ за как можно меньшее количество команд. Однако, он не может выполнять одну и ту же команду два или более раза подряд.</p><p>Какое минимальное количество команд необходимо, чтобы достичь $$$(x, y)$$$ из $$$(0, 0)$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>В каждой из следующих $$$t$$$ строк записаны по два целых числа $$$x$$$ и $$$y$$$ ($$$0 \le x, y \le 10^4$$$) — координаты клетки назначения робота.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно целое число — минимальное необходимое количество команд, чтобы робот достиг $$$(x, y)$$$ из $$$(0, 0)$$$, если никакую команду нельзя выполнять два или более раза подряд.</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 5
3 4
7 1
0 0
2 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
7
13
0
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Объяснение теста из условия:</p><p>Мы используем символы <span class="tex-font-style-tt">N</span>, <span class="tex-font-style-tt">E</span>, <span class="tex-font-style-tt">S</span>, <span class="tex-font-style-tt">W</span> и <span class="tex-font-style-tt">0</span> для обозначения действий «пойти на север», «пойти на восток», «пойти на юг», «пойти на запад» и «остаться на месте», соответственно.</p><p>В первом наборе входных данных робот может использовать следующую последовательность команд: <span class="tex-font-style-tt">NENENENENE</span>.</p><p>Во втором наборе входных данных робот может использовать следующую последовательность команд: <span class="tex-font-style-tt">NENENEN</span>.</p><p>В третьем наборе входных данных робот может использовать следующую последовательность команд: <span class="tex-font-style-tt">ESENENE0ENESE</span>.</p><p>В четвертом наборе входных данных роботу не нужно никуда идти.</p><p>В пятом наборе входных данных робот может использовать следующую последовательность команд: <span class="tex-font-style-tt">E0E</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:16: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:'8124b42eaa2f9d9e',t:'MTY5NjY2NjYwNi4wMzgwMDA='};_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.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"] | ||
1452B | 1452 | 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$$$ коробок и в $$$i$$$-й коробке лежит $$$a_i$$$ кубиков. Его игра состоит из двух ходов: </p><ol> <li> он выбирает произвольную коробку $$$i$$$; </li><li> он пытается переложить <span class="tex-font-style-bf">все</span> кубики из $$$i$$$-й коробки в другие коробки. </li></ol> Если у него получится сделать равное количество кубиков в каждой из оставшихся $$$n - 1$$$ коробок, то он обрадуется, а если не получится — расстроится. Заметьте, что ваш племянник может перекладывать кубики только из выбранной коробки; он не может перекладывать кубики из других коробок.<p>Вы не хотите, чтобы ваш племянник расстраивался, поэтому вы решили доложить несколько дополнительных кубиков в некоторые коробки так, что независимо от того, какую коробку $$$i$$$ он выберет, он не расстроится. Какое минимальное количество кубиков вам нужно доложить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — количество коробок.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — количество кубиков в каждой коробке.</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>
3
3
3 2 2
4
2 2 3 2
3
0 3 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
0
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, вы можете, например, положить один дополнительный блок в первую коробку и сделать $$$a = [4, 2, 2]$$$. Если ваш племянник выберет коробку с $$$4$$$ кубиками, то он переложит два кубика во вторую коробку и два кубика в третью. Если же он выберет коробку с $$$2$$$ кубиками, то оно переложит эти два кубика в другую коробку с $$$2$$$ кубиками.</p><p>Во втором наборе, вам не нужно докладывать кубики, потому что независимо от того, какую коробку он выберет, он всегда сможет выровнять количество кубиков в других коробках.</p><p>В третьем наборе, вам нужно доложить хотя бы $$$3$$$ кубика. Например, вы можете положить $$$2$$$ кубика в первую коробку и $$$1$$$ кубик в третью. Вы получите $$$a = [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="eb0d2a1e8b09190fa26f080eb01592b8"/>
<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="664af618891471d339d5e2b70e31be7a305d90e1"/>
<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='eb0d2a1e8b09190fa26f080eb01592b8'> </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%2F1452%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='eb0d2a1e8b09190fa26f080eb01592b8'/>
<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/1452">Educational Codeforces Round 98 (рейтинговый для Див. 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='eb0d2a1e8b09190fa26f080eb01592b8'/>
<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/1452/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='eb0d2a1e8b09190fa26f080eb01592b8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="802105"/>
<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='eb0d2a1e8b09190fa26f080eb01592b8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="802105"/>
<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/84758" title="Educational Codeforces Round 98 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12386:12387" 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/84847" title="84847" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12398:12399" 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/1452">Задачи</a></li>
<li><a
href="/contest/1452/submit">Отослать</a></li>
<li><a
href="/contest/1452/my">Мои посылки</a></li>
<li><a
href="/contest/1452/status">Статус</a></li>
<li><a
href="/contest/1452/hacks">Взломы</a></li>
<li><a
href="/contest/1452/standings">Положение</a></li>
<li><a
href="/contest/1452/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_e2c6a3c1879fe526ccd2830f1777ab63e33504aa">
<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$$$ коробок и в $$$i$$$-й коробке лежит $$$a_i$$$ кубиков. Его игра состоит из двух ходов: </p><ol> <li> он выбирает произвольную коробку $$$i$$$; </li><li> он пытается переложить <span class="tex-font-style-bf">все</span> кубики из $$$i$$$-й коробки в другие коробки. </li></ol> Если у него получится сделать равное количество кубиков в каждой из оставшихся $$$n - 1$$$ коробок, то он обрадуется, а если не получится — расстроится. Заметьте, что ваш племянник может перекладывать кубики только из выбранной коробки; он не может перекладывать кубики из других коробок.<p>Вы не хотите, чтобы ваш племянник расстраивался, поэтому вы решили доложить несколько дополнительных кубиков в некоторые коробки так, что независимо от того, какую коробку $$$i$$$ он выберет, он не расстроится. Какое минимальное количество кубиков вам нужно доложить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — количество коробок.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — количество кубиков в каждой коробке.</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>
3
3
3 2 2
4
2 2 3 2
3
0 3 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
0
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, вы можете, например, положить один дополнительный блок в первую коробку и сделать $$$a = [4, 2, 2]$$$. Если ваш племянник выберет коробку с $$$4$$$ кубиками, то он переложит два кубика во вторую коробку и два кубика в третью. Если же он выберет коробку с $$$2$$$ кубиками, то оно переложит эти два кубика в другую коробку с $$$2$$$ кубиками.</p><p>Во втором наборе, вам не нужно докладывать кубики, потому что независимо от того, какую коробку он выберет, он всегда сможет выровнять количество кубиков в других коробках.</p><p>В третьем наборе, вам нужно доложить хотя бы $$$3$$$ кубика. Например, вы можете положить $$$2$$$ кубика в первую коробку и $$$1$$$ кубик в третью. Вы получите $$$a = [2, 3, 1]$$$.</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:16: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:'8124b4376d3d1490',t:'MTY5NjY2NjYwNy4zOTgwMDA='};_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.", "\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", "\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", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1400"] | ||
1452C | 1452 | 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>Дана последовательность $$$s$$$, состоящая из скобок двух типов: '<span class="tex-font-style-tt">(</span>', '<span class="tex-font-style-tt">)</span>', '<span class="tex-font-style-tt">[</span>' и '<span class="tex-font-style-tt">]</span>'.</p><p>Строка называется правильной скобочной последовательностью (ПСП), если она одного из следующих типов: </p><ul> <li> пустая строка; </li><li> '<span class="tex-font-style-tt">(</span>' + ПСП + '<span class="tex-font-style-tt">)</span>'; </li><li> '<span class="tex-font-style-tt">[</span>' + ПСП + '<span class="tex-font-style-tt">]</span>'; </li><li> ПСП + ПСП. </li></ul><p>где плюс — это операция склеивания двух строк.</p><p>За один ход можно выбрать непустую подпоследовательность символов строки $$$s$$$ (не обязательно подряд идущих), которые являются ПСП, удалить их из строки и склеить оставшиеся части, не изменяя порядка.</p><p>Какое наибольшее количество ходов можно совершить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В каждой из следующих $$$t$$$ строк содержится одна непустая строка, состоящая только из символов '<span class="tex-font-style-tt">(</span>', '<span class="tex-font-style-tt">)</span>', '<span class="tex-font-style-tt">[</span>' и '<span class="tex-font-style-tt">]</span>'. Суммарная длина строк по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — наибольшее количество ходов, которые можно совершить с данной строкой $$$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
()
[]()
([)]
)]([
)[(]
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
2
0
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно просто удалить всю строку.</p><p>Во втором примере можно сначала удалить скобки на позициях $$$1$$$ и $$$2$$$: «<span class="tex-font-style-tt"><span class="tex-font-style-bf">[]</span>()</span>», затем останется «<span class="tex-font-style-tt">()</span>». Потом можно удалить строку целиком. Можно было и сразу удалить всю строку, но тогда была бы одна операция вместо двух.</p><p>В третьем примере можно сначала удалить скобки на позициях $$$1$$$ и $$$3$$$: «<span class="tex-font-style-tt"><span class="tex-font-style-bf">(</span>[<span class="tex-font-style-bf">)</span>]</span>». Они образуют ПСП «<span class="tex-font-style-tt">()</span>». Затем останется «<span class="tex-font-style-tt">[]</span>», поэтому можно удалить ее целиком.</p><p>В четвертом примере нет ни одной подпоследовательности, которая является ПСП, поэтому нельзя совершить ни один ход.</p><p>В пятом примере можно удалить скобки на позициях $$$2$$$ и $$$4$$$: «<span class="tex-font-style-tt">)<span class="tex-font-style-bf">[</span>(<span class="tex-font-style-bf">]</span></span>» и получить «<span class="tex-font-style-tt">)(</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="5cf0618d23cba919a7e95483d0c44e61"/>
<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="664af618891471d339d5e2b70e31be7a305d90e1"/>
<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='5cf0618d23cba919a7e95483d0c44e61'> </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%2F1452%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='5cf0618d23cba919a7e95483d0c44e61'/>
<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/1452">Educational Codeforces Round 98 (рейтинговый для Див. 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='5cf0618d23cba919a7e95483d0c44e61'/>
<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/1452/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='5cf0618d23cba919a7e95483d0c44e61'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="802106"/>
<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='5cf0618d23cba919a7e95483d0c44e61'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="802106"/>
<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/84758" title="Educational Codeforces Round 98 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12386:12387" 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/84847" title="84847" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12398:12399" 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/1452">Задачи</a></li>
<li><a
href="/contest/1452/submit">Отослать</a></li>
<li><a
href="/contest/1452/my">Мои посылки</a></li>
<li><a
href="/contest/1452/status">Статус</a></li>
<li><a
href="/contest/1452/hacks">Взломы</a></li>
<li><a
href="/contest/1452/standings">Положение</a></li>
<li><a
href="/contest/1452/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_8278c40eb283bc1f65242dcd824431dd46bd7547">
<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>Дана последовательность $$$s$$$, состоящая из скобок двух типов: '<span class="tex-font-style-tt">(</span>', '<span class="tex-font-style-tt">)</span>', '<span class="tex-font-style-tt">[</span>' и '<span class="tex-font-style-tt">]</span>'.</p><p>Строка называется правильной скобочной последовательностью (ПСП), если она одного из следующих типов: </p><ul> <li> пустая строка; </li><li> '<span class="tex-font-style-tt">(</span>' + ПСП + '<span class="tex-font-style-tt">)</span>'; </li><li> '<span class="tex-font-style-tt">[</span>' + ПСП + '<span class="tex-font-style-tt">]</span>'; </li><li> ПСП + ПСП. </li></ul><p>где плюс — это операция склеивания двух строк.</p><p>За один ход можно выбрать непустую подпоследовательность символов строки $$$s$$$ (не обязательно подряд идущих), которые являются ПСП, удалить их из строки и склеить оставшиеся части, не изменяя порядка.</p><p>Какое наибольшее количество ходов можно совершить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В каждой из следующих $$$t$$$ строк содержится одна непустая строка, состоящая только из символов '<span class="tex-font-style-tt">(</span>', '<span class="tex-font-style-tt">)</span>', '<span class="tex-font-style-tt">[</span>' и '<span class="tex-font-style-tt">]</span>'. Суммарная длина строк по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — наибольшее количество ходов, которые можно совершить с данной строкой $$$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
()
[]()
([)]
)]([
)[(]
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
2
0
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно просто удалить всю строку.</p><p>Во втором примере можно сначала удалить скобки на позициях $$$1$$$ и $$$2$$$: «<span class="tex-font-style-tt"><span class="tex-font-style-bf">[]</span>()</span>», затем останется «<span class="tex-font-style-tt">()</span>». Потом можно удалить строку целиком. Можно было и сразу удалить всю строку, но тогда была бы одна операция вместо двух.</p><p>В третьем примере можно сначала удалить скобки на позициях $$$1$$$ и $$$3$$$: «<span class="tex-font-style-tt"><span class="tex-font-style-bf">(</span>[<span class="tex-font-style-bf">)</span>]</span>». Они образуют ПСП «<span class="tex-font-style-tt">()</span>». Затем останется «<span class="tex-font-style-tt">[]</span>», поэтому можно удалить ее целиком.</p><p>В четвертом примере нет ни одной подпоследовательности, которая является ПСП, поэтому нельзя совершить ни один ход.</p><p>В пятом примере можно удалить скобки на позициях $$$2$$$ и $$$4$$$: «<span class="tex-font-style-tt">)<span class="tex-font-style-bf">[</span>(<span class="tex-font-style-bf">]</span></span>» и получить «<span class="tex-font-style-tt">)(</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:16: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:'8124b43ffaeb1660',t:'MTY5NjY2NjYwOC43NTcwMDA='};_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"] | ||
1452D | 1452 | 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 + 2$$$ города, с номерами от $$$0$$$ до $$$n + 1$$$. $$$i$$$-й город расположен в точке $$$i$$$.</p><p>В каждом из городов $$$1, 2, \dots, n$$$ с вероятностью $$$\frac{1}{2}$$$ строится радиовышка (эти события независимы). После этого вы хотите установить мощность сигнала каждой вышки равной целому числу от $$$1$$$ до $$$n$$$ (мощность сигнала не обязательно одинакова для всех вышек, но и не обязательно отличается). Сигнал с вышки, расположенной в городе $$$i$$$ с мощностью сигнала $$$p$$$, достигает каждого города $$$c$$$, что $$$|c - i| < p$$$.</p><p>После постройки вышек вы хотите выбрать мощность сигнала таким образом, чтобы:</p><ul> <li> города $$$0$$$ и $$$n + 1$$$ не получали сигнал от радиовышек; </li><li> города $$$1, 2, \dots, n$$$ получали сигнал <span class="tex-font-style-it">ровно</span> от одной радиовышки каждый. </li></ul><p>Например, если $$$n = 5$$$, и вышки построены в городах $$$2$$$, $$$4$$$ и $$$5$$$, вы можете установить мощность сигнала вышки в городе $$$2$$$ равной $$$2$$$, а мощность сигнала вышек в городах $$$4$$$ и $$$5$$$ равной $$$1$$$. Таким образом, города $$$0$$$ и $$$n + 1$$$ не получат сигнал ни от одной вышки, города $$$1$$$, $$$2$$$ и $$$3$$$ получат сигнал от вышки в городе $$$2$$$, город $$$4$$$ получит сигнал от вышки в городе $$$4$$$, а город $$$5$$$ получит сигнал от вышки в городе $$$5$$$.</p><p>Посчитайте вероятность того, что после постройки вышек у вас будет возможность установить мощность сигнала каждой из них, чтобы удовлетворить всем ограничениям.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая (и единственная) строка входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность того, что найдется способ установить мощность сигнала так, чтобы все ограничения были выполнены, взятая по модулю $$$998244353$$$.</p><p>Вероятность можно выразить в виде несократимой дроби $$$\frac{x}{y}$$$. Вы должны вывести значение $$$x \cdot y^{-1} \bmod 998244353$$$, где $$$y^{-1}$$$ — целое число, такое, что $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
748683265
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
748683265
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
842268673
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
200000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
202370013
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Настоящий ответ для первого примера — $$$\frac{1}{4}$$$:</p><ul> <li> с вероятностью $$$\frac{1}{4}$$$ вышки построены в обоих городах $$$1$$$ и $$$2$$$, поэтому мы можем установить их мощность сигнала равной $$$1$$$. </li></ul><p>Настоящий ответ для второго примера — $$$\frac{1}{4}$$$: </p><ul> <li> с вероятностью $$$\frac{1}{8}$$$ вышки построены в городах $$$1$$$, $$$2$$$ и $$$3$$$, поэтому мы можем установить их мощность сигнала равной $$$1$$$; </li><li> с вероятностью $$$\frac{1}{8}$$$ построена только одна башня в городе $$$2$$$, и мы можем установить ее мощность сигнала равной $$$2$$$. </li></ul><p>Настоящий ответ для третьего примера — $$$\frac{5}{32}$$$. Обратите внимание, что даже если предыдущие пояснения использовали равные мощности сигнала для всех башен, это не обязательно так. Например, если $$$n = 5$$$ и башни построены в городах $$$2$$$, $$$4$$$ и $$$5$$$, вы можете установить мощность сигнала башни в городе $$$2$$$ равной $$$2$$$, а мощность сигнала башен в городах $$$4$$$ и $$$5$$$ равной $$$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="7a81e8fc3ac93f12b86a01aaf5c282a9"/>
<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="664af618891471d339d5e2b70e31be7a305d90e1"/>
<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='7a81e8fc3ac93f12b86a01aaf5c282a9'> </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%2F1452%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='7a81e8fc3ac93f12b86a01aaf5c282a9'/>
<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/1452">Educational Codeforces Round 98 (рейтинговый для Див. 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='7a81e8fc3ac93f12b86a01aaf5c282a9'/>
<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/1452/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='7a81e8fc3ac93f12b86a01aaf5c282a9'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="802107"/>
<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='7a81e8fc3ac93f12b86a01aaf5c282a9'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="802107"/>
<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/84758" title="Educational Codeforces Round 98 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12386:12387" 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/84847" title="84847" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12398:12399" 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/1452">Задачи</a></li>
<li><a
href="/contest/1452/submit">Отослать</a></li>
<li><a
href="/contest/1452/my">Мои посылки</a></li>
<li><a
href="/contest/1452/status">Статус</a></li>
<li><a
href="/contest/1452/hacks">Взломы</a></li>
<li><a
href="/contest/1452/standings">Положение</a></li>
<li><a
href="/contest/1452/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_7ae22c8d88412f0a4ad8b2745d5951ebfe46e690">
<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 + 2$$$ города, с номерами от $$$0$$$ до $$$n + 1$$$. $$$i$$$-й город расположен в точке $$$i$$$.</p><p>В каждом из городов $$$1, 2, \dots, n$$$ с вероятностью $$$\frac{1}{2}$$$ строится радиовышка (эти события независимы). После этого вы хотите установить мощность сигнала каждой вышки равной целому числу от $$$1$$$ до $$$n$$$ (мощность сигнала не обязательно одинакова для всех вышек, но и не обязательно отличается). Сигнал с вышки, расположенной в городе $$$i$$$ с мощностью сигнала $$$p$$$, достигает каждого города $$$c$$$, что $$$|c - i| < p$$$.</p><p>После постройки вышек вы хотите выбрать мощность сигнала таким образом, чтобы:</p><ul> <li> города $$$0$$$ и $$$n + 1$$$ не получали сигнал от радиовышек; </li><li> города $$$1, 2, \dots, n$$$ получали сигнал <span class="tex-font-style-it">ровно</span> от одной радиовышки каждый. </li></ul><p>Например, если $$$n = 5$$$, и вышки построены в городах $$$2$$$, $$$4$$$ и $$$5$$$, вы можете установить мощность сигнала вышки в городе $$$2$$$ равной $$$2$$$, а мощность сигнала вышек в городах $$$4$$$ и $$$5$$$ равной $$$1$$$. Таким образом, города $$$0$$$ и $$$n + 1$$$ не получат сигнал ни от одной вышки, города $$$1$$$, $$$2$$$ и $$$3$$$ получат сигнал от вышки в городе $$$2$$$, город $$$4$$$ получит сигнал от вышки в городе $$$4$$$, а город $$$5$$$ получит сигнал от вышки в городе $$$5$$$.</p><p>Посчитайте вероятность того, что после постройки вышек у вас будет возможность установить мощность сигнала каждой из них, чтобы удовлетворить всем ограничениям.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая (и единственная) строка входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность того, что найдется способ установить мощность сигнала так, чтобы все ограничения были выполнены, взятая по модулю $$$998244353$$$.</p><p>Вероятность можно выразить в виде несократимой дроби $$$\frac{x}{y}$$$. Вы должны вывести значение $$$x \cdot y^{-1} \bmod 998244353$$$, где $$$y^{-1}$$$ — целое число, такое, что $$$y \cdot y^{-1} \bmod 998244353 = 1$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
748683265
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
748683265
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
842268673
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
200000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
202370013
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Настоящий ответ для первого примера — $$$\frac{1}{4}$$$:</p><ul> <li> с вероятностью $$$\frac{1}{4}$$$ вышки построены в обоих городах $$$1$$$ и $$$2$$$, поэтому мы можем установить их мощность сигнала равной $$$1$$$. </li></ul><p>Настоящий ответ для второго примера — $$$\frac{1}{4}$$$: </p><ul> <li> с вероятностью $$$\frac{1}{8}$$$ вышки построены в городах $$$1$$$, $$$2$$$ и $$$3$$$, поэтому мы можем установить их мощность сигнала равной $$$1$$$; </li><li> с вероятностью $$$\frac{1}{8}$$$ построена только одна башня в городе $$$2$$$, и мы можем установить ее мощность сигнала равной $$$2$$$. </li></ul><p>Настоящий ответ для третьего примера — $$$\frac{5}{32}$$$. Обратите внимание, что даже если предыдущие пояснения использовали равные мощности сигнала для всех башен, это не обязательно так. Например, если $$$n = 5$$$ и башни построены в городах $$$2$$$, $$$4$$$ и $$$5$$$, вы можете установить мощность сигнала башни в городе $$$2$$$ равной $$$2$$$, а мощность сигнала башен в городах $$$4$$$ и $$$5$$$ равной $$$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:16: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:'8124b44878ad4991',t:'MTY5NjY2NjYxMC4yNDAwMDA='};_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.", "\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", "*1600"] | ||
1452E | 1452 | 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>Только что завершился Берляндский региональный отбор к ICPC. Было $$$m$$$ участников, пронумерованных от $$$1$$$ до $$$m$$$, которые решали $$$n$$$ задач, пронумерованных от $$$1$$$ до $$$n$$$.</p><p>Сейчас будет проходить разбор. Два автора задач готовы разобрать по <span class="tex-font-style-bf">$$$k$$$ последовательных задач</span> каждый. Авторы выбирают отрезки из $$$k$$$ последовательных задач независимо друг от друга. Отрезки могут совпадать, пересекаться или не пересекаться вообще.</p><p>$$$i$$$-й участник хочет послушать разбор всех последовательных задач с $$$l_i$$$ по $$$r_i$$$. Каждый участник всегда выбирает слушать разбор только того автора, который расскажет большее количество интересных ему задач. Пусть это количество будет равно $$$a_i$$$. Никто не может слушать разбор обоих авторов, даже если их отрезки не пересекаются.</p><p>Авторы задач хотят выбрать отрезки из $$$k$$$ последовательных задач для себя так, чтобы сумма $$$a_i$$$ по всем участникам была как можно больше.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n, m$$$ и $$$k$$$ ($$$1 \le n, m \le 2000$$$, $$$1 \le k \le n$$$) — количество задач, количество участников и длина отрезка задач, разбор на которые планирует рассказать каждый из авторов.</p><p>В $$$i$$$-й из следующих $$$m$$$ строк записаны по два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — отрезок задач, разбор на которые хочет послушать $$$i$$$-й участник.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — наибольшую возможную сумму $$$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>
10 5 3
1 3
2 4
6 9
6 9
1 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
14
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 3 3
2 4
4 6
3 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 4 1
3 3
1 1
2 2
4 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 4 5
1 2
2 3
3 4
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере первый автор может рассказать разбор по задачам с $$$1$$$ по $$$3$$$, а второй — с $$$6$$$ по $$$8$$$. Тогда последовательность $$$a_i$$$ будет $$$[3, 2, 3, 3, 3]$$$. Обратите внимание, что последний участник не может послушать обоих авторов, он выбирает только того, кто расскажет ему больше интересующих его задач.</p><p>Во втором примере первый может рассказать задачи с $$$2$$$ по $$$4$$$, а второй — с $$$4$$$ по $$$6$$$.</p><p>В третьем примере первый может рассказать задачи с $$$1$$$ по $$$1$$$, а второй — с $$$2$$$ по $$$2$$$. Или с $$$4$$$ по $$$4$$$ и с $$$3$$$ по $$$3$$$. Любая пара различных задач даст одинаковую сумму $$$2$$$.</p><p>В четвертом примере первый может рассказать задачи с $$$1$$$ по $$$5$$$ и второй тоже с $$$1$$$ по $$$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="f6c4ae7c5bbd1735fd4dd31df8452b5b"/>
<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="664af618891471d339d5e2b70e31be7a305d90e1"/>
<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='f6c4ae7c5bbd1735fd4dd31df8452b5b'> </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%2F1452%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='f6c4ae7c5bbd1735fd4dd31df8452b5b'/>
<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/1452">Educational Codeforces Round 98 (рейтинговый для Див. 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='f6c4ae7c5bbd1735fd4dd31df8452b5b'/>
<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/1452/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='f6c4ae7c5bbd1735fd4dd31df8452b5b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="802108"/>
<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='f6c4ae7c5bbd1735fd4dd31df8452b5b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="802108"/>
<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/84758" title="Educational Codeforces Round 98 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12386:12387" 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/84847" title="84847" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12398:12399" 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/1452">Задачи</a></li>
<li><a
href="/contest/1452/submit">Отослать</a></li>
<li><a
href="/contest/1452/my">Мои посылки</a></li>
<li><a
href="/contest/1452/status">Статус</a></li>
<li><a
href="/contest/1452/hacks">Взломы</a></li>
<li><a
href="/contest/1452/standings">Положение</a></li>
<li><a
href="/contest/1452/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_c96f131b7cea1ec585c6487708eec0c5d631b961">
<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>Только что завершился Берляндский региональный отбор к ICPC. Было $$$m$$$ участников, пронумерованных от $$$1$$$ до $$$m$$$, которые решали $$$n$$$ задач, пронумерованных от $$$1$$$ до $$$n$$$.</p><p>Сейчас будет проходить разбор. Два автора задач готовы разобрать по <span class="tex-font-style-bf">$$$k$$$ последовательных задач</span> каждый. Авторы выбирают отрезки из $$$k$$$ последовательных задач независимо друг от друга. Отрезки могут совпадать, пересекаться или не пересекаться вообще.</p><p>$$$i$$$-й участник хочет послушать разбор всех последовательных задач с $$$l_i$$$ по $$$r_i$$$. Каждый участник всегда выбирает слушать разбор только того автора, который расскажет большее количество интересных ему задач. Пусть это количество будет равно $$$a_i$$$. Никто не может слушать разбор обоих авторов, даже если их отрезки не пересекаются.</p><p>Авторы задач хотят выбрать отрезки из $$$k$$$ последовательных задач для себя так, чтобы сумма $$$a_i$$$ по всем участникам была как можно больше.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n, m$$$ и $$$k$$$ ($$$1 \le n, m \le 2000$$$, $$$1 \le k \le n$$$) — количество задач, количество участников и длина отрезка задач, разбор на которые планирует рассказать каждый из авторов.</p><p>В $$$i$$$-й из следующих $$$m$$$ строк записаны по два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — отрезок задач, разбор на которые хочет послушать $$$i$$$-й участник.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — наибольшую возможную сумму $$$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>
10 5 3
1 3
2 4
6 9
6 9
1 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
14
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 3 3
2 4
4 6
3 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 4 1
3 3
1 1
2 2
4 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 4 5
1 2
2 3
3 4
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере первый автор может рассказать разбор по задачам с $$$1$$$ по $$$3$$$, а второй — с $$$6$$$ по $$$8$$$. Тогда последовательность $$$a_i$$$ будет $$$[3, 2, 3, 3, 3]$$$. Обратите внимание, что последний участник не может послушать обоих авторов, он выбирает только того, кто расскажет ему больше интересующих его задач.</p><p>Во втором примере первый может рассказать задачи с $$$2$$$ по $$$4$$$, а второй — с $$$4$$$ по $$$6$$$.</p><p>В третьем примере первый может рассказать задачи с $$$1$$$ по $$$1$$$, а второй — с $$$2$$$ по $$$2$$$. Или с $$$4$$$ по $$$4$$$ и с $$$3$$$ по $$$3$$$. Любая пара различных задач даст одинаковую сумму $$$2$$$.</p><p>В четвертом примере первый может рассказать задачи с $$$1$$$ по $$$5$$$ и второй тоже с $$$1$$$ по $$$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:16: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:'8124b451ae589d75',t:'MTY5NjY2NjYxMS41OTgwMDA='};_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", "\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\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2500"] | ||
1452F | 1452 | 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>Вам задано мультимножество степеней двоек. Точнее, для каждого $$$i$$$ от $$$0$$$ до $$$n$$$ невключительно у вас есть $$$cnt_i$$$ элементов равных $$$2^i$$$.</p><p>За одну операцию, вы можете выбрать один любой элемент $$$2^l > 1$$$ и разделить его на два элемента $$$2^{l - 1}$$$.</p><p>Вам нужно обработать $$$q$$$ запросов. Каждый запрос имеет один из двух типов: </p><ul> <li> «$$$1$$$ $$$pos$$$ $$$val$$$» — присвоить $$$cnt_{pos} := val$$$; </li><li> «$$$2$$$ $$$x$$$ $$$k$$$» — посчитать минимальное количество операций необходимых для того, чтобы сделать не менее $$$k$$$ элементов со значениями не более $$$2^x$$$. </li></ul><p>Заметим, что запросы второго типа не влияют на мультимножество; таким образом, вы только считаете количество операций, но не применяете их.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 30$$$; $$$1 \le q \le 2 \cdot 10^5$$$) — размер массива $$$cnt$$$ и количество операций.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$cnt_0, cnt_1, \dots, cnt_{n - 1}$$$ ($$$0 \le cnt_i \le 10^6$$$).</p><p>В следующих $$$q$$$ строках заданы запросы: по одному в строке. Каждый запрос имеет один из двух типов: </p><ul> <li> «$$$1$$$ $$$pos$$$ $$$val$$$» ($$$0 \le pos < n$$$; $$$0 \le val \le 10^6$$$); </li><li> «$$$2$$$ $$$x$$$ $$$k$$$» ($$$0 \le x < n$$$; $$$1 \le k \le 10^{15}$$$). </li></ul><p>Гарантируется, что есть хотя бы один запрос второго типа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса второго типа, выведите минимальное количество операций, необходимых для того, чтобы получить хотя бы $$$k$$$ элементов со значением не более $$$2^x$$$, либо $$$-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 11
0 1 0 0 1 0
2 1 5
2 4 18
1 1 0
2 2 5
2 0 17
1 0 3
2 1 2
1 1 4
1 4 0
1 5 1
2 2 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
16
4
-1
0
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="b98310df5b85141be6a494354ff898e2"/>
<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="664af618891471d339d5e2b70e31be7a305d90e1"/>
<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='b98310df5b85141be6a494354ff898e2'> </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%2F1452%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='b98310df5b85141be6a494354ff898e2'/>
<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/1452">Educational Codeforces Round 98 (рейтинговый для Див. 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='b98310df5b85141be6a494354ff898e2'/>
<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/1452/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="Сложность">
*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='b98310df5b85141be6a494354ff898e2'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="802109"/>
<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='b98310df5b85141be6a494354ff898e2'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="802109"/>
<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/84758" title="Educational Codeforces Round 98 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12386:12387" 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/84847" title="84847" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12398:12399" 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/1452">Задачи</a></li>
<li><a
href="/contest/1452/submit">Отослать</a></li>
<li><a
href="/contest/1452/my">Мои посылки</a></li>
<li><a
href="/contest/1452/status">Статус</a></li>
<li><a
href="/contest/1452/hacks">Взломы</a></li>
<li><a
href="/contest/1452/standings">Положение</a></li>
<li><a
href="/contest/1452/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_70f7d006fd66a8e55c9a03bc325584108e752faa">
<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>Вам задано мультимножество степеней двоек. Точнее, для каждого $$$i$$$ от $$$0$$$ до $$$n$$$ невключительно у вас есть $$$cnt_i$$$ элементов равных $$$2^i$$$.</p><p>За одну операцию, вы можете выбрать один любой элемент $$$2^l > 1$$$ и разделить его на два элемента $$$2^{l - 1}$$$.</p><p>Вам нужно обработать $$$q$$$ запросов. Каждый запрос имеет один из двух типов: </p><ul> <li> «$$$1$$$ $$$pos$$$ $$$val$$$» — присвоить $$$cnt_{pos} := val$$$; </li><li> «$$$2$$$ $$$x$$$ $$$k$$$» — посчитать минимальное количество операций необходимых для того, чтобы сделать не менее $$$k$$$ элементов со значениями не более $$$2^x$$$. </li></ul><p>Заметим, что запросы второго типа не влияют на мультимножество; таким образом, вы только считаете количество операций, но не применяете их.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 30$$$; $$$1 \le q \le 2 \cdot 10^5$$$) — размер массива $$$cnt$$$ и количество операций.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$cnt_0, cnt_1, \dots, cnt_{n - 1}$$$ ($$$0 \le cnt_i \le 10^6$$$).</p><p>В следующих $$$q$$$ строках заданы запросы: по одному в строке. Каждый запрос имеет один из двух типов: </p><ul> <li> «$$$1$$$ $$$pos$$$ $$$val$$$» ($$$0 \le pos < n$$$; $$$0 \le val \le 10^6$$$); </li><li> «$$$2$$$ $$$x$$$ $$$k$$$» ($$$0 \le x < n$$$; $$$1 \le k \le 10^{15}$$$). </li></ul><p>Гарантируется, что есть хотя бы один запрос второго типа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса второго типа, выведите минимальное количество операций, необходимых для того, чтобы получить хотя бы $$$k$$$ элементов со значением не более $$$2^x$$$, либо $$$-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 11
0 1 0 0 1 0
2 1 5
2 4 18
1 1 0
2 2 5
2 0 17
1 0 3
2 1 2
1 1 4
1 4 0
1 5 1
2 2 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
16
4
-1
0
1
</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:16: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:'8124b45a2f2a4975',t:'MTY5NjY2NjYxMi45MjEwMDA='};_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", "\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", "*2900"] | ||
1452G | 1452 | 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>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$$$ вершин. Изначально у Боба есть $$$k$$$ фишек, $$$i$$$-я фишка расположена в вершине $$$a_i$$$ (все эти вершины уникальны). Перед началом игры Алиса поместит фишку в одну из вершин дерева.</p><p>Игра состоит из ходов. На каждом ходу происходят следующие события (последовательно, точно в следующем порядке):</p><ol> <li> Алиса либо перемещает свою фишку в соседнюю вершину, либо не перемещает ее; </li><li> для каждой фишки Боба он либо перемещает ее в соседнюю вершину, либо не перемещает. Обратите внимание, что этот выбор делается независимо для каждой фишки. </li></ol><p>Игра заканчивается, когда фишка Алисы находится в одной вершине с одной (или несколькими) фишками Боба. Обратите внимание, что фишки Боба могут находиться в одной и той же вершине, даже если они находились в разных вершинах в начале игры.</p><p>Алиса хочет максимизировать количество ходов, а Боб хочет минимизировать его. Если игра заканчивается в середине некоторого хода (Алиса перемещает свою фишку в вершину, содержащую одну или несколько фишек Боба), этот ход засчитывается.</p><p>Для каждой вершины подсчитайте, сколько ходов продлится игра, если Алиса поместит свою фишку в эту вершину.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество вершин в дереве.</p><p>Затем следует $$$n - 1$$$ строка, каждая строка содержит два целых числа $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — ребра дерева. Гарантируется, что эти ребра образуют дерево.</p><p>Следующая строка содержит одно целое число $$$k$$$ ($$$1 \le k \le n - 1$$$) — количество фишек Боба.</p><p>Последняя строка содержит $$$k$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_k$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne a_j$$$, если $$$i \ne j$$$) — вершины, в которых изначально размещены фишки Боба.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел. $$$i$$$-е из них должно быть равно числу ходов, которое продлится игра, если Алиса изначально поместит свою фишку в вершину $$$i$$$. Если одна из фишек Боба уже помещена в вершину $$$i$$$, то ответ для вершины $$$i$$$ равен $$$0$$$.</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 4
3 1
3 4
3 5
2
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1 2 0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
4 1
8 4
4 5
6 4
2 5
4 3
1 7
3
2 8 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 0 0 3 1 2 3 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
2 5
4 3
7 3
7 2
5 8
3 6
8 10
7 9
7 1
4
10 6 9 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 2 2 2 2 0 2 2 0 0
</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="82de377fe51514eaaced4849b0f9dd35"/>
<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="664af618891471d339d5e2b70e31be7a305d90e1"/>
<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='82de377fe51514eaaced4849b0f9dd35'> </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%2F1452%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='82de377fe51514eaaced4849b0f9dd35'/>
<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/1452">Educational Codeforces Round 98 (рейтинговый для Див. 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='82de377fe51514eaaced4849b0f9dd35'/>
<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/1452/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="Сложность">
*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='82de377fe51514eaaced4849b0f9dd35'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="802110"/>
<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='82de377fe51514eaaced4849b0f9dd35'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="802110"/>
<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/84758" title="Educational Codeforces Round 98 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12386:12387" 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/84847" title="84847" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12398:12399" 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/1452">Задачи</a></li>
<li><a
href="/contest/1452/submit">Отослать</a></li>
<li><a
href="/contest/1452/my">Мои посылки</a></li>
<li><a
href="/contest/1452/status">Статус</a></li>
<li><a
href="/contest/1452/hacks">Взломы</a></li>
<li><a
href="/contest/1452/standings">Положение</a></li>
<li><a
href="/contest/1452/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_acae7e7ca8a93902835ac8aaa654cb5efff414d5">
<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>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$$$ вершин. Изначально у Боба есть $$$k$$$ фишек, $$$i$$$-я фишка расположена в вершине $$$a_i$$$ (все эти вершины уникальны). Перед началом игры Алиса поместит фишку в одну из вершин дерева.</p><p>Игра состоит из ходов. На каждом ходу происходят следующие события (последовательно, точно в следующем порядке):</p><ol> <li> Алиса либо перемещает свою фишку в соседнюю вершину, либо не перемещает ее; </li><li> для каждой фишки Боба он либо перемещает ее в соседнюю вершину, либо не перемещает. Обратите внимание, что этот выбор делается независимо для каждой фишки. </li></ol><p>Игра заканчивается, когда фишка Алисы находится в одной вершине с одной (или несколькими) фишками Боба. Обратите внимание, что фишки Боба могут находиться в одной и той же вершине, даже если они находились в разных вершинах в начале игры.</p><p>Алиса хочет максимизировать количество ходов, а Боб хочет минимизировать его. Если игра заканчивается в середине некоторого хода (Алиса перемещает свою фишку в вершину, содержащую одну или несколько фишек Боба), этот ход засчитывается.</p><p>Для каждой вершины подсчитайте, сколько ходов продлится игра, если Алиса поместит свою фишку в эту вершину.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество вершин в дереве.</p><p>Затем следует $$$n - 1$$$ строка, каждая строка содержит два целых числа $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — ребра дерева. Гарантируется, что эти ребра образуют дерево.</p><p>Следующая строка содержит одно целое число $$$k$$$ ($$$1 \le k \le n - 1$$$) — количество фишек Боба.</p><p>Последняя строка содержит $$$k$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_k$$$ ($$$1 \le a_i \le n$$$; $$$a_i \ne a_j$$$, если $$$i \ne j$$$) — вершины, в которых изначально размещены фишки Боба.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел. $$$i$$$-е из них должно быть равно числу ходов, которое продлится игра, если Алиса изначально поместит свою фишку в вершину $$$i$$$. Если одна из фишек Боба уже помещена в вершину $$$i$$$, то ответ для вершины $$$i$$$ равен $$$0$$$.</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 4
3 1
3 4
3 5
2
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1 2 0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
4 1
8 4
4 5
6 4
2 5
4 3
1 7
3
2 8 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 0 0 3 1 2 3 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
2 5
4 3
7 3
7 2
5 8
3 6
8 10
7 9
7 1
4
10 6 9 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 2 2 2 2 0 2 2 0 0
</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:16: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:'8124b4626f73166c',t:'MTY5NjY2NjYxNC4yOTEwMDA='};_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", "*2700"] | ||
1453A | 1453 | 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>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>Gildong живет в городе, в котором система поездов устроена как $$$100$$$ поездов, которые путешествуют от нижнего края до верхнего края и $$$100$$$ поездов, которые путешествуют от левого края до правого края. Поезда на каждой стороне пронумерованы от $$$1$$$ до $$$100$$$ соответственно, и все поезда движутся с одинаковой скоростью. Рассмотрим следующую картинку.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f4c2ba66d97e5e8e1a993791f065fbda83ec96c5.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Система поездов может быть описана как координаты на 2D плоскости. $$$i$$$-й поезд, стартующий на нижнем краю, имеет координаты $$$(i,0)$$$ и будет находится в координатах $$$(i,T)$$$ спустя $$$T$$$ минут, а $$$i$$$-й поезд, стартующий на левом краю, имеет координаты $$$(0,i)$$$ и будет находится в координатах $$$(T,i)$$$ спустя $$$T$$$ минут. Все поезда приезжают на место назначения спустя $$$101$$$ минуту.</p><p>Gildong обнаружил, что некоторые поезда очень опасно отправлять одновременно. В данный момент $$$n$$$ поездов запланировано отправить с нижнего края, и $$$m$$$ поездов запланировано отправить с левого края. Если два поезда одновременно находятся в одной и той же точке $$$(x,y)$$$ для некоторых $$$x$$$ и $$$y$$$, они врежутся друг в друга. Он попросил вас найти <span class="tex-font-style-bf">минимальное</span> число поездов, отправку которых нужно отменить, чтобы предотвратить все столкновения.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$).</p><p>Каждый набор входных данных содержит три строки. В первой строке каждого набора входных данных записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 100$$$) — количество поездов, у которых запланирована отправка с нижнего края, и количество поездов, у которых запланирована отправка с левого края, соответственно.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел. Каждое целое число — это номер поезда, у которого запланирована отправка с <span class="tex-font-style-bf">нижнего</span> края. Числа даны в строго возрастающем порядке и находятся в промежутке от $$$1$$$ до $$$100$$$ включительно.</p><p>Третья строка каждого набора входных данных содержит $$$m$$$ целых чисел. Каждое целое число — это номер поезда, у которого запланирована отправка с <span class="tex-font-style-bf">левого</span> края. Числа даны в строго возрастающем порядке и находятся в промежутке от $$$1$$$ до $$$100$$$ включительно.</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
1 2
1
3 4
3 2
1 3 4
2 4
9 14
2 7 16 28 33 57 59 86 99
3 9 14 19 25 26 28 35 41 59 85 87 99 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно показать, что текущее расписание не повлечет никаких столкновений. Таким образом, ответ равен нулю.</p><p>Во втором наборе входных данных в момент времени $$$T=4$$$ произойдет столкновение, как можно увидеть на картинке ниже. Можно показать, что если отменить отправление одного из этих поездов, то столкновений не произойдет. Таким образом, ответ равен одному.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8ff67b51b83a9053d20064d651827fc92a02c927.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="595bc93b08dc6222772fd2b54d4ec8c2"/>
<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="04785a83927fcbd703336e7558745d62cade5968"/>
<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='595bc93b08dc6222772fd2b54d4ec8c2'> </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%2F1453%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='595bc93b08dc6222772fd2b54d4ec8c2'/>
<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/1453">Codeforces Round 688 (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='595bc93b08dc6222772fd2b54d4ec8c2'/>
<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/1453/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='595bc93b08dc6222772fd2b54d4ec8c2'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821022"/>
<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='595bc93b08dc6222772fd2b54d4ec8c2'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821022"/>
<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/85151" title="Codeforces Round #688 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12493" resourceName="Codeforces Round #688 (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/85288" title="Codeforces Round #688 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12536" resourceName="Codeforces Round #688 (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/1453">Задачи</a></li>
<li><a
href="/contest/1453/submit">Отослать</a></li>
<li><a
href="/contest/1453/my">Мои посылки</a></li>
<li><a
href="/contest/1453/status">Статус</a></li>
<li><a
href="/contest/1453/hacks">Взломы</a></li>
<li><a
href="/contest/1453/room/1">Комната</a></li>
<li><a
href="/contest/1453/standings">Положение</a></li>
<li><a
href="/contest/1453/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_9b6fdc6738dbfe6b00499c7a1a00a4e58d617875">
<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>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>Gildong живет в городе, в котором система поездов устроена как $$$100$$$ поездов, которые путешествуют от нижнего края до верхнего края и $$$100$$$ поездов, которые путешествуют от левого края до правого края. Поезда на каждой стороне пронумерованы от $$$1$$$ до $$$100$$$ соответственно, и все поезда движутся с одинаковой скоростью. Рассмотрим следующую картинку.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f4c2ba66d97e5e8e1a993791f065fbda83ec96c5.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Система поездов может быть описана как координаты на 2D плоскости. $$$i$$$-й поезд, стартующий на нижнем краю, имеет координаты $$$(i,0)$$$ и будет находится в координатах $$$(i,T)$$$ спустя $$$T$$$ минут, а $$$i$$$-й поезд, стартующий на левом краю, имеет координаты $$$(0,i)$$$ и будет находится в координатах $$$(T,i)$$$ спустя $$$T$$$ минут. Все поезда приезжают на место назначения спустя $$$101$$$ минуту.</p><p>Gildong обнаружил, что некоторые поезда очень опасно отправлять одновременно. В данный момент $$$n$$$ поездов запланировано отправить с нижнего края, и $$$m$$$ поездов запланировано отправить с левого края. Если два поезда одновременно находятся в одной и той же точке $$$(x,y)$$$ для некоторых $$$x$$$ и $$$y$$$, они врежутся друг в друга. Он попросил вас найти <span class="tex-font-style-bf">минимальное</span> число поездов, отправку которых нужно отменить, чтобы предотвратить все столкновения.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$).</p><p>Каждый набор входных данных содержит три строки. В первой строке каждого набора входных данных записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 100$$$) — количество поездов, у которых запланирована отправка с нижнего края, и количество поездов, у которых запланирована отправка с левого края, соответственно.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел. Каждое целое число — это номер поезда, у которого запланирована отправка с <span class="tex-font-style-bf">нижнего</span> края. Числа даны в строго возрастающем порядке и находятся в промежутке от $$$1$$$ до $$$100$$$ включительно.</p><p>Третья строка каждого набора входных данных содержит $$$m$$$ целых чисел. Каждое целое число — это номер поезда, у которого запланирована отправка с <span class="tex-font-style-bf">левого</span> края. Числа даны в строго возрастающем порядке и находятся в промежутке от $$$1$$$ до $$$100$$$ включительно.</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
1 2
1
3 4
3 2
1 3 4
2 4
9 14
2 7 16 28 33 57 59 86 99
3 9 14 19 25 26 28 35 41 59 85 87 99 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно показать, что текущее расписание не повлечет никаких столкновений. Таким образом, ответ равен нулю.</p><p>Во втором наборе входных данных в момент времени $$$T=4$$$ произойдет столкновение, как можно увидеть на картинке ниже. Можно показать, что если отменить отправление одного из этих поездов, то столкновений не произойдет. Таким образом, ответ равен одному.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8ff67b51b83a9053d20064d651827fc92a02c927.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:16: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:'8124b46b291216f0',t:'MTY5NjY2NjYxNS43NTYwMDA='};_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"] | ||
1453B | 1453 | 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>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>У Gildong есть интересная машина, которая оперирует над массивом $$$a$$$ из $$$n$$$ целых чисел. Машина умеет выполнять операции двух типов:</p><ol> <li> Увеличить все элементы на суффиксе массива на $$$1$$$. </li><li> Уменьшить все элементы на суффиксе массива на $$$1$$$. </li></ol><p>Суффикс это подотрезок (последовательных элементов) массива, содержащий $$$a_n$$$. Иначе говоря, для всех $$$i$$$, что $$$a_i$$$ включен в отрезок, все $$$a_j$$$, что $$$i \lt j \le n$$$ тоже должны быть включены в отрезок.</p><p>Gildong хочет сделать все элементы в $$$a$$$ равными — он всегда будет это делать минимальным возможным числом операций. Чтобы облегчить ему жизнь, перед тем, как Gildong начнет использовать машину, у вас есть возможность заменить любой один элемент массива на любое целое число. Вам разрешается оставить массив нетронутым. Вы хотите минимизировать число операций, которое совершит Gildong. С вашей помощью, какое минимальное число операций совершит Gildong?</p><p>Обратите внимание, что даже если вы измените одно число в массиве, вы <span class="tex-font-style-bf">не</span> должны считать это как одну из операций, потому что Gildong ее не совершал.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из одного или нескольких наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 1000$$$).</p><p>Каждый набор входных данных состоит из двух строк. В первой строке каждого набора входных записано одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество элементов в массиве $$$a$$$.</p><p>Во второй строке каждого набора входных данных записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$-5 \cdot 10^8 \le a_i \le 5 \cdot 10^8$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборах входных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество операций, которое должен совершить Gildong, чтобы сделать все элементы массива равными.</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
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
3
4
6
5
2847372102
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных все элементы массива уже одинаковы. Таким образом, вам не требуется совершать никаких операций, и Gildong совершит ноль операций.</p><p>Во втором наборе входных данных мы можем сделать $$$a_3$$$ равным $$$0$$$, и массив превратится в $$$[-1,0,0]$$$. После этого Gildong может совершить $$$2$$$-ю операцию один раз на суффиксе, начинающимся с $$$a_2$$$, что уменьшит $$$a_2$$$ и $$$a_3$$$ на $$$1$$$, превратив все элементы массива в $$$-1$$$.</p><p>В третьем наборе входных данных можно сделать $$$a_1$$$ равным $$$96$$$, так что массив превратится в $$$[96,96,97,95]$$$. После этого Gildong должен: </p><ul> <li> Использовать $$$2$$$-ю операцию на суффиксе, который начинается с $$$a_3$$$, один раз, превратив массив в $$$[96,96,96,94]$$$. </li><li> Использовать $$$1$$$-ю операцию на суффиксе, который начинается с $$$a_4$$$, $$$2$$$ раза, превратив массив в $$$[96,96,96,96]$$$. </li></ul><p>В четвертом примере можно заменить массив на $$$[-3,-3,-2,1]$$$. Затем Gildong должен: </p><ul> <li> Использовать $$$2$$$-ю операцию на суффиксе, который начинается с $$$a_4$$$, $$$3$$$ раза, превратив массив в $$$[-3,-3,-2,-2]$$$. </li><li> Испоьзовать $$$2$$$-ю операцию на суффиксе, который начинается с $$$a_3$$$, один раз, превратив массив в $$$[-3,-3,-3,-3]$$$. </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="624807e83263dc7d6bf180bff4d841fe"/>
<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="04785a83927fcbd703336e7558745d62cade5968"/>
<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='624807e83263dc7d6bf180bff4d841fe'> </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%2F1453%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='624807e83263dc7d6bf180bff4d841fe'/>
<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/1453">Codeforces Round 688 (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='624807e83263dc7d6bf180bff4d841fe'/>
<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/1453/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="Сложность">
*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='624807e83263dc7d6bf180bff4d841fe'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821023"/>
<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='624807e83263dc7d6bf180bff4d841fe'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821023"/>
<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/85151" title="Codeforces Round #688 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12493" resourceName="Codeforces Round #688 (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/85288" title="Codeforces Round #688 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12536" resourceName="Codeforces Round #688 (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/1453">Задачи</a></li>
<li><a
href="/contest/1453/submit">Отослать</a></li>
<li><a
href="/contest/1453/my">Мои посылки</a></li>
<li><a
href="/contest/1453/status">Статус</a></li>
<li><a
href="/contest/1453/hacks">Взломы</a></li>
<li><a
href="/contest/1453/room/1">Комната</a></li>
<li><a
href="/contest/1453/standings">Положение</a></li>
<li><a
href="/contest/1453/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_17fdedc6a32c527b88abe44e645e205238bc7405">
<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>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>У Gildong есть интересная машина, которая оперирует над массивом $$$a$$$ из $$$n$$$ целых чисел. Машина умеет выполнять операции двух типов:</p><ol> <li> Увеличить все элементы на суффиксе массива на $$$1$$$. </li><li> Уменьшить все элементы на суффиксе массива на $$$1$$$. </li></ol><p>Суффикс это подотрезок (последовательных элементов) массива, содержащий $$$a_n$$$. Иначе говоря, для всех $$$i$$$, что $$$a_i$$$ включен в отрезок, все $$$a_j$$$, что $$$i \lt j \le n$$$ тоже должны быть включены в отрезок.</p><p>Gildong хочет сделать все элементы в $$$a$$$ равными — он всегда будет это делать минимальным возможным числом операций. Чтобы облегчить ему жизнь, перед тем, как Gildong начнет использовать машину, у вас есть возможность заменить любой один элемент массива на любое целое число. Вам разрешается оставить массив нетронутым. Вы хотите минимизировать число операций, которое совершит Gildong. С вашей помощью, какое минимальное число операций совершит Gildong?</p><p>Обратите внимание, что даже если вы измените одно число в массиве, вы <span class="tex-font-style-bf">не</span> должны считать это как одну из операций, потому что Gildong ее не совершал.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из одного или нескольких наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 1000$$$).</p><p>Каждый набор входных данных состоит из двух строк. В первой строке каждого набора входных записано одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество элементов в массиве $$$a$$$.</p><p>Во второй строке каждого набора входных данных записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$-5 \cdot 10^8 \le a_i \le 5 \cdot 10^8$$$).</p><p>Гарантируется, что сумма $$$n$$$ по всем наборах входных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество операций, которое должен совершить Gildong, чтобы сделать все элементы массива равными.</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
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
3
4
6
5
2847372102
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных все элементы массива уже одинаковы. Таким образом, вам не требуется совершать никаких операций, и Gildong совершит ноль операций.</p><p>Во втором наборе входных данных мы можем сделать $$$a_3$$$ равным $$$0$$$, и массив превратится в $$$[-1,0,0]$$$. После этого Gildong может совершить $$$2$$$-ю операцию один раз на суффиксе, начинающимся с $$$a_2$$$, что уменьшит $$$a_2$$$ и $$$a_3$$$ на $$$1$$$, превратив все элементы массива в $$$-1$$$.</p><p>В третьем наборе входных данных можно сделать $$$a_1$$$ равным $$$96$$$, так что массив превратится в $$$[96,96,97,95]$$$. После этого Gildong должен: </p><ul> <li> Использовать $$$2$$$-ю операцию на суффиксе, который начинается с $$$a_3$$$, один раз, превратив массив в $$$[96,96,96,94]$$$. </li><li> Использовать $$$1$$$-ю операцию на суффиксе, который начинается с $$$a_4$$$, $$$2$$$ раза, превратив массив в $$$[96,96,96,96]$$$. </li></ul><p>В четвертом примере можно заменить массив на $$$[-3,-3,-2,1]$$$. Затем Gildong должен: </p><ul> <li> Использовать $$$2$$$-ю операцию на суффиксе, который начинается с $$$a_4$$$, $$$3$$$ раза, превратив массив в $$$[-3,-3,-2,-2]$$$. </li><li> Испоьзовать $$$2$$$-ю операцию на суффиксе, который начинается с $$$a_3$$$, один раз, превратив массив в $$$[-3,-3,-3,-3]$$$. </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:16: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:'8124b4742d1c0c48',t:'MTY5NjY2NjYxNy4xMjIwMDA='};_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", "*1400"] | ||
1453C | 1453 | 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>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>У Gildong есть квадратная доска из $$$n$$$ строк и $$$n$$$ столбцов квадратных клеток, каждая клетка содержит одну цифру (от $$$0$$$ до $$$9$$$). Клетка на пересечении $$$j$$$-го столбца и $$$i$$$-й строки может быть описана как $$$(i, j)$$$, длины сторон каждой клетки равны $$$1$$$. Gildong любит большие вещи, так что для каждой цифры $$$d$$$ он хочет найти треугольник такой, что:</p><ul> <li> Каждая вершина треугольника находится в центре клетки. </li><li> Цифра на каждой вершине треугольнике равна $$$d$$$. </li><li> Хотя бы одна сторона треугольника параллельна одной из сторон доски. Вы можете считать, что сторона длины $$$0$$$ параллельна обоим сторонам доски. </li><li> Площадь треугольника максимальна. </li></ul><p>Конечно, его не успокоят только эти треугольники. Для каждой цифры $$$d$$$ он хочет изменить цифру у ровно одной клетки доски на $$$d$$$, и затем найти искомый треугольник. Он меняет цифру этой клетки обратно после того, как он нашел треугольник. Найдите максимальную площадь треугольника, которую он может получить, для каждой цифры.</p><p>Обратите внимание, что он может ставить несколько вершин треугольника на одну и ту же клетку, и что треугольник может быть <a href="https://vk.cc/bVwzCX">вырожденным</a>; иначе говоря, площадь треугольника может быть равна $$$0$$$. Также обратите внимание, что разрешается менять цифру $$$d$$$ на $$$d$$$.</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 2000$$$) — количество строк и столбцов в таблице.</p><p>Следующие $$$n$$$ строк каждого набора входных данных содержат строку из $$$n$$$ цифр без пробелов. В $$$j$$$-й цифре $$$i$$$-й строки записана цифра клетки $$$(i, j)$$$. Каждая цифра представлена символом от $$$0$$$ до $$$9$$$.</p><p>Гарантируется, что сумма $$$n^2$$$ по всем наборам входных данных не превосходит $$$4 \cdot 10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите строку из $$$10$$$ целых чисел. $$$i$$$-е из них должно быть равно максимальной площади, которую может получить Gildong, для $$$d = i-1$$$, <span class="tex-font-style-bf">умноженной на $$$2$$$</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
000
122
001
2
57
75
4
0123
4012
3401
2340
1
9
8
42987101
98289412
38949562
87599023
92834718
83917348
19823743
38947912
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4 4 1 0 0 0 0 0 0 0
0 0 0 0 0 1 0 1 0 0
9 6 9 9 6 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
18 49 49 49 49 15 0 30 42 42
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных для $$$d=0$$$ вне зависимости от выбранной клетки треугольник с вершинами $$$(1, 1)$$$, $$$(1, 3)$$$ и $$$(3, 1)$$$ — это самый большой треугольник площади $$$\cfrac{2 \cdot 2}{2} = 2$$$. Так как мы должны вывести ответ, умноженный на $$$2$$$, ответ для $$$d=0$$$ это $$$4$$$.</p><p>Для $$$d=1$$$ Gildong может поменять цифру у клетки $$$(1, 3)$$$ на $$$1$$$, получив треугольник с вершинами в клетках с цифрой $$$1$$$ с площадью $$$2$$$.</p><p>Для $$$d=2$$$ Gildong может поменять цифру ровно одной из следующих клеток на $$$2$$$, чтобы получить треугольник с площадью $$$\cfrac{1}{2}$$$: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(3, 1)$$$, $$$(3, 2)$$$ и $$$(3, 3)$$$.</p><p>Для остальных цифр (от $$$3$$$ до $$$9$$$) клетка, которую поменяет Gildong, будет единственной клеткой, содержащей эту цифру. Таким образом, треугольник всегда будет вырожденным и площади $$$0$$$.</p><p>В третьем наборе входных данных для $$$d=4$$$ обратите внимание, что треугольник будет больше чем ответ, если Gildong поменяет цифру у клетки $$$(1, 4)$$$, а затем выберет дополнительно клетки $$$(2, 1)$$$ и $$$(4, 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="5760d5d73c709585edab11e1afa4b272"/>
<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="04785a83927fcbd703336e7558745d62cade5968"/>
<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='5760d5d73c709585edab11e1afa4b272'> </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%2F1453%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='5760d5d73c709585edab11e1afa4b272'/>
<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/1453">Codeforces Round 688 (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='5760d5d73c709585edab11e1afa4b272'/>
<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/1453/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='5760d5d73c709585edab11e1afa4b272'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821024"/>
<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='5760d5d73c709585edab11e1afa4b272'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821024"/>
<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/85151" title="Codeforces Round #688 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12493" resourceName="Codeforces Round #688 (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/85288" title="Codeforces Round #688 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12536" resourceName="Codeforces Round #688 (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/1453">Задачи</a></li>
<li><a
href="/contest/1453/submit">Отослать</a></li>
<li><a
href="/contest/1453/my">Мои посылки</a></li>
<li><a
href="/contest/1453/status">Статус</a></li>
<li><a
href="/contest/1453/hacks">Взломы</a></li>
<li><a
href="/contest/1453/room/1">Комната</a></li>
<li><a
href="/contest/1453/standings">Положение</a></li>
<li><a
href="/contest/1453/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_ece60ca9e923d6a73f18a658b3ec306a498004de">
<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>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>У Gildong есть квадратная доска из $$$n$$$ строк и $$$n$$$ столбцов квадратных клеток, каждая клетка содержит одну цифру (от $$$0$$$ до $$$9$$$). Клетка на пересечении $$$j$$$-го столбца и $$$i$$$-й строки может быть описана как $$$(i, j)$$$, длины сторон каждой клетки равны $$$1$$$. Gildong любит большие вещи, так что для каждой цифры $$$d$$$ он хочет найти треугольник такой, что:</p><ul> <li> Каждая вершина треугольника находится в центре клетки. </li><li> Цифра на каждой вершине треугольнике равна $$$d$$$. </li><li> Хотя бы одна сторона треугольника параллельна одной из сторон доски. Вы можете считать, что сторона длины $$$0$$$ параллельна обоим сторонам доски. </li><li> Площадь треугольника максимальна. </li></ul><p>Конечно, его не успокоят только эти треугольники. Для каждой цифры $$$d$$$ он хочет изменить цифру у ровно одной клетки доски на $$$d$$$, и затем найти искомый треугольник. Он меняет цифру этой клетки обратно после того, как он нашел треугольник. Найдите максимальную площадь треугольника, которую он может получить, для каждой цифры.</p><p>Обратите внимание, что он может ставить несколько вершин треугольника на одну и ту же клетку, и что треугольник может быть <a href="https://vk.cc/bVwzCX">вырожденным</a>; иначе говоря, площадь треугольника может быть равна $$$0$$$. Также обратите внимание, что разрешается менять цифру $$$d$$$ на $$$d$$$.</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 2000$$$) — количество строк и столбцов в таблице.</p><p>Следующие $$$n$$$ строк каждого набора входных данных содержат строку из $$$n$$$ цифр без пробелов. В $$$j$$$-й цифре $$$i$$$-й строки записана цифра клетки $$$(i, j)$$$. Каждая цифра представлена символом от $$$0$$$ до $$$9$$$.</p><p>Гарантируется, что сумма $$$n^2$$$ по всем наборам входных данных не превосходит $$$4 \cdot 10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите строку из $$$10$$$ целых чисел. $$$i$$$-е из них должно быть равно максимальной площади, которую может получить Gildong, для $$$d = i-1$$$, <span class="tex-font-style-bf">умноженной на $$$2$$$</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
000
122
001
2
57
75
4
0123
4012
3401
2340
1
9
8
42987101
98289412
38949562
87599023
92834718
83917348
19823743
38947912
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4 4 1 0 0 0 0 0 0 0
0 0 0 0 0 1 0 1 0 0
9 6 9 9 6 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
18 49 49 49 49 15 0 30 42 42
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных для $$$d=0$$$ вне зависимости от выбранной клетки треугольник с вершинами $$$(1, 1)$$$, $$$(1, 3)$$$ и $$$(3, 1)$$$ — это самый большой треугольник площади $$$\cfrac{2 \cdot 2}{2} = 2$$$. Так как мы должны вывести ответ, умноженный на $$$2$$$, ответ для $$$d=0$$$ это $$$4$$$.</p><p>Для $$$d=1$$$ Gildong может поменять цифру у клетки $$$(1, 3)$$$ на $$$1$$$, получив треугольник с вершинами в клетках с цифрой $$$1$$$ с площадью $$$2$$$.</p><p>Для $$$d=2$$$ Gildong может поменять цифру ровно одной из следующих клеток на $$$2$$$, чтобы получить треугольник с площадью $$$\cfrac{1}{2}$$$: $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(3, 1)$$$, $$$(3, 2)$$$ и $$$(3, 3)$$$.</p><p>Для остальных цифр (от $$$3$$$ до $$$9$$$) клетка, которую поменяет Gildong, будет единственной клеткой, содержащей эту цифру. Таким образом, треугольник всегда будет вырожденным и площади $$$0$$$.</p><p>В третьем наборе входных данных для $$$d=4$$$ обратите внимание, что треугольник будет больше чем ответ, если Gildong поменяет цифру у клетки $$$(1, 4)$$$, а затем выберет дополнительно клетки $$$(2, 1)$$$ и $$$(4, 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:16: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:'8124b47cac18064b',t:'MTY5NjY2NjYxOC40NTAwMDA='};_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", "*1700"] | ||
1453D | 1453 | 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>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>Gildong разрабатывает игру, состоящую из $$$n$$$ уровней, пронумерованных от $$$1$$$ до $$$n$$$. Игрок начинает игру на $$$1$$$-м уровне и должен проходить их в порядке возрастания номера. Игрок выигрывает, когда он проходит $$$n$$$-й уровень.</p><p>На каждом уровне есть не более одной контрольной точки, но она всегда есть на $$$1$$$-м уровне. В начале игры, только контрольная точка на $$$1$$$-м уровне активирована, а все остальные деактивированы. Когда игрок доходит до $$$i$$$-го уровня, на котором есть контрольная точка, эта контрольная точка активируется.</p><p>Для каждой попытки прохождения уровня, игрок может либо пройти уровень, либо проиграть. Если он проходит $$$i$$$-й уровень, игрок следует на $$$i+1$$$-й уровень. Если он проигрывает на $$$i$$$-м уровне, игрок отправляется на самую последнюю активированную контрольную точку, и ему требуется снова проходить уровни начиная с этой контрольной точки.</p><p>Например, если $$$n = 4$$$ и контрольные точки расположены на $$$1$$$-м и $$$3$$$-м уровнях. Игрок начинает на $$$1$$$-м уровне. Если он проигрывает на $$$1$$$-м уровне, ему требуется снова проходить $$$1$$$-й уровень, потому что контрольная точка на $$$1$$$-м уровне это последняя активированная контрольная точка. Если игрок проходит $$$1$$$-й уровень, он двигается на $$$2$$$-й уровень. Если он проигрывает на нем, он отправляется обратно на $$$1$$$-й уровень. Если он проходит $$$1$$$-й уровень и $$$2$$$-й уровень, он отправляется на $$$3$$$-й уровень и активирует контрольную точку на $$$3$$$-м уровне. Теперь если он проиграет на $$$3$$$-м уровне, или на $$$4$$$-м уровне после прохождения $$$3$$$-го, он отправится обратно на $$$3$$$-й уровень. Если он пройдет и $$$3$$$-й уровень, и $$$4$$$-й, он выиграет игру.</p><p>Gildong хочет, чтобы сложности уровней были одинаковы. Он просит вас найти любую систему уровней и контрольных точек используя не больше чем $$$2000$$$ уровней, чтобы <a href="https://vk.cc/6p6Ots">математическое ожидание</a> количества попыток на всех уровней (до прохождения игры) было равно $$$k$$$, для игрока, который проходит каждой уровень с вероятностью $$$\cfrac{1}{2}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из одного или нескольких наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 50$$$).</p><p>Каждый набор входных данных состоит из ровно одной строки. В строке записано одно целое число $$$k$$$ ($$$1 \le k \le 10^{18}$$$) — математическое ожидание суммарного числа попыток по всем уровням, которое Gildong хочет получить для игрока, который проходит каждый уровень с вероятностью $$$\cfrac{1}{2}$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите $$$-1$$$, если невозможно построить такую систему уровней и контрольных точек с не более чем $$$2000$$$ уровней.</p><p>Иначе, выведите две строки. В первой строке должно быть записано одно целое число $$$n$$$ ($$$1 \le n \le 2000$$$) — количество уровней. Во второй строке должны быть записаны $$$n$$$ целых чисел, $$$i$$$-е из них описывает, установлена ли контрольная точка в $$$i$$$-м уровне. $$$i$$$-е число должно быть $$$0$$$, если $$$i$$$-й уровень не содержит контрольную точку, и $$$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
1
2
8
12
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и втором наборе входных данных, можно видеть, что самая <span class="tex-font-style-it">простая</span> конструкция имеет только $$$1$$$ уровень с контрольной точкой. Это требует $$$2$$$ попытки прохождения, поэтому невозможно построить конструкцию с $$$1$$$ попыткой.</p><p>В третьем наборе входных данных, это занимает $$$2$$$ попытки в среднем чтобы пройти каждый уровень, и игрок всегда может повторить уровень без откатывания не прошлые уровни. Таким образом, математическое ожидание равно $$$8$$$. Обратите внимание, что есть решения с меньшим количеством уровней, но вам не требуется минимизировать их количество. </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="6ba679850570465c963ef7488b5732d2"/>
<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="04785a83927fcbd703336e7558745d62cade5968"/>
<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='6ba679850570465c963ef7488b5732d2'> </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%2F1453%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='6ba679850570465c963ef7488b5732d2'/>
<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/1453">Codeforces Round 688 (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='6ba679850570465c963ef7488b5732d2'/>
<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/1453/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='6ba679850570465c963ef7488b5732d2'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821025"/>
<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='6ba679850570465c963ef7488b5732d2'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821025"/>
<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/85151" title="Codeforces Round #688 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12493" resourceName="Codeforces Round #688 (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/85288" title="Codeforces Round #688 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12536" resourceName="Codeforces Round #688 (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/1453">Задачи</a></li>
<li><a
href="/contest/1453/submit">Отослать</a></li>
<li><a
href="/contest/1453/my">Мои посылки</a></li>
<li><a
href="/contest/1453/status">Статус</a></li>
<li><a
href="/contest/1453/hacks">Взломы</a></li>
<li><a
href="/contest/1453/room/1">Комната</a></li>
<li><a
href="/contest/1453/standings">Положение</a></li>
<li><a
href="/contest/1453/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_08126ac4535643daf29fadc4a6b996ea0d6603d8">
<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>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>Gildong разрабатывает игру, состоящую из $$$n$$$ уровней, пронумерованных от $$$1$$$ до $$$n$$$. Игрок начинает игру на $$$1$$$-м уровне и должен проходить их в порядке возрастания номера. Игрок выигрывает, когда он проходит $$$n$$$-й уровень.</p><p>На каждом уровне есть не более одной контрольной точки, но она всегда есть на $$$1$$$-м уровне. В начале игры, только контрольная точка на $$$1$$$-м уровне активирована, а все остальные деактивированы. Когда игрок доходит до $$$i$$$-го уровня, на котором есть контрольная точка, эта контрольная точка активируется.</p><p>Для каждой попытки прохождения уровня, игрок может либо пройти уровень, либо проиграть. Если он проходит $$$i$$$-й уровень, игрок следует на $$$i+1$$$-й уровень. Если он проигрывает на $$$i$$$-м уровне, игрок отправляется на самую последнюю активированную контрольную точку, и ему требуется снова проходить уровни начиная с этой контрольной точки.</p><p>Например, если $$$n = 4$$$ и контрольные точки расположены на $$$1$$$-м и $$$3$$$-м уровнях. Игрок начинает на $$$1$$$-м уровне. Если он проигрывает на $$$1$$$-м уровне, ему требуется снова проходить $$$1$$$-й уровень, потому что контрольная точка на $$$1$$$-м уровне это последняя активированная контрольная точка. Если игрок проходит $$$1$$$-й уровень, он двигается на $$$2$$$-й уровень. Если он проигрывает на нем, он отправляется обратно на $$$1$$$-й уровень. Если он проходит $$$1$$$-й уровень и $$$2$$$-й уровень, он отправляется на $$$3$$$-й уровень и активирует контрольную точку на $$$3$$$-м уровне. Теперь если он проиграет на $$$3$$$-м уровне, или на $$$4$$$-м уровне после прохождения $$$3$$$-го, он отправится обратно на $$$3$$$-й уровень. Если он пройдет и $$$3$$$-й уровень, и $$$4$$$-й, он выиграет игру.</p><p>Gildong хочет, чтобы сложности уровней были одинаковы. Он просит вас найти любую систему уровней и контрольных точек используя не больше чем $$$2000$$$ уровней, чтобы <a href="https://vk.cc/6p6Ots">математическое ожидание</a> количества попыток на всех уровней (до прохождения игры) было равно $$$k$$$, для игрока, который проходит каждой уровень с вероятностью $$$\cfrac{1}{2}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест состоит из одного или нескольких наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 50$$$).</p><p>Каждый набор входных данных состоит из ровно одной строки. В строке записано одно целое число $$$k$$$ ($$$1 \le k \le 10^{18}$$$) — математическое ожидание суммарного числа попыток по всем уровням, которое Gildong хочет получить для игрока, который проходит каждый уровень с вероятностью $$$\cfrac{1}{2}$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите $$$-1$$$, если невозможно построить такую систему уровней и контрольных точек с не более чем $$$2000$$$ уровней.</p><p>Иначе, выведите две строки. В первой строке должно быть записано одно целое число $$$n$$$ ($$$1 \le n \le 2000$$$) — количество уровней. Во второй строке должны быть записаны $$$n$$$ целых чисел, $$$i$$$-е из них описывает, установлена ли контрольная точка в $$$i$$$-м уровне. $$$i$$$-е число должно быть $$$0$$$, если $$$i$$$-й уровень не содержит контрольную точку, и $$$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
1
2
8
12
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
1
1
4
1 1 1 1
5
1 1 0 1 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и втором наборе входных данных, можно видеть, что самая <span class="tex-font-style-it">простая</span> конструкция имеет только $$$1$$$ уровень с контрольной точкой. Это требует $$$2$$$ попытки прохождения, поэтому невозможно построить конструкцию с $$$1$$$ попыткой.</p><p>В третьем наборе входных данных, это занимает $$$2$$$ попытки в среднем чтобы пройти каждый уровень, и игрок всегда может повторить уровень без откатывания не прошлые уровни. Таким образом, математическое ожидание равно $$$8$$$. Обратите внимание, что есть решения с меньшим количеством уровней, но вам не требуется минимизировать их количество. </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:16:59</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:'8124b4852e77167e',t:'MTY5NjY2NjYxOS44MDQwMDA='};_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.", "\u041f\u0435\u0440\u0435\u0431\u043e\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"] | ["\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*1900"] | ||
1453E | 1453 | 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 секунды</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>Gildong играет в игру со своей собакой, Badugi. Они находятся в парке, в котором есть $$$n$$$ перекрестков и $$$n-1$$$ двусторонних дорог, длиной в $$$1$$$ и соединяющих два перекрестка. Пересечения пронумерованы от $$$1$$$ до $$$n$$$, и для каждой пары $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le n$$$), возможно пройти от $$$b$$$-го перекрестка до $$$a$$$-го передвигаясь по дорогам.</p><p>Gildong поставил одну закуску на каждый перекресток. Gildong поставил Badugi задачу — съесть все закуски. Badugi начинает на $$$1$$$-м перекрестке, и он передвигается по следующим правилам:</p><ul> <li> Badugi ищет закуски, которые находятся к нему как можно ближе. Расстояние это длина кратчайшего пути от текущей позиции Badugi до перекрестка с закуской. Однако, обоняние Badugi ограничено до $$$k$$$ метров, так что он может находить только закуски на расстоянии не больше чем $$$k$$$ метров от текущей позиции. Если он не может найти ни одной закуски, задание считается проваленным. </li><li> Среди всех закусок, которые Badugi чувствует на его текущей позиции, он выбирает закуску с минимальным расстоянием до текущей позиции. Если есть несколько возможных закусок, он выбирает одну любую из них. </li><li> Он повторяет этот процесс пока он не съест все $$$n$$$ закусок. После этого, он должен снова найти $$$1$$$-й перекресток, который должен быть на расстоянии не больше чем $$$k$$$ метров от последней съеденной закуски. Если он может найти его, он проходит задание. Иначе, задание считается проваленным. </li></ul><p>К сожалению, Gildong не знает значение $$$k$$$. Таким образом, он просит вас найти минимальное значение $$$k$$$, при котором Badugi сможет выполнить задание, если будет действовать оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Тест состоит из одного или нескольких наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$).</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество перекрестков в парке.</p><p>В каждой из следующих $$$n-1$$$ строк записаны два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) , которые описывают двунаправленную дорогу между перекрестками $$$u$$$ и $$$v$$$. Все дороги двухсторонние и различны.</p><p>Гарантируется, что: </p><ul> <li> Для каждого набора входных данных, для каждой пары $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le n$$$), возможно пройти от $$$b$$$-го перекрестка до $$$a$$$-го передвигаясь по дорогам. </li><li> Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное возможное значение $$$k$$$, при котором Badugi может выполнить свое задание.</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
1 2
1 3
4
1 2
2 3
3 4
8
1 2
2 3
3 4
1 5
5 6
6 7
5 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, Badugi может выполнить задание для $$$k=2$$$, передвигаясь следующим образом: </p><ol> <li> Исходно, Badugi находится на $$$1$$$-м перекрестке. Ближайшая закуска, очевидно, находится на $$$1$$$-м перекрестке, поэтому он съедает ее. </li><li> Затем, он ищет ближайшую закуску, которая может быть либо на $$$2$$$-м или на $$$3$$$-м перекрестке. Предположим, что он выбирает $$$2$$$-й перекресток. Он переходит на $$$2$$$-й перекресток, который находится на расстоянии $$$1$$$ метр, и ест закуску. </li><li> Единственная закуска находится на $$$3$$$-м перекрестке, и ему нужно пройти по $$$2$$$ дорогам, чтобы дойти до нее. </li><li> После съедения закуски на $$$3$$$-м перекрестке, ему снова нужно найти $$$1$$$-й перекресток, который находится на расстоянии $$$1$$$ метр. После того как он возвращается на него, он выполнил свое задание. </li></ol><p>Во втором наборе входных данных, единственная возможная последовательность действий это $$$1$$$ – $$$2$$$ – $$$3$$$ – $$$4$$$ – $$$1$$$. Так как расстояние между $$$4$$$-м и $$$1$$$-м перекрестком равно $$$3$$$, $$$k$$$ должно быть хотя бы $$$3$$$ для того, чтобы Badugi смог выполнить задание.</p><p>В третьем наборе входных данных, Badugi может двигаться следующим образом: $$$1$$$ – $$$5$$$ – $$$6$$$ – $$$7$$$ – $$$8$$$ – $$$2$$$ – $$$3$$$ – $$$4$$$ – $$$1$$$. Можно показать, что это единственный вариант для Badugi выполнить миссию с $$$k=3$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/01a73a4d94f92e9efdc13d6e48314600e4350493.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="74509f93629f8be36a060c67d3c09784"/>
<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="04785a83927fcbd703336e7558745d62cade5968"/>
<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='74509f93629f8be36a060c67d3c09784'> </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%2F1453%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='74509f93629f8be36a060c67d3c09784'/>
<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/1453">Codeforces Round 688 (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='74509f93629f8be36a060c67d3c09784'/>
<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/1453/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='74509f93629f8be36a060c67d3c09784'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821026"/>
<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='74509f93629f8be36a060c67d3c09784'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821026"/>
<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/85151" title="Codeforces Round #688 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12493" resourceName="Codeforces Round #688 (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/85288" title="Codeforces Round #688 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12536" resourceName="Codeforces Round #688 (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/1453">Задачи</a></li>
<li><a
href="/contest/1453/submit">Отослать</a></li>
<li><a
href="/contest/1453/my">Мои посылки</a></li>
<li><a
href="/contest/1453/status">Статус</a></li>
<li><a
href="/contest/1453/hacks">Взломы</a></li>
<li><a
href="/contest/1453/room/1">Комната</a></li>
<li><a
href="/contest/1453/standings">Положение</a></li>
<li><a
href="/contest/1453/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_e878e7bea84d8e553c8ef7c45d6ebb61455e35f6">
<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 секунды</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>Gildong играет в игру со своей собакой, Badugi. Они находятся в парке, в котором есть $$$n$$$ перекрестков и $$$n-1$$$ двусторонних дорог, длиной в $$$1$$$ и соединяющих два перекрестка. Пересечения пронумерованы от $$$1$$$ до $$$n$$$, и для каждой пары $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le n$$$), возможно пройти от $$$b$$$-го перекрестка до $$$a$$$-го передвигаясь по дорогам.</p><p>Gildong поставил одну закуску на каждый перекресток. Gildong поставил Badugi задачу — съесть все закуски. Badugi начинает на $$$1$$$-м перекрестке, и он передвигается по следующим правилам:</p><ul> <li> Badugi ищет закуски, которые находятся к нему как можно ближе. Расстояние это длина кратчайшего пути от текущей позиции Badugi до перекрестка с закуской. Однако, обоняние Badugi ограничено до $$$k$$$ метров, так что он может находить только закуски на расстоянии не больше чем $$$k$$$ метров от текущей позиции. Если он не может найти ни одной закуски, задание считается проваленным. </li><li> Среди всех закусок, которые Badugi чувствует на его текущей позиции, он выбирает закуску с минимальным расстоянием до текущей позиции. Если есть несколько возможных закусок, он выбирает одну любую из них. </li><li> Он повторяет этот процесс пока он не съест все $$$n$$$ закусок. После этого, он должен снова найти $$$1$$$-й перекресток, который должен быть на расстоянии не больше чем $$$k$$$ метров от последней съеденной закуски. Если он может найти его, он проходит задание. Иначе, задание считается проваленным. </li></ul><p>К сожалению, Gildong не знает значение $$$k$$$. Таким образом, он просит вас найти минимальное значение $$$k$$$, при котором Badugi сможет выполнить задание, если будет действовать оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Тест состоит из одного или нескольких наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10^4$$$).</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — количество перекрестков в парке.</p><p>В каждой из следующих $$$n-1$$$ строк записаны два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$, $$$u \ne v$$$) , которые описывают двунаправленную дорогу между перекрестками $$$u$$$ и $$$v$$$. Все дороги двухсторонние и различны.</p><p>Гарантируется, что: </p><ul> <li> Для каждого набора входных данных, для каждой пары $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le n$$$), возможно пройти от $$$b$$$-го перекрестка до $$$a$$$-го передвигаясь по дорогам. </li><li> Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное возможное значение $$$k$$$, при котором Badugi может выполнить свое задание.</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
1 2
1 3
4
1 2
2 3
3 4
8
1 2
2 3
3 4
1 5
5 6
6 7
5 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, Badugi может выполнить задание для $$$k=2$$$, передвигаясь следующим образом: </p><ol> <li> Исходно, Badugi находится на $$$1$$$-м перекрестке. Ближайшая закуска, очевидно, находится на $$$1$$$-м перекрестке, поэтому он съедает ее. </li><li> Затем, он ищет ближайшую закуску, которая может быть либо на $$$2$$$-м или на $$$3$$$-м перекрестке. Предположим, что он выбирает $$$2$$$-й перекресток. Он переходит на $$$2$$$-й перекресток, который находится на расстоянии $$$1$$$ метр, и ест закуску. </li><li> Единственная закуска находится на $$$3$$$-м перекрестке, и ему нужно пройти по $$$2$$$ дорогам, чтобы дойти до нее. </li><li> После съедения закуски на $$$3$$$-м перекрестке, ему снова нужно найти $$$1$$$-й перекресток, который находится на расстоянии $$$1$$$ метр. После того как он возвращается на него, он выполнил свое задание. </li></ol><p>Во втором наборе входных данных, единственная возможная последовательность действий это $$$1$$$ – $$$2$$$ – $$$3$$$ – $$$4$$$ – $$$1$$$. Так как расстояние между $$$4$$$-м и $$$1$$$-м перекрестком равно $$$3$$$, $$$k$$$ должно быть хотя бы $$$3$$$ для того, чтобы Badugi смог выполнить задание.</p><p>В третьем наборе входных данных, Badugi может двигаться следующим образом: $$$1$$$ – $$$5$$$ – $$$6$$$ – $$$7$$$ – $$$8$$$ – $$$2$$$ – $$$3$$$ – $$$4$$$ – $$$1$$$. Можно показать, что это единственный вариант для Badugi выполнить миссию с $$$k=3$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/01a73a4d94f92e9efdc13d6e48314600e4350493.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:17: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:'8124b48d68ee7b2b',t:'MTY5NjY2NjYyMS4xMjAwMDA='};_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\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", "\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\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\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", "*2300"] | ||
1453F | 1453 | 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>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>Gildong разрабатывает новую головоломку. Головоломка состоит из $$$n$$$ платформ, пронумерованных от $$$1$$$ до $$$n$$$. Игрок играет за персонажа, который может стоять на платформах и цель игры это передвинуть персонажа с $$$1$$$-й платформы на $$$n$$$-ю. На $$$i$$$-й платформе записано число $$$a_i$$$ ($$$0 \le a_i \le n-i$$$). Когда персонаж стоит на $$$i$$$-й платформе, игрок может передвинуть его на $$$j$$$-ю платформу, для $$$i+1 \le j \le i+a_i$$$. Если игрок находится на $$$i$$$-й платформе, что $$$a_i=0$$$ и $$$i \ne n$$$, игрок проигрывает.</p><p>Так как Gildong думает, что текущая игра слишком простая, он хочет сделать ее еще сложнее. Он хочет поменять несколько (возможно, ноль) чисел на платформах на $$$0$$$, чтобы остался ровно один способ выиграть. Он хочет вносить как можно меньше изменений в игру, так что он просит вас найти <span class="tex-font-style-bf">минимальное</span> количество платформ, у которых нужно изменить числа. Два способа выиграть считаются различными, если существует платформа, на которой был персонаж в одном способе, но не был в другом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 500$$$).</p><p>Каждый набор входных данных содержит две строки. В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 3000$$$) — количество платформ в игре.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \le a_i \le n-i$$$) — целое число на $$$i$$$-й платформе.</p><p>Гарантируется, что: </p><ul> <li> Для каждого набора входных данных, есть хотя бы один способ исходно выиграть. </li><li> Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$3000$$$. </li></ul></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>
3
4
1 1 1 0
5
4 3 2 1 0
9
4 1 4 2 1 0 2 1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
3
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, игрок может двигать только на следующую платформу, пока он не доберется до $$$4$$$-й платформы. Так как исходно есть ровно один способ выиграть, ответ равен нулю.</p><p>Во втором наборе входных данных, Gildong может поменять $$$a_2$$$, $$$a_3$$$, и $$$a_4$$$ на $$$0$$$, чтобы игра стала $$$4$$$ $$$0$$$ $$$0$$$ $$$0$$$ $$$0$$$. Теперь единственный способ выиграть, это прыгнуть с $$$1$$$-й платформы на $$$5$$$-ю платформу.</p><p>В третьем наборе входных данных, Gildong может поменять $$$a_2$$$ и $$$a_8$$$ на $$$0$$$, тогда единственный способ выиграть это: $$$1$$$ – $$$3$$$ – $$$7$$$ – $$$9$$$.</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="33cef8849116900dc0aeeeab1090b858"/>
<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="04785a83927fcbd703336e7558745d62cade5968"/>
<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='33cef8849116900dc0aeeeab1090b858'> </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%2F1453%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='33cef8849116900dc0aeeeab1090b858'/>
<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/1453">Codeforces Round 688 (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='33cef8849116900dc0aeeeab1090b858'/>
<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/1453/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="Сложность">
*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='33cef8849116900dc0aeeeab1090b858'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="821027"/>
<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='33cef8849116900dc0aeeeab1090b858'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="821027"/>
<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/85151" title="Codeforces Round #688 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12493" resourceName="Codeforces Round #688 (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/85288" title="Codeforces Round #688 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12536" resourceName="Codeforces Round #688 (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/1453">Задачи</a></li>
<li><a
href="/contest/1453/submit">Отослать</a></li>
<li><a
href="/contest/1453/my">Мои посылки</a></li>
<li><a
href="/contest/1453/status">Статус</a></li>
<li><a
href="/contest/1453/hacks">Взломы</a></li>
<li><a
href="/contest/1453/room/1">Комната</a></li>
<li><a
href="/contest/1453/standings">Положение</a></li>
<li><a
href="/contest/1453/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_4813eafee375578e566bd7770e8385b85fce7976">
<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>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>Gildong разрабатывает новую головоломку. Головоломка состоит из $$$n$$$ платформ, пронумерованных от $$$1$$$ до $$$n$$$. Игрок играет за персонажа, который может стоять на платформах и цель игры это передвинуть персонажа с $$$1$$$-й платформы на $$$n$$$-ю. На $$$i$$$-й платформе записано число $$$a_i$$$ ($$$0 \le a_i \le n-i$$$). Когда персонаж стоит на $$$i$$$-й платформе, игрок может передвинуть его на $$$j$$$-ю платформу, для $$$i+1 \le j \le i+a_i$$$. Если игрок находится на $$$i$$$-й платформе, что $$$a_i=0$$$ и $$$i \ne n$$$, игрок проигрывает.</p><p>Так как Gildong думает, что текущая игра слишком простая, он хочет сделать ее еще сложнее. Он хочет поменять несколько (возможно, ноль) чисел на платформах на $$$0$$$, чтобы остался ровно один способ выиграть. Он хочет вносить как можно меньше изменений в игру, так что он просит вас найти <span class="tex-font-style-bf">минимальное</span> количество платформ, у которых нужно изменить числа. Два способа выиграть считаются различными, если существует платформа, на которой был персонаж в одном способе, но не был в другом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 500$$$).</p><p>Каждый набор входных данных содержит две строки. В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 3000$$$) — количество платформ в игре.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \le a_i \le n-i$$$) — целое число на $$$i$$$-й платформе.</p><p>Гарантируется, что: </p><ul> <li> Для каждого набора входных данных, есть хотя бы один способ исходно выиграть. </li><li> Сумма $$$n$$$ по всем наборам входных данных не превосходит $$$3000$$$. </li></ul></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>
3
4
1 1 1 0
5
4 3 2 1 0
9
4 1 4 2 1 0 2 1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
3
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, игрок может двигать только на следующую платформу, пока он не доберется до $$$4$$$-й платформы. Так как исходно есть ровно один способ выиграть, ответ равен нулю.</p><p>Во втором наборе входных данных, Gildong может поменять $$$a_2$$$, $$$a_3$$$, и $$$a_4$$$ на $$$0$$$, чтобы игра стала $$$4$$$ $$$0$$$ $$$0$$$ $$$0$$$ $$$0$$$. Теперь единственный способ выиграть, это прыгнуть с $$$1$$$-й платформы на $$$5$$$-ю платформу.</p><p>В третьем наборе входных данных, Gildong может поменять $$$a_2$$$ и $$$a_8$$$ на $$$0$$$, тогда единственный способ выиграть это: $$$1$$$ – $$$3$$$ – $$$7$$$ – $$$9$$$.</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:17:02</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:'8124b495ac3f4991',t:'MTY5NjY2NjYyMi40ODMwMDA='};_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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "*2700"] | ||
1454A | 1454 | 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$$$).</p><p>Напомним, что перестановкой длины $$$n$$$ называется массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$, расположенных в любом порядке. Например, $$$[2, 3, 1, 5, 4]$$$ является перестановкой длины $$$5$$$, но $$$[1, 2, 2]$$$ не является перестановкой ($$$2$$$ встречается в массиве дважды), а также $$$[1, 3, 4]$$$ не является перестановкой ($$$n = 3$$$, но в массиве есть $$$4$$$).</p><p>Ваша задача — найти такую перестановку $$$p$$$ длины $$$n$$$, что не существует индекса $$$i$$$ ($$$1 \le i \le n$$$) такого, для которого выполняется $$$p_i = i$$$ (таким образом, для всех $$$i$$$ от $$$1$$$ до $$$n$$$ должно выполняться условие $$$p_i \ne i$$$).</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Если существует несколько возможных ответов, вы можете вывести любой. Можно доказать, что ответ существует для любого $$$n > 1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 100$$$) — длину перестановки, которую вам необходимо найти.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ — перестановку, в которой не существует индекса $$$i$$$ ($$$1 \le i \le n$$$) такого, что для него выполняется $$$p_i = i$$$ (таким образом, для всех $$$i$$$ от $$$1$$$ до $$$n$$$ должно выполняться условие $$$p_i \ne i$$$).</p><p>Если существует несколько возможных ответов, вы можете вывести любой. Можно доказать, что ответ существует для любого $$$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>
2
2
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1
2 1 5 3 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</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="a659fb433e045a39e687f40493c8cc95"/>
<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="d0c5555b071c6d4ce2d405dcd6bf4b0594be6175"/>
<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='a659fb433e045a39e687f40493c8cc95'> </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%2F1454%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='a659fb433e045a39e687f40493c8cc95'/>
<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/1454">Codeforces Round 686 (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='a659fb433e045a39e687f40493c8cc95'/>
<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/1454/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='a659fb433e045a39e687f40493c8cc95'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="808360"/>
<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='a659fb433e045a39e687f40493c8cc95'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="808360"/>
<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/84957" title="84957" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12464" resourceName="84957"
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/84984" title="Разбор Codeforces Round #686 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12461:12462" 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="//www.youtube.com/watch?v=cFhSJgCplUk" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12465" resourceName="watch"
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/1454">Задачи</a></li>
<li><a
href="/contest/1454/submit">Отослать</a></li>
<li><a
href="/contest/1454/my">Мои посылки</a></li>
<li><a
href="/contest/1454/status">Статус</a></li>
<li><a
href="/contest/1454/hacks">Взломы</a></li>
<li><a
href="/contest/1454/standings">Положение</a></li>
<li><a
href="/contest/1454/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_021e1421c92bc3516e219153f205ca2500715e1d">
<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$$$).</p><p>Напомним, что перестановкой длины $$$n$$$ называется массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$, расположенных в любом порядке. Например, $$$[2, 3, 1, 5, 4]$$$ является перестановкой длины $$$5$$$, но $$$[1, 2, 2]$$$ не является перестановкой ($$$2$$$ встречается в массиве дважды), а также $$$[1, 3, 4]$$$ не является перестановкой ($$$n = 3$$$, но в массиве есть $$$4$$$).</p><p>Ваша задача — найти такую перестановку $$$p$$$ длины $$$n$$$, что не существует индекса $$$i$$$ ($$$1 \le i \le n$$$) такого, для которого выполняется $$$p_i = i$$$ (таким образом, для всех $$$i$$$ от $$$1$$$ до $$$n$$$ должно выполняться условие $$$p_i \ne i$$$).</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Если существует несколько возможных ответов, вы можете вывести любой. Можно доказать, что ответ существует для любого $$$n > 1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 100$$$) — длину перестановки, которую вам необходимо найти.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ — перестановку, в которой не существует индекса $$$i$$$ ($$$1 \le i \le n$$$) такого, что для него выполняется $$$p_i = i$$$ (таким образом, для всех $$$i$$$ от $$$1$$$ до $$$n$$$ должно выполняться условие $$$p_i \ne i$$$).</p><p>Если существует несколько возможных ответов, вы можете вывести любой. Можно доказать, что ответ существует для любого $$$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>
2
2
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1
2 1 5 3 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</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:17: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:'8124b49e29a63a65',t:'MTY5NjY2NjYyMy44MzEwMDA='};_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", "\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"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*800"] | ||
1454B | 1454 | B | ru | B. Unique Bid Auction | <div class="problem-statement"><div class="header"><div class="title">B. Unique Bid Auction</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>Существует игра под названием «Unique Bid Auction». Вы можете узнать про нее больше здесь: <a href="https://en.wikipedia.org/wiki/Unique_bid_auction">https://en.wikipedia.org/wiki/Unique_bid_auction</a> (тем не менее, в этом нет необходимости для решения задачи).</p><p>Давайте немного упростим эту игру. Формально, в игре есть $$$n$$$ участников, $$$i$$$-й участник выбрал число $$$a_i$$$. Победителем игры является тот участник, чье число <span class="tex-font-style-bf">уникально</span> (то есть никто кроме него не выбрал это число) и <span class="tex-font-style-bf">минимально</span> (то есть среди всех уникальных значений $$$a$$$ минимальное из них является выигрышным).</p><p>Ваша задача — найти <span class="tex-font-style-bf">индекс</span> участника, который победил в игре (или же <span class="tex-font-style-tt">-1</span>, если победителя нет). Индексы начинаются с $$$1$$$, то есть участники пронумерованы от $$$1$$$ до $$$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>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество участников. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), где $$$a_i$$$ равно числу, выбранному $$$i$$$-м участником.</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>Выведите ответ на каждый набор тестовых данных — <span class="tex-font-style-bf">индекс</span> участника, который победил в игре (или же <span class="tex-font-style-tt">-1</span>, если победителя нет). <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>
6
2
1 1
3
2 1 3
4
2 2 2 3
1
1
5
2 3 2 4 2
6
1 1 5 5 4 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
2
4
1
2
-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="cf4e7cf86eeae57d2dbbefd4d76bb4eb"/>
<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="d0c5555b071c6d4ce2d405dcd6bf4b0594be6175"/>
<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='cf4e7cf86eeae57d2dbbefd4d76bb4eb'> </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%2F1454%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='cf4e7cf86eeae57d2dbbefd4d76bb4eb'/>
<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/1454">Codeforces Round 686 (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='cf4e7cf86eeae57d2dbbefd4d76bb4eb'/>
<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/1454/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='cf4e7cf86eeae57d2dbbefd4d76bb4eb'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="808361"/>
<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='cf4e7cf86eeae57d2dbbefd4d76bb4eb'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="808361"/>
<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/84957" title="84957" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12464" resourceName="84957"
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/84984" title="Разбор Codeforces Round #686 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12461:12462" 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="//www.youtube.com/watch?v=cFhSJgCplUk" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12465" resourceName="watch"
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/1454">Задачи</a></li>
<li><a
href="/contest/1454/submit">Отослать</a></li>
<li><a
href="/contest/1454/my">Мои посылки</a></li>
<li><a
href="/contest/1454/status">Статус</a></li>
<li><a
href="/contest/1454/hacks">Взломы</a></li>
<li><a
href="/contest/1454/standings">Положение</a></li>
<li><a
href="/contest/1454/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_0cbc8c352d4d5e028850bb30c1ffe778c902c0cd">
<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. Unique Bid Auction</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>Существует игра под названием «Unique Bid Auction». Вы можете узнать про нее больше здесь: <a href="https://en.wikipedia.org/wiki/Unique_bid_auction">https://en.wikipedia.org/wiki/Unique_bid_auction</a> (тем не менее, в этом нет необходимости для решения задачи).</p><p>Давайте немного упростим эту игру. Формально, в игре есть $$$n$$$ участников, $$$i$$$-й участник выбрал число $$$a_i$$$. Победителем игры является тот участник, чье число <span class="tex-font-style-bf">уникально</span> (то есть никто кроме него не выбрал это число) и <span class="tex-font-style-bf">минимально</span> (то есть среди всех уникальных значений $$$a$$$ минимальное из них является выигрышным).</p><p>Ваша задача — найти <span class="tex-font-style-bf">индекс</span> участника, который победил в игре (или же <span class="tex-font-style-tt">-1</span>, если победителя нет). Индексы начинаются с $$$1$$$, то есть участники пронумерованы от $$$1$$$ до $$$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>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество участников. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), где $$$a_i$$$ равно числу, выбранному $$$i$$$-м участником.</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>Выведите ответ на каждый набор тестовых данных — <span class="tex-font-style-bf">индекс</span> участника, который победил в игре (или же <span class="tex-font-style-tt">-1</span>, если победителя нет). <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>
6
2
1 1
3
2 1 3
4
2 2 2 3
1
1
5
2 3 2 4 2
6
1 1 5 5 4 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
2
4
1
2
-1
</pre></div></div></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:17: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:'8124b4a69c121654',t:'MTY5NjY2NjYyNS4xODkwMDA='};_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"] | ||
1454C | 1454 | 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>Вы хотите изменить эту последовательность таким образом, чтобы все элементы в ней <span class="tex-font-style-it">были равны между собой</span> (то есть чтобы она состояла из какого-то количества вхождений одного элемента).</p><p>Чтобы это сделать, вы выбираете какое-то целое число $$$x$$$, <span class="tex-font-style-bf">которое встречается в $$$a$$$ хотя бы раз</span>, и затем совершаете следующую операцию любое количество раз (возможно, нулевое): выбираете какой-то отрезок последовательности $$$[l, r]$$$ и удаляете его. Но есть одно исключение: <span class="tex-font-style-bf">вы не можете выбирать отрезки, которые содержат $$$x$$$</span>. Более формально, вы выбираете какую-то такую последовательную подпоследовательность $$$[a_l, a_{l + 1}, \dots, a_r]$$$, что $$$a_i \ne x$$$ для $$$l \le i \le r$$$, и удаляете ее. После удаления индексация элементов справа от удаленного отрезка меняется: элемент, который был $$$(r+1)$$$-м, становится $$$l$$$-м, элемент, который был $$$(r+2)$$$-м, становится $$$(l+1)$$$-м, и так далее (то есть последовательность просто схлопывается).</p><p>Заметьте, что вы <span class="tex-font-style-bf">не можете изменять</span> $$$x$$$ после того, выбрали его.</p><p>Например, пусть $$$n = 6$$$, $$$a = [1, 3, 2, 4, 1, 2]$$$. Тогда одним из способов изменить ее за две операции является выбрать $$$x = 1$$$, а затем:</p><ol> <li> выбрать $$$l = 2$$$, $$$r = 4$$$, после чего получится последовательность $$$a = [1, 1, 2]$$$; </li><li> выбрать $$$l = 3$$$, $$$r = 3$$$, после чего получится последовательность $$$a = [1, 1]$$$. </li></ol><p>Заметьте, что выбор $$$x$$$ не является операцией. Также заметьте, что вы <span class="tex-font-style-bf">не можете</span> удалять никакое вхождение $$$x$$$.</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 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество элементов в $$$a$$$. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</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>Выведите ответ на каждый набор тестовых данных — <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
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
1
2
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="a5a814d1b9e77b732d5d26c141255c78"/>
<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="d0c5555b071c6d4ce2d405dcd6bf4b0594be6175"/>
<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='a5a814d1b9e77b732d5d26c141255c78'> </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%2F1454%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='a5a814d1b9e77b732d5d26c141255c78'/>
<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/1454">Codeforces Round 686 (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='a5a814d1b9e77b732d5d26c141255c78'/>
<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/1454/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='a5a814d1b9e77b732d5d26c141255c78'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="808362"/>
<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='a5a814d1b9e77b732d5d26c141255c78'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="808362"/>
<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/84957" title="84957" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12464" resourceName="84957"
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/84984" title="Разбор Codeforces Round #686 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12461:12462" 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="//www.youtube.com/watch?v=cFhSJgCplUk" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12465" resourceName="watch"
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/1454">Задачи</a></li>
<li><a
href="/contest/1454/submit">Отослать</a></li>
<li><a
href="/contest/1454/my">Мои посылки</a></li>
<li><a
href="/contest/1454/status">Статус</a></li>
<li><a
href="/contest/1454/hacks">Взломы</a></li>
<li><a
href="/contest/1454/standings">Положение</a></li>
<li><a
href="/contest/1454/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_61bf74b8296d470a39b20a4e71f9fc7123f65233">
<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>Вы хотите изменить эту последовательность таким образом, чтобы все элементы в ней <span class="tex-font-style-it">были равны между собой</span> (то есть чтобы она состояла из какого-то количества вхождений одного элемента).</p><p>Чтобы это сделать, вы выбираете какое-то целое число $$$x$$$, <span class="tex-font-style-bf">которое встречается в $$$a$$$ хотя бы раз</span>, и затем совершаете следующую операцию любое количество раз (возможно, нулевое): выбираете какой-то отрезок последовательности $$$[l, r]$$$ и удаляете его. Но есть одно исключение: <span class="tex-font-style-bf">вы не можете выбирать отрезки, которые содержат $$$x$$$</span>. Более формально, вы выбираете какую-то такую последовательную подпоследовательность $$$[a_l, a_{l + 1}, \dots, a_r]$$$, что $$$a_i \ne x$$$ для $$$l \le i \le r$$$, и удаляете ее. После удаления индексация элементов справа от удаленного отрезка меняется: элемент, который был $$$(r+1)$$$-м, становится $$$l$$$-м, элемент, который был $$$(r+2)$$$-м, становится $$$(l+1)$$$-м, и так далее (то есть последовательность просто схлопывается).</p><p>Заметьте, что вы <span class="tex-font-style-bf">не можете изменять</span> $$$x$$$ после того, выбрали его.</p><p>Например, пусть $$$n = 6$$$, $$$a = [1, 3, 2, 4, 1, 2]$$$. Тогда одним из способов изменить ее за две операции является выбрать $$$x = 1$$$, а затем:</p><ol> <li> выбрать $$$l = 2$$$, $$$r = 4$$$, после чего получится последовательность $$$a = [1, 1, 2]$$$; </li><li> выбрать $$$l = 3$$$, $$$r = 3$$$, после чего получится последовательность $$$a = [1, 1]$$$. </li></ol><p>Заметьте, что выбор $$$x$$$ не является операцией. Также заметьте, что вы <span class="tex-font-style-bf">не можете</span> удалять никакое вхождение $$$x$$$.</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 2 \cdot 10^4$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество элементов в $$$a$$$. Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</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>Выведите ответ на каждый набор тестовых данных — <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
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
1
2
3
</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:17: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:'8124b4af1b2a163a',t:'MTY5NjY2NjYyNi41NzIwMDA='};_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"] | ||
1454D | 1454 | D | ru | D. Число в последовательность | <div class="problem-statement"><div class="header"><div class="title">D. Число в последовательность</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$$$ ($$$n > 1$$$).</p><p>Ваша задача — найти последовательность целых чисел $$$a_1, a_2, \ldots, a_k$$$ такую, что:</p><ul> <li> каждое $$$a_i$$$ строго больше $$$1$$$; </li><li> $$$a_1 \cdot a_2 \cdot \ldots \cdot a_k = n$$$ (то есть произведение этой последовательности равно $$$n$$$); </li><li> $$$a_{i + 1}$$$ делится на $$$a_i$$$ для всех $$$i$$$ от $$$1$$$ до $$$k-1$$$; </li><li> $$$k$$$ является <span class="tex-font-style-bf">максимально</span> возможным (то есть длина этой последовательности является <span class="tex-font-style-bf">максимально</span> возможной). </li></ul><p>Если существует несколько таких последовательностей, любая из них считается подходящей. Можно доказать, что хотя бы одна корректная последовательность всегда существует для любого целого числа $$$n > 1$$$.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 5000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^{10}$$$).</p><p>Гарантируется, что сумма $$$n$$$ не превосходит $$$10^{10}$$$ ($$$\sum n \le 10^{10}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на каждый набор тестовых данных: в первой строке выведите одно положительное целое число $$$k$$$ — <span class="tex-font-style-bf">максимально</span> возможную длину $$$a$$$. Во второй строке выведите $$$k$$$ целых чисел $$$a_1, a_2, \ldots, a_k$$$ — последовательность длины $$$k$$$, удовлетворяющую ограничениям из условия задачи.</p><p>Если существует несколько возможных ответов, вы можете вывести любой из них. Можно доказать, что хотя бы одна корректная последовательность всегда существует для любого целого числа $$$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>
4
2
360
4999999937
4998207083
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
3
2 2 90
1
4999999937
1
4998207083
</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="9afa4e103502284904e00484012610f6"/>
<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="d0c5555b071c6d4ce2d405dcd6bf4b0594be6175"/>
<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='9afa4e103502284904e00484012610f6'> </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%2F1454%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='9afa4e103502284904e00484012610f6'/>
<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/1454">Codeforces Round 686 (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='9afa4e103502284904e00484012610f6'/>
<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/1454/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="Сложность">
*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='9afa4e103502284904e00484012610f6'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="808363"/>
<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='9afa4e103502284904e00484012610f6'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="808363"/>
<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/84957" title="84957" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12464" resourceName="84957"
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/84984" title="Разбор Codeforces Round #686 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12461:12462" 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="//www.youtube.com/watch?v=cFhSJgCplUk" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12465" resourceName="watch"
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/1454">Задачи</a></li>
<li><a
href="/contest/1454/submit">Отослать</a></li>
<li><a
href="/contest/1454/my">Мои посылки</a></li>
<li><a
href="/contest/1454/status">Статус</a></li>
<li><a
href="/contest/1454/hacks">Взломы</a></li>
<li><a
href="/contest/1454/standings">Положение</a></li>
<li><a
href="/contest/1454/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_0149468f79a30ca3e3cc892ed132b8147366e831">
<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>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$$$ ($$$n > 1$$$).</p><p>Ваша задача — найти последовательность целых чисел $$$a_1, a_2, \ldots, a_k$$$ такую, что:</p><ul> <li> каждое $$$a_i$$$ строго больше $$$1$$$; </li><li> $$$a_1 \cdot a_2 \cdot \ldots \cdot a_k = n$$$ (то есть произведение этой последовательности равно $$$n$$$); </li><li> $$$a_{i + 1}$$$ делится на $$$a_i$$$ для всех $$$i$$$ от $$$1$$$ до $$$k-1$$$; </li><li> $$$k$$$ является <span class="tex-font-style-bf">максимально</span> возможным (то есть длина этой последовательности является <span class="tex-font-style-bf">максимально</span> возможной). </li></ul><p>Если существует несколько таких последовательностей, любая из них считается подходящей. Можно доказать, что хотя бы одна корректная последовательность всегда существует для любого целого числа $$$n > 1$$$.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 5000$$$) — количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Единственная строка набора тестовых данных содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^{10}$$$).</p><p>Гарантируется, что сумма $$$n$$$ не превосходит $$$10^{10}$$$ ($$$\sum n \le 10^{10}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите ответ на каждый набор тестовых данных: в первой строке выведите одно положительное целое число $$$k$$$ — <span class="tex-font-style-bf">максимально</span> возможную длину $$$a$$$. Во второй строке выведите $$$k$$$ целых чисел $$$a_1, a_2, \ldots, a_k$$$ — последовательность длины $$$k$$$, удовлетворяющую ограничениям из условия задачи.</p><p>Если существует несколько возможных ответов, вы можете вывести любой из них. Можно доказать, что хотя бы одна корректная последовательность всегда существует для любого целого числа $$$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>
4
2
360
4999999937
4998207083
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
3
2 2 90
1
4999999937
1
4998207083
</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:17: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:'8124b4b7ce7c75ab',t:'MTY5NjY2NjYyNy45OTIwMDA='};_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.", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1300"] | ||
1454E | 1454 | 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> граф, состоящий из $$$n$$$ вершин и $$$n$$$ ребер. Гарантируется, что заданный граф является <span class="tex-font-style-bf">связным</span> (то есть возможно достичь любую вершину из любой другой вершины) и не содержит петель и кратных ребер.</p><p>Ваша задача — посчитать количество <span class="tex-font-style-bf">простых путей</span> длины <span class="tex-font-style-bf">хотя бы</span> $$$1$$$ в заданном графе. Заметьте, что пути, которые отличаются только направлением, являются одинаковыми (то есть вам необходимо посчитать количество <span class="tex-font-style-it">неориентированных</span> путей). Например, пути $$$[1, 2, 3]$$$ и $$$[3, 2, 1]$$$ являются одинаковыми.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Напомним, что путем в графе называется такая последовательность вершин $$$v_1, v_2, \ldots, v_k$$$, что каждая пара соседних (последовательных) вершин в этой последовательности соединена ребром. Длиной пути является количество ребер в нем. <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$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — количество вершин (и количество ребер) в графе.</p><p>Следующие $$$n$$$ строк набора тестовых данных описывают ребра: ребро $$$i$$$ задано парой вершин $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), где $$$u_i$$$ и $$$v_i$$$ — это вершины, которые соединяет $$$i$$$-е ребро. Для каждой пары вершин $$$(u, v)$$$ существует не более одного ребра между $$$u$$$ и $$$v$$$. Не существует ребер из вершины в саму себя. Таким образом, в графе отсутствуют петли и кратные ребра. Граф является <span class="tex-font-style-bf">неориентированным</span>, то есть все его ребра являются двунаправленными. Граф является связным, то есть всегда возможно достичь любую вершину из любой другой вершины, двигаясь по ребрам графа.</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>Выведите одно целое число для каждого набора тестовых данных: количество <span class="tex-font-style-bf">простых путей</span> длины <span class="tex-font-style-bf">хотя бы</span> $$$1$$$ в заданном графе. Заметьте, что пути, которые отличаются только направлением, являются одинаковыми (то есть вам необходимо посчитать количество <span class="tex-font-style-it">неориентированных</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
3
1 2
2 3
1 3
4
1 2
2 3
3 4
4 2
5
1 2
2 3
1 3
2 5
4 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
11
18
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим второй набор тестовых данных примера. Он выглядит следующим образом:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/cdc0dddade1f65afc73f91ab5381548d98c39863.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Здесь есть $$$11$$$ различных простых путей:</p><ol> <li> $$$[1, 2]$$$; </li><li> $$$[2, 3]$$$; </li><li> $$$[3, 4]$$$; </li><li> $$$[2, 4]$$$; </li><li> $$$[1, 2, 4]$$$; </li><li> $$$[1, 2, 3]$$$; </li><li> $$$[2, 3, 4]$$$; </li><li> $$$[2, 4, 3]$$$; </li><li> $$$[3, 2, 4]$$$; </li><li> $$$[1, 2, 3, 4]$$$; </li><li> $$$[1, 2, 4, 3]$$$. </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="c254e9c47d816213711a99121228f391"/>
<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="d0c5555b071c6d4ce2d405dcd6bf4b0594be6175"/>
<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='c254e9c47d816213711a99121228f391'> </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%2F1454%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='c254e9c47d816213711a99121228f391'/>
<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/1454">Codeforces Round 686 (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='c254e9c47d816213711a99121228f391'/>
<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/1454/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='c254e9c47d816213711a99121228f391'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="808364"/>
<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='c254e9c47d816213711a99121228f391'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="808364"/>
<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/84957" title="84957" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12464" resourceName="84957"
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/84984" title="Разбор Codeforces Round #686 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12461:12462" 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="//www.youtube.com/watch?v=cFhSJgCplUk" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12465" resourceName="watch"
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/1454">Задачи</a></li>
<li><a
href="/contest/1454/submit">Отослать</a></li>
<li><a
href="/contest/1454/my">Мои посылки</a></li>
<li><a
href="/contest/1454/status">Статус</a></li>
<li><a
href="/contest/1454/hacks">Взломы</a></li>
<li><a
href="/contest/1454/standings">Положение</a></li>
<li><a
href="/contest/1454/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_577ba5725de24a158cf703f4903793d1a4d37476">
<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> граф, состоящий из $$$n$$$ вершин и $$$n$$$ ребер. Гарантируется, что заданный граф является <span class="tex-font-style-bf">связным</span> (то есть возможно достичь любую вершину из любой другой вершины) и не содержит петель и кратных ребер.</p><p>Ваша задача — посчитать количество <span class="tex-font-style-bf">простых путей</span> длины <span class="tex-font-style-bf">хотя бы</span> $$$1$$$ в заданном графе. Заметьте, что пути, которые отличаются только направлением, являются одинаковыми (то есть вам необходимо посчитать количество <span class="tex-font-style-it">неориентированных</span> путей). Например, пути $$$[1, 2, 3]$$$ и $$$[3, 2, 1]$$$ являются одинаковыми.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p><p>Напомним, что путем в графе называется такая последовательность вершин $$$v_1, v_2, \ldots, v_k$$$, что каждая пара соседних (последовательных) вершин в этой последовательности соединена ребром. Длиной пути является количество ребер в нем. <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$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — количество вершин (и количество ребер) в графе.</p><p>Следующие $$$n$$$ строк набора тестовых данных описывают ребра: ребро $$$i$$$ задано парой вершин $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$), где $$$u_i$$$ и $$$v_i$$$ — это вершины, которые соединяет $$$i$$$-е ребро. Для каждой пары вершин $$$(u, v)$$$ существует не более одного ребра между $$$u$$$ и $$$v$$$. Не существует ребер из вершины в саму себя. Таким образом, в графе отсутствуют петли и кратные ребра. Граф является <span class="tex-font-style-bf">неориентированным</span>, то есть все его ребра являются двунаправленными. Граф является связным, то есть всегда возможно достичь любую вершину из любой другой вершины, двигаясь по ребрам графа.</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>Выведите одно целое число для каждого набора тестовых данных: количество <span class="tex-font-style-bf">простых путей</span> длины <span class="tex-font-style-bf">хотя бы</span> $$$1$$$ в заданном графе. Заметьте, что пути, которые отличаются только направлением, являются одинаковыми (то есть вам необходимо посчитать количество <span class="tex-font-style-it">неориентированных</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
3
1 2
2 3
1 3
4
1 2
2 3
3 4
4 2
5
1 2
2 3
1 3
2 5
4 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
11
18
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим второй набор тестовых данных примера. Он выглядит следующим образом:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/cdc0dddade1f65afc73f91ab5381548d98c39863.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Здесь есть $$$11$$$ различных простых путей:</p><ol> <li> $$$[1, 2]$$$; </li><li> $$$[2, 3]$$$; </li><li> $$$[3, 4]$$$; </li><li> $$$[2, 4]$$$; </li><li> $$$[1, 2, 4]$$$; </li><li> $$$[1, 2, 3]$$$; </li><li> $$$[2, 3, 4]$$$; </li><li> $$$[2, 4, 3]$$$; </li><li> $$$[3, 2, 4]$$$; </li><li> $$$[1, 2, 3, 4]$$$; </li><li> $$$[1, 2, 4, 3]$$$. </li></ol></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:17: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:'8124b4c0b8387b73',t:'MTY5NjY2NjYyOS4zNDEwMDA='};_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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\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", "*2000"] | ||
1454F | 1454 | 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>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел.</p><p>Пусть $$$min(l, r)$$$ равно минимальному значению среди $$$a_l, a_{l + 1}, \ldots, a_r$$$, а $$$max(l, r)$$$ равно максимальному значению среди $$$a_l, a_{l + 1}, \ldots, a_r$$$.</p><p>Ваша задача — выбрать три таких <span class="tex-font-style-bf">положительных</span> (больших $$$0$$$) целых числа $$$x$$$, $$$y$$$ и $$$z$$$, что:</p><ul> <li> $$$x + y + z = n$$$; </li><li> $$$max(1, x) = min(x + 1, x + y) = max(x + y + 1, n)$$$. </li></ul><p>Другими словами, вам необходимо разделить массив $$$a$$$ на три последовательные непустые части, которые покрывают весь массив, и максимум в первой части равен минимуму во второй части, а также равен максимуму в третьей части (или же определить, что такое разбиение невозможно найти).</p><p>Среди всех возможных троек (разделений) можно выбрать любое.</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$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — длину $$$a$$$.</p><p>Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</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>Выведите ответ на каждый набор тестовых данных: <span class="tex-font-style-tt">NO</span> в единственной строке, если не существует такого разбиения $$$a$$$, которе удовлетворяет ограничениям из условия задачи. Иначе выведите <span class="tex-font-style-tt">YES</span> в первой строке и три целых числа $$$x$$$, $$$y$$$ и $$$z$$$ ($$$x + y + z = n$$$) во второй строке.</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>
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 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="202feff2477456d52fbbae7cc146350f"/>
<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="d0c5555b071c6d4ce2d405dcd6bf4b0594be6175"/>
<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='202feff2477456d52fbbae7cc146350f'> </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%2F1454%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='202feff2477456d52fbbae7cc146350f'/>
<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/1454">Codeforces Round 686 (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='202feff2477456d52fbbae7cc146350f'/>
<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/1454/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='202feff2477456d52fbbae7cc146350f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="808365"/>
<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='202feff2477456d52fbbae7cc146350f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="808365"/>
<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/84957" title="84957" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12464" resourceName="84957"
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/84984" title="Разбор Codeforces Round #686 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12461:12462" 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="//www.youtube.com/watch?v=cFhSJgCplUk" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12465" resourceName="watch"
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/1454">Задачи</a></li>
<li><a
href="/contest/1454/submit">Отослать</a></li>
<li><a
href="/contest/1454/my">Мои посылки</a></li>
<li><a
href="/contest/1454/status">Статус</a></li>
<li><a
href="/contest/1454/hacks">Взломы</a></li>
<li><a
href="/contest/1454/standings">Положение</a></li>
<li><a
href="/contest/1454/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_c246e0c117acfd79ef7ee0f7377b7d021f078a52">
<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>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел.</p><p>Пусть $$$min(l, r)$$$ равно минимальному значению среди $$$a_l, a_{l + 1}, \ldots, a_r$$$, а $$$max(l, r)$$$ равно максимальному значению среди $$$a_l, a_{l + 1}, \ldots, a_r$$$.</p><p>Ваша задача — выбрать три таких <span class="tex-font-style-bf">положительных</span> (больших $$$0$$$) целых числа $$$x$$$, $$$y$$$ и $$$z$$$, что:</p><ul> <li> $$$x + y + z = n$$$; </li><li> $$$max(1, x) = min(x + 1, x + y) = max(x + y + 1, n)$$$. </li></ul><p>Другими словами, вам необходимо разделить массив $$$a$$$ на три последовательные непустые части, которые покрывают весь массив, и максимум в первой части равен минимуму во второй части, а также равен максимуму в третьей части (или же определить, что такое разбиение невозможно найти).</p><p>Среди всех возможных троек (разделений) можно выбрать любое.</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$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — длину $$$a$$$.</p><p>Вторая строка набора тестовых данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</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>Выведите ответ на каждый набор тестовых данных: <span class="tex-font-style-tt">NO</span> в единственной строке, если не существует такого разбиения $$$a$$$, которе удовлетворяет ограничениям из условия задачи. Иначе выведите <span class="tex-font-style-tt">YES</span> в первой строке и три целых числа $$$x$$$, $$$y$$$ и $$$z$$$ ($$$x + y + z = n$$$) во второй строке.</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>
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
</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:17: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:'8124b4c91e1e164b',t:'MTY5NjY2NjYzMC42NzgwMDA='};_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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2100"] | ||
1455A | 1455 | 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>Давайте определим функцию $$$f(x)$$$ ($$$x$$$ — положительное целое число) следующим образом: запишем все цифры десятичного представления $$$x$$$ в обратном порядке, а затем избавимся от лидирующих нулей. Например, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.</p><p>Давайте определим другую функцию $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ — положительное целое число).</p><p>Ваша задача состоит в следующем: для данного положительного целого числа $$$n$$$ вычислите количество различных значений $$$g(x)$$$ среди всех чисел $$$x$$$ таких, что $$$1 \le x \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из одной строки, содержащей одно целое число $$$n$$$ ($$$1 \le n < 10^{100}$$$). Это целое число задается без лидирующих нулей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для набора входных данных выведите одно целое число — количество различных значений, которые может принимать $$$g(x)$$$, если $$$x$$$ может быть любым целым числом из $$$[1, n]$$$.</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
37
998244353
1000000007
12345678901337426966631415
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
9
10
26
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пояснения к двум первым наборам входных данных примера из условия:</p><ol> <li> если $$$n = 4$$$, то для каждого целого числа $$$x$$$ такого, что $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; </li><li> если $$$n = 37$$$, то для некоторых целых чисел $$$x$$$ таких, что $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (например, если $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); а для других значений $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (например, если $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). Итак, существуют два различных значения $$$g(x)$$$. </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="806c6456e76f8819a90c0bbedbe86ff1"/>
<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="f7e7e2a66369bc4b78b7cc5992accc53fbe5e0d6"/>
<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='806c6456e76f8819a90c0bbedbe86ff1'> </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%2F1455%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='806c6456e76f8819a90c0bbedbe86ff1'/>
<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/1455">Educational Codeforces Round 99 (рейтинговый для Див. 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='806c6456e76f8819a90c0bbedbe86ff1'/>
<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/1455/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='806c6456e76f8819a90c0bbedbe86ff1'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="815714"/>
<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='806c6456e76f8819a90c0bbedbe86ff1'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="815714"/>
<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/85116" title="Educational Codeforces Round 99 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12478:12479" 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/85186" title="85186" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12501:12502" 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="//www.youtube.com/watch?v=1-S4FALm9OI" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12633" resourceName="watch"
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/1455">Задачи</a></li>
<li><a
href="/contest/1455/submit">Отослать</a></li>
<li><a
href="/contest/1455/my">Мои посылки</a></li>
<li><a
href="/contest/1455/status">Статус</a></li>
<li><a
href="/contest/1455/hacks">Взломы</a></li>
<li><a
href="/contest/1455/standings">Положение</a></li>
<li><a
href="/contest/1455/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_3a9c185e00a165da72a0aa7c4f732bd6962bd1dd">
<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>Давайте определим функцию $$$f(x)$$$ ($$$x$$$ — положительное целое число) следующим образом: запишем все цифры десятичного представления $$$x$$$ в обратном порядке, а затем избавимся от лидирующих нулей. Например, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.</p><p>Давайте определим другую функцию $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ — положительное целое число).</p><p>Ваша задача состоит в следующем: для данного положительного целого числа $$$n$$$ вычислите количество различных значений $$$g(x)$$$ среди всех чисел $$$x$$$ таких, что $$$1 \le x \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из одной строки, содержащей одно целое число $$$n$$$ ($$$1 \le n < 10^{100}$$$). Это целое число задается без лидирующих нулей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для набора входных данных выведите одно целое число — количество различных значений, которые может принимать $$$g(x)$$$, если $$$x$$$ может быть любым целым числом из $$$[1, n]$$$.</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
37
998244353
1000000007
12345678901337426966631415
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
9
10
26
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пояснения к двум первым наборам входных данных примера из условия:</p><ol> <li> если $$$n = 4$$$, то для каждого целого числа $$$x$$$ такого, что $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; </li><li> если $$$n = 37$$$, то для некоторых целых чисел $$$x$$$ таких, что $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (например, если $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); а для других значений $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (например, если $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). Итак, существуют два различных значения $$$g(x)$$$. </li></ol></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:17: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:'8124b4d16b079d70',t:'MTY5NjY2NjYzMi4xMjUwMDA='};_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.", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*800"] | ||
1455B | 1455 | 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>Вы стоите на оси $$$\mathit{OX}$$$ в точке $$$0$$$ и хотите попасть в целочисленную точку $$$x > 0$$$.</p><p>Вы можете сделать некоторое количество прыжков. Предположим, вы сейчас в точке $$$y$$$ ($$$y$$$ может быть отрицательным) и прыгаете в $$$k$$$-й раз. Вы можете: </p><ul> <li> либо прыгнуть в точку $$$y + k$$$, </li><li> либо прыгнуть в точку $$$y - 1$$$. </li></ul><p>Какое минимальное количество прыжков вам понадобится, чтобы попасть в точку $$$x$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В первой и единственной строке каждого набора задано единственное целое число $$$x$$$ ($$$1 \le x \le 10^6$$$) — точка, куда вам нужно попасть.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите единственное число — минимальное количество прыжков, чтобы попасть в $$$x$$$. Можно доказать, что мы можем достигнуть любую целую точку $$$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
1
2
3
4
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
3
2
3
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$x = 1$$$, поэтому вам нужен только один прыжок: $$$1$$$-й прыжок из $$$0$$$ в $$$0 + 1 = 1$$$.</p><p>Во втором наборе $$$x = 2$$$. Вам необходимы хотя бы три прыжка: </p><ul> <li> $$$1$$$-й прыжок из $$$0$$$ в $$$0 + 1 = 1$$$; </li><li> $$$2$$$-й прыжок из $$$1$$$ в $$$1 + 2 = 3$$$; </li><li> $$$3$$$-й прыжок из $$$3$$$ в $$$3 - 1 = 2$$$; </li></ul><p>Двух прыжков недостаточно, потому что есть только следующие варианты: </p><ul> <li> $$$1$$$-й прыжок равный $$$-1$$$ и $$$2$$$-й равный $$$-1$$$ — вы попадете в $$$0 -1 -1 =-2$$$; </li><li> $$$1$$$-й прыжок равный $$$-1$$$ и $$$2$$$-й равный $$$+2$$$ — вы попадете в $$$0 -1 +2 = 1$$$; </li><li> $$$1$$$-й прыжок равный $$$+1$$$ и $$$2$$$-й равный $$$-1$$$ — вы попадете в $$$0 +1 -1 = 0$$$; </li><li> $$$1$$$-й прыжок равный $$$+1$$$ и $$$2$$$-й равный $$$+2$$$ — вы попадете в $$$0 +1 +2 = 3$$$; </li></ul><p>В третьем наборе, вам нужно два прыжка: $$$1$$$-й равный $$$+1$$$ и $$$2$$$-й равный $$$+2$$$, тогда $$$0 + 1 + 2 = 3$$$.</p><p>В четвертом наборе, вам нужно три прыжка: $$$1$$$-й равный $$$-1$$$, $$$2$$$-й равный $$$+2$$$ и $$$3$$$-й равный $$$+3$$$, тогда $$$0 - 1 + 2 + 3 = 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="17954cea51d0352f9b67e8eb587a190e"/>
<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="f7e7e2a66369bc4b78b7cc5992accc53fbe5e0d6"/>
<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='17954cea51d0352f9b67e8eb587a190e'> </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%2F1455%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='17954cea51d0352f9b67e8eb587a190e'/>
<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/1455">Educational Codeforces Round 99 (рейтинговый для Див. 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='17954cea51d0352f9b67e8eb587a190e'/>
<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/1455/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='17954cea51d0352f9b67e8eb587a190e'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="815715"/>
<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='17954cea51d0352f9b67e8eb587a190e'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="815715"/>
<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/85116" title="Educational Codeforces Round 99 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12478:12479" 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/85186" title="85186" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12501:12502" 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="//www.youtube.com/watch?v=1-S4FALm9OI" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12633" resourceName="watch"
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/1455">Задачи</a></li>
<li><a
href="/contest/1455/submit">Отослать</a></li>
<li><a
href="/contest/1455/my">Мои посылки</a></li>
<li><a
href="/contest/1455/status">Статус</a></li>
<li><a
href="/contest/1455/hacks">Взломы</a></li>
<li><a
href="/contest/1455/standings">Положение</a></li>
<li><a
href="/contest/1455/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_dae8bcd2b1466f2473fd1be8eb52f36490454704">
<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>Вы стоите на оси $$$\mathit{OX}$$$ в точке $$$0$$$ и хотите попасть в целочисленную точку $$$x > 0$$$.</p><p>Вы можете сделать некоторое количество прыжков. Предположим, вы сейчас в точке $$$y$$$ ($$$y$$$ может быть отрицательным) и прыгаете в $$$k$$$-й раз. Вы можете: </p><ul> <li> либо прыгнуть в точку $$$y + k$$$, </li><li> либо прыгнуть в точку $$$y - 1$$$. </li></ul><p>Какое минимальное количество прыжков вам понадобится, чтобы попасть в точку $$$x$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>В первой и единственной строке каждого набора задано единственное целое число $$$x$$$ ($$$1 \le x \le 10^6$$$) — точка, куда вам нужно попасть.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите единственное число — минимальное количество прыжков, чтобы попасть в $$$x$$$. Можно доказать, что мы можем достигнуть любую целую точку $$$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
1
2
3
4
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
3
2
3
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$x = 1$$$, поэтому вам нужен только один прыжок: $$$1$$$-й прыжок из $$$0$$$ в $$$0 + 1 = 1$$$.</p><p>Во втором наборе $$$x = 2$$$. Вам необходимы хотя бы три прыжка: </p><ul> <li> $$$1$$$-й прыжок из $$$0$$$ в $$$0 + 1 = 1$$$; </li><li> $$$2$$$-й прыжок из $$$1$$$ в $$$1 + 2 = 3$$$; </li><li> $$$3$$$-й прыжок из $$$3$$$ в $$$3 - 1 = 2$$$; </li></ul><p>Двух прыжков недостаточно, потому что есть только следующие варианты: </p><ul> <li> $$$1$$$-й прыжок равный $$$-1$$$ и $$$2$$$-й равный $$$-1$$$ — вы попадете в $$$0 -1 -1 =-2$$$; </li><li> $$$1$$$-й прыжок равный $$$-1$$$ и $$$2$$$-й равный $$$+2$$$ — вы попадете в $$$0 -1 +2 = 1$$$; </li><li> $$$1$$$-й прыжок равный $$$+1$$$ и $$$2$$$-й равный $$$-1$$$ — вы попадете в $$$0 +1 -1 = 0$$$; </li><li> $$$1$$$-й прыжок равный $$$+1$$$ и $$$2$$$-й равный $$$+2$$$ — вы попадете в $$$0 +1 +2 = 3$$$; </li></ul><p>В третьем наборе, вам нужно два прыжка: $$$1$$$-й равный $$$+1$$$ и $$$2$$$-й равный $$$+2$$$, тогда $$$0 + 1 + 2 = 3$$$.</p><p>В четвертом наборе, вам нужно три прыжка: $$$1$$$-й равный $$$-1$$$, $$$2$$$-й равный $$$+2$$$ и $$$3$$$-й равный $$$+3$$$, тогда $$$0 - 1 + 2 + 3 = 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:17: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:'8124b4da6f75160a',t:'MTY5NjY2NjYzMy41MTkwMDA='};_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", "*1200"] | ||
1455C | 1455 | 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><p>Игрок, подающий мяч, начинает раунд. Подающий наносит удар по мячу, затем принимающий делает ответный удар, отбивая мяч назад. После этого подающий и принимающий должны поочередно отбивать, пока один из них не пропустит мяч.</p><p>Тот, кто не отбивает удар, проигрывает этот раунд. Победитель раунда начинает следующий раунд. Алиса начинает первый раунд.</p><p>У Алисы $$$x$$$ выносливости, а у Боба $$$y$$$. Чтобы ударить по мячу (при подаче или отбивании), каждый игрок тратит $$$1$$$ выносливости, поэтому, если у него нулевая выносливость, он не может отбить мяч (и проигрывает раунд) или не может подать мяч (в этом случае подача мяча переходит к другому игроку). Если у обоих игроков закончилась выносливость, игра окончена.</p><p>Иногда стратегически оптимально не отбивать мяч, проиграть текущий раунд, но сохранить выносливость. Но во время подачи игрок обязан произвести удар, если у него осталась выносливость.</p><p>И Алиса, и Боб играют оптимально и хотят, во-первых, максимизировать свое количество побед а, во-вторых, минимизировать количество побед своего противника.</p><p>Подсчитайте итоговое число побед Алисы и Боба.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Первая и единственная строка каждого набора содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le 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>
3
1 1
2 1
1 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 1
1 1
0 7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Алиса подает мяч и тратит $$$1$$$ выносливости. Затем Боб отбивает мяч и также тратит $$$1$$$ выносливости. Алиса не может отбить мяч, так как у нее не осталось выносливости, и она проигрывает раунд. У них обоих закончилась выносливость, так что игра закончилась с $$$0$$$ побед у Алисы и $$$1$$$ победой Боба.</p><p>Во втором примере Алиса подает мяч и тратит $$$1$$$ выносливости. Боб решает не отбивать мяч — он проигрывает раунд, но сохраняет выносливость. Алиса, как победитель последнего раунда, подает мяч в следующем и тратит еще $$$1$$$ выносливости. На этот раз Боб отбивает мяч и тратит $$$1$$$ выносливости. У Алисы не осталось сил, поэтому она не может отбить мяч и проигрывает раунд. У них обоих закончилась выносливость, так что игра закончилась с $$$1$$$ победой у Алисы и $$$1$$$ победой у Боба.</p><p>В третьем примере Алиса подает мяч и тратит $$$1$$$ выносливости. Боб отбивает мяч и тратит $$$1$$$ выносливости. У Алисы кончилась выносливость, поэтому она не может отбить мяч и проигрывает раунд. Боб, как победитель, подает мяч в следующих $$$6$$$ раундах. Каждый раз Алиса не может отбить мяч и проигрывает каждую раунд. Игра заканчивается с $$$0$$$ побед у Алисы и $$$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="cae658ed80d75c0c603d7bc5bba9a89f"/>
<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="f7e7e2a66369bc4b78b7cc5992accc53fbe5e0d6"/>
<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='cae658ed80d75c0c603d7bc5bba9a89f'> </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%2F1455%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='cae658ed80d75c0c603d7bc5bba9a89f'/>
<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/1455">Educational Codeforces Round 99 (рейтинговый для Див. 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='cae658ed80d75c0c603d7bc5bba9a89f'/>
<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/1455/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='cae658ed80d75c0c603d7bc5bba9a89f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="815716"/>
<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='cae658ed80d75c0c603d7bc5bba9a89f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="815716"/>
<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/85116" title="Educational Codeforces Round 99 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12478:12479" 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/85186" title="85186" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12501:12502" 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="//www.youtube.com/watch?v=1-S4FALm9OI" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12633" resourceName="watch"
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/1455">Задачи</a></li>
<li><a
href="/contest/1455/submit">Отослать</a></li>
<li><a
href="/contest/1455/my">Мои посылки</a></li>
<li><a
href="/contest/1455/status">Статус</a></li>
<li><a
href="/contest/1455/hacks">Взломы</a></li>
<li><a
href="/contest/1455/standings">Положение</a></li>
<li><a
href="/contest/1455/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_4d82a687dd346efc16a32c3bf1a3e024423dfe7b">
<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><p>Игрок, подающий мяч, начинает раунд. Подающий наносит удар по мячу, затем принимающий делает ответный удар, отбивая мяч назад. После этого подающий и принимающий должны поочередно отбивать, пока один из них не пропустит мяч.</p><p>Тот, кто не отбивает удар, проигрывает этот раунд. Победитель раунда начинает следующий раунд. Алиса начинает первый раунд.</p><p>У Алисы $$$x$$$ выносливости, а у Боба $$$y$$$. Чтобы ударить по мячу (при подаче или отбивании), каждый игрок тратит $$$1$$$ выносливости, поэтому, если у него нулевая выносливость, он не может отбить мяч (и проигрывает раунд) или не может подать мяч (в этом случае подача мяча переходит к другому игроку). Если у обоих игроков закончилась выносливость, игра окончена.</p><p>Иногда стратегически оптимально не отбивать мяч, проиграть текущий раунд, но сохранить выносливость. Но во время подачи игрок обязан произвести удар, если у него осталась выносливость.</p><p>И Алиса, и Боб играют оптимально и хотят, во-первых, максимизировать свое количество побед а, во-вторых, минимизировать количество побед своего противника.</p><p>Подсчитайте итоговое число побед Алисы и Боба.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Первая и единственная строка каждого набора содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le 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>
3
1 1
2 1
1 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 1
1 1
0 7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Алиса подает мяч и тратит $$$1$$$ выносливости. Затем Боб отбивает мяч и также тратит $$$1$$$ выносливости. Алиса не может отбить мяч, так как у нее не осталось выносливости, и она проигрывает раунд. У них обоих закончилась выносливость, так что игра закончилась с $$$0$$$ побед у Алисы и $$$1$$$ победой Боба.</p><p>Во втором примере Алиса подает мяч и тратит $$$1$$$ выносливости. Боб решает не отбивать мяч — он проигрывает раунд, но сохраняет выносливость. Алиса, как победитель последнего раунда, подает мяч в следующем и тратит еще $$$1$$$ выносливости. На этот раз Боб отбивает мяч и тратит $$$1$$$ выносливости. У Алисы не осталось сил, поэтому она не может отбить мяч и проигрывает раунд. У них обоих закончилась выносливость, так что игра закончилась с $$$1$$$ победой у Алисы и $$$1$$$ победой у Боба.</p><p>В третьем примере Алиса подает мяч и тратит $$$1$$$ выносливости. Боб отбивает мяч и тратит $$$1$$$ выносливости. У Алисы кончилась выносливость, поэтому она не может отбить мяч и проигрывает раунд. Боб, как победитель, подает мяч в следующих $$$6$$$ раундах. Каждый раз Алиса не может отбить мяч и проигрывает каждую раунд. Игра заканчивается с $$$0$$$ побед у Алисы и $$$7$$$ победами у Боба.</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:17: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:'8124b4e33a7e7b77',t:'MTY5NjY2NjYzNC45MDAwMDA='};_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\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", "\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"] | ["\u0438\u0433\u0440\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1100"] | ||
1455D | 1455 | 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.5 секунд</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$$$, состоящая из $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$, а также целое число $$$x$$$. Ваша задача заключается в том, чтобы сделать последовательность $$$a$$$ отсортированной (последовательность отсортирована, если выполняется условие $$$a_1 \le a_2 \le a_3 \le \dots \le a_n$$$).</p><p>Чтобы отсортировать последовательность, вы можете выполнять следующую операцию любое количество раз (возможно, ноль): выбрать целое число $$$i$$$ такое, что $$$1 \le i \le n$$$ и $$$a_i > x$$$, поменять местами значения $$$a_i$$$ и $$$x$$$.</p><p>Например, если $$$a = [0, 2, 3, 5, 4]$$$, $$$x = 1$$$, возможна следующая последовательность операций:</p><ol> <li> выбрать $$$i = 2$$$ (это возможно, так как $$$a_2 > x$$$), получим $$$a = [0, 1, 3, 5, 4]$$$, $$$x = 2$$$; </li><li> выбрать $$$i = 3$$$ (это возможно, так как $$$a_3 > x$$$), получим $$$a = [0, 1, 2, 5, 4]$$$, $$$x = 3$$$; </li><li> выбрать $$$i = 4$$$ (это возможно, так как $$$a_4 > x$$$), получим $$$a = [0, 1, 2, 3, 4]$$$, $$$x = 5$$$. </li></ol><p>Вычислите минимальное количество операций, которые необходимо выполнить, чтобы $$$a$$$ стала отсортированной, или сообщите, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 500$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из двух строк. Первая строка содержит два целых числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 500$$$, $$$0 \le x \le 500$$$) — количество элементов в последовательности и начальное значение $$$x$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 500$$$).</p><p>Сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество операций, которые необходимо выполнить, чтобы сделать $$$a$$$ отсортированной, или $$$-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
2 3 5 4
5 6
1 1 3 4 4
1 10
2
2 10
11 9
2 10
12 11
5 18
81 324 218 413 324
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
0
0
-1
1
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="3427867af32e6386c23c1e3802a609c3"/>
<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="f7e7e2a66369bc4b78b7cc5992accc53fbe5e0d6"/>
<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='3427867af32e6386c23c1e3802a609c3'> </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%2F1455%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='3427867af32e6386c23c1e3802a609c3'/>
<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/1455">Educational Codeforces Round 99 (рейтинговый для Див. 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='3427867af32e6386c23c1e3802a609c3'/>
<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/1455/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='3427867af32e6386c23c1e3802a609c3'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="815717"/>
<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='3427867af32e6386c23c1e3802a609c3'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="815717"/>
<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/85116" title="Educational Codeforces Round 99 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12478:12479" 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/85186" title="85186" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12501:12502" 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="//www.youtube.com/watch?v=1-S4FALm9OI" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12633" resourceName="watch"
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/1455">Задачи</a></li>
<li><a
href="/contest/1455/submit">Отослать</a></li>
<li><a
href="/contest/1455/my">Мои посылки</a></li>
<li><a
href="/contest/1455/status">Статус</a></li>
<li><a
href="/contest/1455/hacks">Взломы</a></li>
<li><a
href="/contest/1455/standings">Положение</a></li>
<li><a
href="/contest/1455/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_b46b24c10df70e091089eb0d35758fd3f936d450">
<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.5 секунд</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$$$, состоящая из $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$, а также целое число $$$x$$$. Ваша задача заключается в том, чтобы сделать последовательность $$$a$$$ отсортированной (последовательность отсортирована, если выполняется условие $$$a_1 \le a_2 \le a_3 \le \dots \le a_n$$$).</p><p>Чтобы отсортировать последовательность, вы можете выполнять следующую операцию любое количество раз (возможно, ноль): выбрать целое число $$$i$$$ такое, что $$$1 \le i \le n$$$ и $$$a_i > x$$$, поменять местами значения $$$a_i$$$ и $$$x$$$.</p><p>Например, если $$$a = [0, 2, 3, 5, 4]$$$, $$$x = 1$$$, возможна следующая последовательность операций:</p><ol> <li> выбрать $$$i = 2$$$ (это возможно, так как $$$a_2 > x$$$), получим $$$a = [0, 1, 3, 5, 4]$$$, $$$x = 2$$$; </li><li> выбрать $$$i = 3$$$ (это возможно, так как $$$a_3 > x$$$), получим $$$a = [0, 1, 2, 5, 4]$$$, $$$x = 3$$$; </li><li> выбрать $$$i = 4$$$ (это возможно, так как $$$a_4 > x$$$), получим $$$a = [0, 1, 2, 3, 4]$$$, $$$x = 5$$$. </li></ol><p>Вычислите минимальное количество операций, которые необходимо выполнить, чтобы $$$a$$$ стала отсортированной, или сообщите, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 500$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из двух строк. Первая строка содержит два целых числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 500$$$, $$$0 \le x \le 500$$$) — количество элементов в последовательности и начальное значение $$$x$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_i \le 500$$$).</p><p>Сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$500$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — минимальное количество операций, которые необходимо выполнить, чтобы сделать $$$a$$$ отсортированной, или $$$-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
2 3 5 4
5 6
1 1 3 4 4
1 10
2
2 10
11 9
2 10
12 11
5 18
81 324 218 413 324
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
0
0
-1
1
3
</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:17: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:'8124b4ebceb89da8',t:'MTY5NjY2NjYzNi4yNTAwMDA='};_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", "*1600"] | ||
1455E | 1455 | 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_1$$$, $$$p_2$$$, $$$p_3$$$ и $$$p_4$$$ на коодинатной плоскости $$$\mathit{XY}$$$.</p><p>За один шаг вы можете выбрать одну из точек $$$p_i$$$ и сдвинуть ее в одном из четырех направлений на единицу. Другими словами, если вы выбрали точку $$$p_i = (x, y)$$$, вы можете передвинуть ее в $$$(x, y + 1)$$$, $$$(x, y - 1)$$$, $$$(x + 1, y)$$$ или $$$(x - 1, y)$$$.</p><p>Ваша задача — сдвинуть точки таким образом, чтобы они образовали квадрат со сторонами параллельными осям $$$\mathit{OX}$$$ и $$$\mathit{OY}$$$ (квадрат со стороной $$$0$$$ разрешен).</p><p>Какое минимальное количество шагов вам нужно, чтобы получить такой квадрат?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из четырех строк. В каждой строке заданы два целых числа $$$x$$$ и $$$y$$$ ($$$0 \le x, y \le 10^9$$$) — координаты одной из точек $$$p_i = (x, y)$$$.</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
0 2
4 2
2 0
2 4
1 0
2 0
4 0
6 0
1 6
2 2
2 5
4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
7
5
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, один из оптимальных ответов изображен ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/90992a9e779e0b0a971205b52a470400036e59b8.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> Каждая точка будет сдвинута два раза, поэтому ответ $$$2 + 2 + 2 + 2 = 8$$$.<p>Во втором наборе, один из оптимальных ответов изображен ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7a5d36b8cd6dffaa7996b6cac5dc6a9079e1eab9.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> Ответ равен $$$3 + 1 + 0 + 3 = 7$$$.<p>В третьем наборе, один из оптимальных ответов изображен ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ec6bde0b0b6102980a76d97620502c9dad5b6466.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> Ответ равен $$$1 + 1 + 2 + 1 = 5$$$.</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="141ac7f48a461384d5f04ed02f7df70f"/>
<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="f7e7e2a66369bc4b78b7cc5992accc53fbe5e0d6"/>
<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='141ac7f48a461384d5f04ed02f7df70f'> </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%2F1455%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='141ac7f48a461384d5f04ed02f7df70f'/>
<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/1455">Educational Codeforces Round 99 (рейтинговый для Див. 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='141ac7f48a461384d5f04ed02f7df70f'/>
<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/1455/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="Сложность">
*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='141ac7f48a461384d5f04ed02f7df70f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="815718"/>
<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='141ac7f48a461384d5f04ed02f7df70f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="815718"/>
<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/85116" title="Educational Codeforces Round 99 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12478:12479" 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/85186" title="85186" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12501:12502" 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="//www.youtube.com/watch?v=1-S4FALm9OI" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12633" resourceName="watch"
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/1455">Задачи</a></li>
<li><a
href="/contest/1455/submit">Отослать</a></li>
<li><a
href="/contest/1455/my">Мои посылки</a></li>
<li><a
href="/contest/1455/status">Статус</a></li>
<li><a
href="/contest/1455/hacks">Взломы</a></li>
<li><a
href="/contest/1455/standings">Положение</a></li>
<li><a
href="/contest/1455/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_49fc5e94a3da6859e276ea671b1e7b4e154562f3">
<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_1$$$, $$$p_2$$$, $$$p_3$$$ и $$$p_4$$$ на коодинатной плоскости $$$\mathit{XY}$$$.</p><p>За один шаг вы можете выбрать одну из точек $$$p_i$$$ и сдвинуть ее в одном из четырех направлений на единицу. Другими словами, если вы выбрали точку $$$p_i = (x, y)$$$, вы можете передвинуть ее в $$$(x, y + 1)$$$, $$$(x, y - 1)$$$, $$$(x + 1, y)$$$ или $$$(x - 1, y)$$$.</p><p>Ваша задача — сдвинуть точки таким образом, чтобы они образовали квадрат со сторонами параллельными осям $$$\mathit{OX}$$$ и $$$\mathit{OY}$$$ (квадрат со стороной $$$0$$$ разрешен).</p><p>Какое минимальное количество шагов вам нужно, чтобы получить такой квадрат?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из четырех строк. В каждой строке заданы два целых числа $$$x$$$ и $$$y$$$ ($$$0 \le x, y \le 10^9$$$) — координаты одной из точек $$$p_i = (x, y)$$$.</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
0 2
4 2
2 0
2 4
1 0
2 0
4 0
6 0
1 6
2 2
2 5
4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
7
5
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, один из оптимальных ответов изображен ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/90992a9e779e0b0a971205b52a470400036e59b8.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> Каждая точка будет сдвинута два раза, поэтому ответ $$$2 + 2 + 2 + 2 = 8$$$.<p>Во втором наборе, один из оптимальных ответов изображен ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/7a5d36b8cd6dffaa7996b6cac5dc6a9079e1eab9.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> Ответ равен $$$3 + 1 + 0 + 3 = 7$$$.<p>В третьем наборе, один из оптимальных ответов изображен ниже: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ec6bde0b0b6102980a76d97620502c9dad5b6466.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> Ответ равен $$$1 + 1 + 2 + 1 = 5$$$.</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:17: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:'8124b4f459a61490',t:'MTY5NjY2NjYzNy42MjAwMDA='};_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", "\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.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041f\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\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", "\u0422\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u043f\u043e\u0442\u043e\u043a\u0438", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0442\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "*2400"] | ||
1455F | 1455 | 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$$$, состоящая из $$$n$$$ символов. Эти символы являются первыми $$$k$$$ строчными буквами латинского алфавита. Вам необходимо выполнить $$$n$$$ операций со строкой.</p><p>Во время $$$i$$$-й операции вы берете символ, который <span class="tex-font-style-bf">первоначально занимал</span> $$$i$$$-ю позицию, и выполняете с ним <span class="tex-font-style-bf">одно</span> из следующих действий:</p><ul> <li> поменять его местами с предыдущим символом в строке (если он существует). Эта операция записывается как <span class="tex-font-style-tt">L</span>; </li><li> поменять его местами со следующим символом в строке (если он существует). Эта операция записывается как <span class="tex-font-style-tt">R</span>; </li><li> циклически заменить его на предыдущий символ в алфавите (<span class="tex-font-style-tt">b</span> становится <span class="tex-font-style-tt">a</span>, <span class="tex-font-style-tt">c</span> становится <span class="tex-font-style-tt">b</span> и т. д.; <span class="tex-font-style-tt">a</span> становится $$$k$$$-й буквой латинского алфавита). Эта операция записывается как <span class="tex-font-style-tt">D</span>; </li><li> циклически заменить его на следующий символ в алфавите (<span class="tex-font-style-tt">a</span> становится <span class="tex-font-style-tt">b</span>, <span class="tex-font-style-tt">b</span> становится <span class="tex-font-style-tt">c</span> и т. д.; $$$k$$$-я буква латинского алфавита становится <span class="tex-font-style-tt">a</span>). Эта операция записывается как <span class="tex-font-style-tt">U</span>; </li><li> ничего не делать. Эта операция записывается как <span class="tex-font-style-tt">0</span>. </li></ul><p>Пусть начальная строка — <span class="tex-font-style-tt">test</span>, $$$k = 20$$$, а последовательность операций — <span class="tex-font-style-tt">URLD</span>. Тогда строка изменяется следующим образом:</p><ol> <li> первая операция <span class="tex-font-style-tt">U</span>, поэтому мы меняем подчеркнутую букву в <span class="tex-font-style-tt"><span class="tex-font-style-underline">t</span>est</span> на следующую из первых $$$20$$$ латинских букв, т. е. на <span class="tex-font-style-tt">a</span>. Теперь строка равна <span class="tex-font-style-tt">aest</span>; </li><li> вторая операция <span class="tex-font-style-tt">R</span>, поэтому мы меняем местами подчеркнутую букву со следующей в строке <span class="tex-font-style-tt">a<span class="tex-font-style-underline">e</span>st</span>. Теперь строка равна <span class="tex-font-style-tt">aset</span>; </li><li> третья операция <span class="tex-font-style-tt">L</span>, поэтому мы меняем местами подчеркнутую букву с предыдущей в строке <span class="tex-font-style-tt">a<span class="tex-font-style-underline">s</span>et</span> (обратите внимание, что теперь это $$$2$$$-й символ строки, но изначально он был $$$3$$$-м, поэтому к нему применяется $$$3$$$-я операция). Теперь строка равна <span class="tex-font-style-tt">saet</span>; </li><li> четвертая операция <span class="tex-font-style-tt">D</span>, поэтому мы меняем подчеркнутую букву в <span class="tex-font-style-tt">sae<span class="tex-font-style-underline">t</span></span> на предыдущую из первых $$$20$$$ латинских букв, т. е. на <span class="tex-font-style-tt">s</span>. Теперь строка равна <span class="tex-font-style-tt">saes</span>. </li></ol><p>Результатом выполнения последовательности операций является <span class="tex-font-style-tt">saes</span>.</p><p>Для заданной строки $$$s$$$ и значения $$$k$$$ найдите лексикографически минимальную строку, которая может быть получена после применения последовательности операций к $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из двух строк. Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 500$$$; $$$2 \le k \le 26$$$).</p><p>Вторая строка содержит строку $$$s$$$, состоящую из $$$n$$$ символов. Каждый символ — это одна из первых $$$k$$$ букв латинского алфавита (в нижнем регистре).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую лексикографически минимальную строку, которая может быть получена из $$$s$$$ с помощью одной последовательности операций.</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 2
bbab
7 5
cceddda
6 5
ecdaed
7 4
dcdbdaa
8 3
ccabbaca
5 7
eabba
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
aaaa
baccacd
aabdac
aabacad
aaaaaaaa
abadb
</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="24745f6b39292fbbd06bc2b5884f3632"/>
<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="f7e7e2a66369bc4b78b7cc5992accc53fbe5e0d6"/>
<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='24745f6b39292fbbd06bc2b5884f3632'> </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%2F1455%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='24745f6b39292fbbd06bc2b5884f3632'/>
<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/1455">Educational Codeforces Round 99 (рейтинговый для Див. 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='24745f6b39292fbbd06bc2b5884f3632'/>
<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/1455/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="Сложность">
*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='24745f6b39292fbbd06bc2b5884f3632'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="815719"/>
<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='24745f6b39292fbbd06bc2b5884f3632'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="815719"/>
<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/85116" title="Educational Codeforces Round 99 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12478:12479" 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/85186" title="85186" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12501:12502" 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="//www.youtube.com/watch?v=1-S4FALm9OI" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12633" resourceName="watch"
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/1455">Задачи</a></li>
<li><a
href="/contest/1455/submit">Отослать</a></li>
<li><a
href="/contest/1455/my">Мои посылки</a></li>
<li><a
href="/contest/1455/status">Статус</a></li>
<li><a
href="/contest/1455/hacks">Взломы</a></li>
<li><a
href="/contest/1455/standings">Положение</a></li>
<li><a
href="/contest/1455/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_7eab3d3f9db8170e9e903655e397ee50729ea4a3">
<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$$$, состоящая из $$$n$$$ символов. Эти символы являются первыми $$$k$$$ строчными буквами латинского алфавита. Вам необходимо выполнить $$$n$$$ операций со строкой.</p><p>Во время $$$i$$$-й операции вы берете символ, который <span class="tex-font-style-bf">первоначально занимал</span> $$$i$$$-ю позицию, и выполняете с ним <span class="tex-font-style-bf">одно</span> из следующих действий:</p><ul> <li> поменять его местами с предыдущим символом в строке (если он существует). Эта операция записывается как <span class="tex-font-style-tt">L</span>; </li><li> поменять его местами со следующим символом в строке (если он существует). Эта операция записывается как <span class="tex-font-style-tt">R</span>; </li><li> циклически заменить его на предыдущий символ в алфавите (<span class="tex-font-style-tt">b</span> становится <span class="tex-font-style-tt">a</span>, <span class="tex-font-style-tt">c</span> становится <span class="tex-font-style-tt">b</span> и т. д.; <span class="tex-font-style-tt">a</span> становится $$$k$$$-й буквой латинского алфавита). Эта операция записывается как <span class="tex-font-style-tt">D</span>; </li><li> циклически заменить его на следующий символ в алфавите (<span class="tex-font-style-tt">a</span> становится <span class="tex-font-style-tt">b</span>, <span class="tex-font-style-tt">b</span> становится <span class="tex-font-style-tt">c</span> и т. д.; $$$k$$$-я буква латинского алфавита становится <span class="tex-font-style-tt">a</span>). Эта операция записывается как <span class="tex-font-style-tt">U</span>; </li><li> ничего не делать. Эта операция записывается как <span class="tex-font-style-tt">0</span>. </li></ul><p>Пусть начальная строка — <span class="tex-font-style-tt">test</span>, $$$k = 20$$$, а последовательность операций — <span class="tex-font-style-tt">URLD</span>. Тогда строка изменяется следующим образом:</p><ol> <li> первая операция <span class="tex-font-style-tt">U</span>, поэтому мы меняем подчеркнутую букву в <span class="tex-font-style-tt"><span class="tex-font-style-underline">t</span>est</span> на следующую из первых $$$20$$$ латинских букв, т. е. на <span class="tex-font-style-tt">a</span>. Теперь строка равна <span class="tex-font-style-tt">aest</span>; </li><li> вторая операция <span class="tex-font-style-tt">R</span>, поэтому мы меняем местами подчеркнутую букву со следующей в строке <span class="tex-font-style-tt">a<span class="tex-font-style-underline">e</span>st</span>. Теперь строка равна <span class="tex-font-style-tt">aset</span>; </li><li> третья операция <span class="tex-font-style-tt">L</span>, поэтому мы меняем местами подчеркнутую букву с предыдущей в строке <span class="tex-font-style-tt">a<span class="tex-font-style-underline">s</span>et</span> (обратите внимание, что теперь это $$$2$$$-й символ строки, но изначально он был $$$3$$$-м, поэтому к нему применяется $$$3$$$-я операция). Теперь строка равна <span class="tex-font-style-tt">saet</span>; </li><li> четвертая операция <span class="tex-font-style-tt">D</span>, поэтому мы меняем подчеркнутую букву в <span class="tex-font-style-tt">sae<span class="tex-font-style-underline">t</span></span> на предыдущую из первых $$$20$$$ латинских букв, т. е. на <span class="tex-font-style-tt">s</span>. Теперь строка равна <span class="tex-font-style-tt">saes</span>. </li></ol><p>Результатом выполнения последовательности операций является <span class="tex-font-style-tt">saes</span>.</p><p>Для заданной строки $$$s$$$ и значения $$$k$$$ найдите лексикографически минимальную строку, которая может быть получена после применения последовательности операций к $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор состоит из двух строк. Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 500$$$; $$$2 \le k \le 26$$$).</p><p>Вторая строка содержит строку $$$s$$$, состоящую из $$$n$$$ символов. Каждый символ — это одна из первых $$$k$$$ букв латинского алфавита (в нижнем регистре).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одну строку, содержащую лексикографически минимальную строку, которая может быть получена из $$$s$$$ с помощью одной последовательности операций.</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 2
bbab
7 5
cceddda
6 5
ecdaed
7 4
dcdbdaa
8 3
ccabbaca
5 7
eabba
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
aaaa
baccacd
aabdac
aabacad
aaaaaaaa
abadb
</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:17: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:'8124b4fccb004975',t:'MTY5NjY2NjYzOC45NDcwMDA='};_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", "*2800"] | ||
1455G | 1455 | 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>Поликарп редактирует очень сложную программу. Сначала определяется переменная $$$x$$$, ей присваивается значение $$$0$$$. Затем следуют инструкции двух типов: </p><ol> <li> <span class="tex-font-style-tt">set $$$y$$$ $$$v$$$</span> — присвоить переменной $$$x$$$ значение $$$y$$$ или потратить $$$v$$$ бурлей, чтобы удалить эту инструкцию (и, соответственно, не изменять $$$x$$$); </li><li> блок <span class="tex-font-style-tt">if $$$y$$$ $$$\dots$$$ end</span> — выполнить инструкции внутри блока <span class="tex-font-style-tt">if</span>, если значение $$$x$$$ равно $$$y$$$, и пропустить блок иначе. </li></ol><p>Внутри блоков <span class="tex-font-style-tt">if</span> могут содержаться <span class="tex-font-style-tt">set</span> инструкции и другие блоки <span class="tex-font-style-tt">if</span>.</p><p>Однако, когда значение $$$x$$$ становится равно $$$s$$$, компьютер ломается и тут же возгорается. Поликарп не хочет этого допустить, и в то же время потратить как можно меньше бурлей.</p><p>Какую минимальную сумму бурлей можно потратить на удаление <span class="tex-font-style-tt">set</span> инструкций, чтобы никогда не присвоить $$$x$$$ значение $$$s$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целы числа $$$n$$$ и $$$s$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le s \le 2 \cdot 10^5$$$) — количество строк в программе и запрещенное значение $$$x$$$.</p><p>Следующие $$$n$$$ строк задают программу. Каждая строка одного из трех типов: </p><ol> <li> <span class="tex-font-style-tt">set $$$y$$$ $$$v$$$</span> $$$(0 \le y \le 2 \cdot 10^5, 1 \le v \le 10^9)$$$; </li><li> <span class="tex-font-style-tt">if $$$y$$$</span> $$$(0 \le y \le 2 \cdot 10^5)$$$; </li><li> <span class="tex-font-style-tt">end</span>. </li></ol><p>Каждая <span class="tex-font-style-tt">if</span> инструкция имеет парную <span class="tex-font-style-tt">end</span> инструкцию. Каждая <span class="tex-font-style-tt">end</span> инструкция имеет парную <span class="tex-font-style-tt">if</span> инструкцию.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальную сумму бурлей, которую Поликарп может потратить на удаление <span class="tex-font-style-tt">set</span> инструкций, чтобы никогда не присвоить $$$x$$$ значение $$$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 1
set 1 10
set 2 15
if 2
set 1 7
end
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
17
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 2
set 3 4
if 3
set 10 4
set 2 7
set 10 1
end
set 4 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
9 200
if 0
set 5 5
if 5
set 100 13
end
if 100
set 200 1
end
end
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 10
set 1 15
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</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="e81f36d14ad13c1d2ca157d4ada9b443"/>
<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="f7e7e2a66369bc4b78b7cc5992accc53fbe5e0d6"/>
<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='e81f36d14ad13c1d2ca157d4ada9b443'> </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%2F1455%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='e81f36d14ad13c1d2ca157d4ada9b443'/>
<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/1455">Educational Codeforces Round 99 (рейтинговый для Див. 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='e81f36d14ad13c1d2ca157d4ada9b443'/>
<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/1455/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="Сложность">
*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='e81f36d14ad13c1d2ca157d4ada9b443'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="815720"/>
<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='e81f36d14ad13c1d2ca157d4ada9b443'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="815720"/>
<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/85116" title="Educational Codeforces Round 99 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12478:12479" 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/85186" title="85186" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12501:12502" 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="//www.youtube.com/watch?v=1-S4FALm9OI" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12633" resourceName="watch"
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/1455">Задачи</a></li>
<li><a
href="/contest/1455/submit">Отослать</a></li>
<li><a
href="/contest/1455/my">Мои посылки</a></li>
<li><a
href="/contest/1455/status">Статус</a></li>
<li><a
href="/contest/1455/hacks">Взломы</a></li>
<li><a
href="/contest/1455/standings">Положение</a></li>
<li><a
href="/contest/1455/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_b859f8e532ea6a3f305900f10491338e0577b533">
<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>Поликарп редактирует очень сложную программу. Сначала определяется переменная $$$x$$$, ей присваивается значение $$$0$$$. Затем следуют инструкции двух типов: </p><ol> <li> <span class="tex-font-style-tt">set $$$y$$$ $$$v$$$</span> — присвоить переменной $$$x$$$ значение $$$y$$$ или потратить $$$v$$$ бурлей, чтобы удалить эту инструкцию (и, соответственно, не изменять $$$x$$$); </li><li> блок <span class="tex-font-style-tt">if $$$y$$$ $$$\dots$$$ end</span> — выполнить инструкции внутри блока <span class="tex-font-style-tt">if</span>, если значение $$$x$$$ равно $$$y$$$, и пропустить блок иначе. </li></ol><p>Внутри блоков <span class="tex-font-style-tt">if</span> могут содержаться <span class="tex-font-style-tt">set</span> инструкции и другие блоки <span class="tex-font-style-tt">if</span>.</p><p>Однако, когда значение $$$x$$$ становится равно $$$s$$$, компьютер ломается и тут же возгорается. Поликарп не хочет этого допустить, и в то же время потратить как можно меньше бурлей.</p><p>Какую минимальную сумму бурлей можно потратить на удаление <span class="tex-font-style-tt">set</span> инструкций, чтобы никогда не присвоить $$$x$$$ значение $$$s$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целы числа $$$n$$$ и $$$s$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le s \le 2 \cdot 10^5$$$) — количество строк в программе и запрещенное значение $$$x$$$.</p><p>Следующие $$$n$$$ строк задают программу. Каждая строка одного из трех типов: </p><ol> <li> <span class="tex-font-style-tt">set $$$y$$$ $$$v$$$</span> $$$(0 \le y \le 2 \cdot 10^5, 1 \le v \le 10^9)$$$; </li><li> <span class="tex-font-style-tt">if $$$y$$$</span> $$$(0 \le y \le 2 \cdot 10^5)$$$; </li><li> <span class="tex-font-style-tt">end</span>. </li></ol><p>Каждая <span class="tex-font-style-tt">if</span> инструкция имеет парную <span class="tex-font-style-tt">end</span> инструкцию. Каждая <span class="tex-font-style-tt">end</span> инструкция имеет парную <span class="tex-font-style-tt">if</span> инструкцию.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальную сумму бурлей, которую Поликарп может потратить на удаление <span class="tex-font-style-tt">set</span> инструкций, чтобы никогда не присвоить $$$x$$$ значение $$$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 1
set 1 10
set 2 15
if 2
set 1 7
end
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
17
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 2
set 3 4
if 3
set 10 4
set 2 7
set 10 1
end
set 4 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
9 200
if 0
set 5 5
if 5
set 100 13
end
if 100
set 200 1
end
end
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 10
set 1 15
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</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:17: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:'8124b50539f89d9e',t:'MTY5NjY2NjY0MC4yOTEwMDA='};_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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2900"] | ||
1456A | 1456 | 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>Вы создаете уровень для некоторой мобильной игры. Уровень состоит из нескольких клеточек, выстроенных в ряд слева направо и пронумерованных последовательными натуральными числами, начиная с $$$1$$$. Каждую клеточку вы можете оставить пустой или расположить там платформу.</p><p>Чтобы пройти уровень, игрок должен бросить мяч слева так, чтобы он сначала упал на платформу в некоторой клеточке $$$p$$$, отскочил от нее, затем отскочил от платформы в клеточке $$$(p + k)$$$, затем от платформы в клеточке $$$(p + 2k)$$$, и так далее от платформы в каждой $$$k$$$-й клеточке до тех пор, пока он не перепрыгнет правее последней клеточки. Если хотя бы одна из этих клеточек не содержит платформы, то уровень с такими значениями $$$p$$$ и $$$k$$$ пройти нельзя.</p><p>У вас уже есть некоторый шаблон уровня, описываемый числами $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, где $$$a_i = 0$$$ означает, что в клеточке $$$i$$$ нет платформы, а $$$a_i = 1$$$ означает, что платформа там есть. Вы хотите модифицировать этот шаблон так, чтобы уровень можно было пройти с заданными $$$p$$$ и $$$k$$$. За $$$x$$$ секунд вы можете добавить платформу в любую пустую клеточку. За $$$y$$$ секунд вы можете полностью убрать первую клеточку, при этом количество клеточек уменьшится на один, а оставшиеся клетки пронумеруются заново, сохраняя порядок. Других изменений вы вносить не можете. Вы <span class="tex-font-style-bf">не можете</span> уменьшить число клеток до меньше $$$p$$$.</p><center> <img class="tex-graphics" height="113px" src="https://espresso.codeforces.com/42f170cf3916d6fb4af8c8ee411ed217f8e79ba7.png" style="max-width: 100.0%;max-height: 100.0%;" width="454px"/> <span class="tex-font-size-small">Иллюстрация к третьему тестовому случаю. Крестами отмечены удаленные клеточки. Синим показана добавленная платформа.</span> </center><p>Какое минимальное количество секунд вам требуется, чтобы сделать возможным прохождение уровня с заданными значениями $$$p$$$ и $$$k$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит количество тестовых случаев $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют описания тестовых случаев.</p><p>Первая строка каждого тестового случая содержит три целых числа $$$n$$$, $$$p$$$ и $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — начальное количество клеточек, номер первой клеточки, которая должна содержать платформу, и требуемый период прыжков мяча.</p><p>Вторая строка каждого тестового случая содержит строку $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ или $$$a_i = 1$$$) — начальный шаблон уровня, записанный <span class="tex-font-style-bf">без пробелов</span>.</p><p>Последняя строка каждого тестового случая содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — время, необходимое для добавления платформы и время, необходимое для удаления первой клеточки, соответственно.</p><p>Сумма $$$n$$$ по всем тестовым случаям не превосходит $$$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>
3
10 3 2
0101010101
2 2
5 4 1
00000
2 10
11 2 3
10110011000
4 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
4
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае лучше всего просто убрать первую клеточку, после чего все необходимые платформы будут на своих местах: <span class="tex-font-style-tt"><span class="tex-font-style-striked">0</span>10<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span></span>. Зачеркнутая цифра удалена, цифры, выделенные жирным — места, где должны быть платформы. Необходимое время равно $$$y = 2$$$.</p><p>Во втором тестовом случае лучше всего добавить платформы в клетки $$$4$$$ и $$$5$$$: <span class="tex-font-style-tt">000<span class="tex-font-style-bf">00</span></span> $$$\to$$$ <span class="tex-font-style-tt">000<span class="tex-font-style-bf">11</span></span>. Необходимое время равно $$$x \cdot 2 = 4$$$.</p><p>В третьем тестовом случае лучше всего удалить первую клеточку дважды и затем добавить платформу в клеточку, которая изначально была $$$10$$$-й: <span class="tex-font-style-tt"><span class="tex-font-style-striked">10</span>1<span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">1</span>10<span class="tex-font-style-bf">0</span>0</span> $$$\to$$$ <span class="tex-font-style-tt"><span class="tex-font-style-striked">10</span>1<span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">1</span>10<span class="tex-font-style-bf">1</span>0</span>. Необходимое время равно $$$y \cdot 2 + x = 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="8d97bea32f9ae566a9cc200b92b3db20"/>
<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="f9cf91e4a82d02a82249de4c5fe377edfb1db011"/>
<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='8d97bea32f9ae566a9cc200b92b3db20'> </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%2F1456%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='8d97bea32f9ae566a9cc200b92b3db20'/>
<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/1456">Codeforces Round 687 (Div. 1, основан на Отборочном раунде 2 Технокубка 2021)</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='8d97bea32f9ae566a9cc200b92b3db20'/>
<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/1456/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='8d97bea32f9ae566a9cc200b92b3db20'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814136"/>
<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='8d97bea32f9ae566a9cc200b92b3db20'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814136"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12468:12469" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12482:12483" 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/1456">Задачи</a></li>
<li><a
href="/contest/1456/submit">Отослать</a></li>
<li><a
href="/contest/1456/my">Мои посылки</a></li>
<li><a
href="/contest/1456/status">Статус</a></li>
<li><a
href="/contest/1456/hacks">Взломы</a></li>
<li><a
href="/contest/1456/room/1">Комната</a></li>
<li><a
href="/contest/1456/standings">Положение</a></li>
<li><a
href="/contest/1456/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_09f4a664ff0735ddfc6e087f48fb0c2b886736fb">
<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>Вы создаете уровень для некоторой мобильной игры. Уровень состоит из нескольких клеточек, выстроенных в ряд слева направо и пронумерованных последовательными натуральными числами, начиная с $$$1$$$. Каждую клеточку вы можете оставить пустой или расположить там платформу.</p><p>Чтобы пройти уровень, игрок должен бросить мяч слева так, чтобы он сначала упал на платформу в некоторой клеточке $$$p$$$, отскочил от нее, затем отскочил от платформы в клеточке $$$(p + k)$$$, затем от платформы в клеточке $$$(p + 2k)$$$, и так далее от платформы в каждой $$$k$$$-й клеточке до тех пор, пока он не перепрыгнет правее последней клеточки. Если хотя бы одна из этих клеточек не содержит платформы, то уровень с такими значениями $$$p$$$ и $$$k$$$ пройти нельзя.</p><p>У вас уже есть некоторый шаблон уровня, описываемый числами $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, где $$$a_i = 0$$$ означает, что в клеточке $$$i$$$ нет платформы, а $$$a_i = 1$$$ означает, что платформа там есть. Вы хотите модифицировать этот шаблон так, чтобы уровень можно было пройти с заданными $$$p$$$ и $$$k$$$. За $$$x$$$ секунд вы можете добавить платформу в любую пустую клеточку. За $$$y$$$ секунд вы можете полностью убрать первую клеточку, при этом количество клеточек уменьшится на один, а оставшиеся клетки пронумеруются заново, сохраняя порядок. Других изменений вы вносить не можете. Вы <span class="tex-font-style-bf">не можете</span> уменьшить число клеток до меньше $$$p$$$.</p><center> <img class="tex-graphics" height="113px" src="https://espresso.codeforces.com/42f170cf3916d6fb4af8c8ee411ed217f8e79ba7.png" style="max-width: 100.0%;max-height: 100.0%;" width="454px" /> <span class="tex-font-size-small">Иллюстрация к третьему тестовому случаю. Крестами отмечены удаленные клеточки. Синим показана добавленная платформа.</span> </center><p>Какое минимальное количество секунд вам требуется, чтобы сделать возможным прохождение уровня с заданными значениями $$$p$$$ и $$$k$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит количество тестовых случаев $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют описания тестовых случаев.</p><p>Первая строка каждого тестового случая содержит три целых числа $$$n$$$, $$$p$$$ и $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — начальное количество клеточек, номер первой клеточки, которая должна содержать платформу, и требуемый период прыжков мяча.</p><p>Вторая строка каждого тестового случая содержит строку $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ или $$$a_i = 1$$$) — начальный шаблон уровня, записанный <span class="tex-font-style-bf">без пробелов</span>.</p><p>Последняя строка каждого тестового случая содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — время, необходимое для добавления платформы и время, необходимое для удаления первой клеточки, соответственно.</p><p>Сумма $$$n$$$ по всем тестовым случаям не превосходит $$$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>
3
10 3 2
0101010101
2 2
5 4 1
00000
2 10
11 2 3
10110011000
4 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
4
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае лучше всего просто убрать первую клеточку, после чего все необходимые платформы будут на своих местах: <span class="tex-font-style-tt"><span class="tex-font-style-striked">0</span>10<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span></span>. Зачеркнутая цифра удалена, цифры, выделенные жирным — места, где должны быть платформы. Необходимое время равно $$$y = 2$$$.</p><p>Во втором тестовом случае лучше всего добавить платформы в клетки $$$4$$$ и $$$5$$$: <span class="tex-font-style-tt">000<span class="tex-font-style-bf">00</span></span> $$$\to$$$ <span class="tex-font-style-tt">000<span class="tex-font-style-bf">11</span></span>. Необходимое время равно $$$x \cdot 2 = 4$$$.</p><p>В третьем тестовом случае лучше всего удалить первую клеточку дважды и затем добавить платформу в клеточку, которая изначально была $$$10$$$-й: <span class="tex-font-style-tt"><span class="tex-font-style-striked">10</span>1<span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">1</span>10<span class="tex-font-style-bf">0</span>0</span> $$$\to$$$ <span class="tex-font-style-tt"><span class="tex-font-style-striked">10</span>1<span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">1</span>10<span class="tex-font-style-bf">1</span>0</span>. Необходимое время равно $$$y \cdot 2 + x = 10$$$.</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:17: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:'8124b50d98969d75',t:'MTY5NjY2NjY0MS43NzgwMDA='};_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", "\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1400"] | ||
1456B | 1456 | B | ru | B. XOR-пушка | <div class="problem-statement"><div class="header"><div class="title">B. XOR-пушка</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> массив натуральных чисел $$$a_1, a_2, \ldots, a_n$$$. Вы завидуете ему и хотите уничтожить это свойство. У вас есть так называемая <span class="tex-font-style-it">XOR-пушка</span>, которую вы можете использовать один или несколько раз.</p><p>За один шаг вы можете выбрать два <span class="tex-font-style-bf">последовательных</span> элемента в массиве, обозначим их за $$$x$$$ и $$$y$$$, удалить их из массива и на их место вставить число $$$x \oplus y$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>. Обратите внимание, что длина массива уменьшается на один в результате этой операции. Вы не можете выполнить эту операцию, если длина массива стала единицей.</p><p>Например, если массив равен $$$[2, 5, 6, 8]$$$, то вы можете выбрать $$$5$$$ и $$$6$$$ и заменить их на $$$5 \oplus 6 = 3$$$. Массив становится равен $$$[2, 3, 8]$$$.</p><p>Вы хотите, чтобы массив перестал быть неубывающим. Какое минимальное количество шагов вам для этого потребуется? Если массив остается неубывающим независимо от того, какие операции вы делаете, выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — начальную длину массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — элементы массива. Гарантируется, что $$$a_i \le a_{i + 1}$$$ для всех $$$1 \le i < n$$$.</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>
4
2 5 6 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
1 2 4 6 20
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно выбрать $$$2$$$ и $$$5$$$, и массив станет равным $$$[7, 6, 8]$$$.</p><p>Во втором примере можно получить только массивы $$$[1, 1]$$$, $$$[3, 3]$$$ и $$$[0]$$$, которые все являются неубывающими.</p><p>В третьем примере можно выбрать $$$1$$$ и $$$2$$$ и массив станет равным $$$[3, 4, 6, 20]$$$. Затем вы можете, например, выбрать $$$3$$$ и $$$4$$$ и массив станет равным $$$[7, 6, 20]$$$. Этот массив не является неубывающим.</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="c6567e1bf3dab5aa3a3c82dd32c0bbe4"/>
<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="f9cf91e4a82d02a82249de4c5fe377edfb1db011"/>
<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='c6567e1bf3dab5aa3a3c82dd32c0bbe4'> </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%2F1456%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='c6567e1bf3dab5aa3a3c82dd32c0bbe4'/>
<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/1456">Codeforces Round 687 (Div. 1, основан на Отборочном раунде 2 Технокубка 2021)</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='c6567e1bf3dab5aa3a3c82dd32c0bbe4'/>
<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/1456/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='c6567e1bf3dab5aa3a3c82dd32c0bbe4'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814137"/>
<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='c6567e1bf3dab5aa3a3c82dd32c0bbe4'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814137"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12468:12469" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12482:12483" 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/1456">Задачи</a></li>
<li><a
href="/contest/1456/submit">Отослать</a></li>
<li><a
href="/contest/1456/my">Мои посылки</a></li>
<li><a
href="/contest/1456/status">Статус</a></li>
<li><a
href="/contest/1456/hacks">Взломы</a></li>
<li><a
href="/contest/1456/room/1">Комната</a></li>
<li><a
href="/contest/1456/standings">Положение</a></li>
<li><a
href="/contest/1456/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_2082d06e1fcd8f0e1e39b09de08aafde11105653">
<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. XOR-пушка</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> массив натуральных чисел $$$a_1, a_2, \ldots, a_n$$$. Вы завидуете ему и хотите уничтожить это свойство. У вас есть так называемая <span class="tex-font-style-it">XOR-пушка</span>, которую вы можете использовать один или несколько раз.</p><p>За один шаг вы можете выбрать два <span class="tex-font-style-bf">последовательных</span> элемента в массиве, обозначим их за $$$x$$$ и $$$y$$$, удалить их из массива и на их место вставить число $$$x \oplus y$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>. Обратите внимание, что длина массива уменьшается на один в результате этой операции. Вы не можете выполнить эту операцию, если длина массива стала единицей.</p><p>Например, если массив равен $$$[2, 5, 6, 8]$$$, то вы можете выбрать $$$5$$$ и $$$6$$$ и заменить их на $$$5 \oplus 6 = 3$$$. Массив становится равен $$$[2, 3, 8]$$$.</p><p>Вы хотите, чтобы массив перестал быть неубывающим. Какое минимальное количество шагов вам для этого потребуется? Если массив остается неубывающим независимо от того, какие операции вы делаете, выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — начальную длину массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — элементы массива. Гарантируется, что $$$a_i \le a_{i + 1}$$$ для всех $$$1 \le i < n$$$.</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>
4
2 5 6 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
1 2 4 6 20
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно выбрать $$$2$$$ и $$$5$$$, и массив станет равным $$$[7, 6, 8]$$$.</p><p>Во втором примере можно получить только массивы $$$[1, 1]$$$, $$$[3, 3]$$$ и $$$[0]$$$, которые все являются неубывающими.</p><p>В третьем примере можно выбрать $$$1$$$ и $$$2$$$ и массив станет равным $$$[3, 4, 6, 20]$$$. Затем вы можете, например, выбрать $$$3$$$ и $$$4$$$ и массив станет равным $$$[7, 6, 20]$$$. Этот массив не является неубывающим.</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:17: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:'8124b516ca5616a7',t:'MTY5NjY2NjY0My4xMjcwMDA='};_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", "\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\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2000"] | ||
1456C | 1456 | 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$$$ боссов, пронумерованных от $$$1$$$ до $$$n$$$. Боссов можно побеждать в любом порядке. Каждого босса нужно победить <span class="tex-font-style-bf">ровно один</span> раз. Также в игре присутствует параметр, называемый комбо-бонусом, изначально равный $$$0$$$.</p><p>Когда игрок побеждает $$$i$$$-го босса, ко счету игрока добавляется текущее значение комбо-бонуса, а затем значение комбо-бонуса изменяется на величину $$$c_i$$$. Обратите внимание, что величина $$$c_i$$$ может быть отрицательной, что означает, что дальнейшие боссы будут давать меньше очков.</p><p>Кролик нашел в игре лазейку. В любой момент времени он может сбросить прохождение игры и начать новое. Это сбросит текущее значение комбо-бонуса в $$$0$$$, но все побежденные боссы останутся побежденными. Кроме того, текущий счет тоже сохраняется и <span class="tex-font-style-bf">не</span> сбрасывается в ноль после этой операции. Эта лазейка может быть использована <span class="tex-font-style-bf">не более</span> $$$k$$$ раз. Можно сбрасывать игру после победы над любым количеством боссов, в том числе перед или после всех, также можно сбрасывать игру несколько раз подряд, не побеждая ни одного босса между сбросами.</p><p>Помогите кролику определить максимально возможный счет, который он может получить, победив <span class="tex-font-style-bf">всех</span> $$$n$$$ боссов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержатся два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$0 \leq k \leq 5 \cdot 10^5$$$) — количество боссов и максимальное количество сбросов соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$c_1,c_2,\ldots,c_n$$$ ($$$-10^6 \leq c_i \leq 10^6$$$) — влияние на комбо-бонус каждого из $$$n$$$ боссов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><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 0
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1
-1 -2 -3 -4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
11
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
13 2
3 1 4 1 5 -9 -2 -6 -5 -3 -5 -8 -9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
71
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте запрещено делать сбросы. Оптимальное решение будет таким. </p><ul> <li> Победить первого босса $$$(+0)$$$. Комбо-бонус становится равным $$$1$$$. </li><li> Победить второго босса $$$(+1)$$$. Комбо-бонус становится равным $$$2$$$. </li><li> Победить третьего босса $$$(+2)$$$. Комбо-бонус становится равным $$$3$$$. </li></ul> <p>Поэтому ответ в первом примере равен $$$0+1+2=3$$$.</p><p>Во втором примере можно показать, что оптимальное решение будет таким: </p><ul> <li> Победить пятого босса $$$(+0)$$$. Комбо-бонус становится равным $$$5$$$. </li><li> Победить первого босса $$$(+5)$$$. Комбо-бонус становится равным $$$4$$$. </li><li> Победить второго босса $$$(+4)$$$. Комбо-бонус становится равным $$$2$$$. </li><li> Победить третьего босса $$$(+2)$$$. Комбо-бонус становится равным $$$-1$$$. </li><li> Сбросить. Комбо-бонус становится равным $$$0$$$. </li><li> Победить четвертого босса $$$(+0)$$$. Комбо-бонус становится равным $$$-4$$$. </li></ul> <p>Поэтому ответ будет равен $$$0+5+4+2+0=11$$$.</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="28f00312a9697e99cfa9bcd6f01cc356"/>
<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="f9cf91e4a82d02a82249de4c5fe377edfb1db011"/>
<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='28f00312a9697e99cfa9bcd6f01cc356'> </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%2F1456%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='28f00312a9697e99cfa9bcd6f01cc356'/>
<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/1456">Codeforces Round 687 (Div. 1, основан на Отборочном раунде 2 Технокубка 2021)</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='28f00312a9697e99cfa9bcd6f01cc356'/>
<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/1456/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='28f00312a9697e99cfa9bcd6f01cc356'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814138"/>
<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='28f00312a9697e99cfa9bcd6f01cc356'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814138"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12468:12469" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12482:12483" 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/1456">Задачи</a></li>
<li><a
href="/contest/1456/submit">Отослать</a></li>
<li><a
href="/contest/1456/my">Мои посылки</a></li>
<li><a
href="/contest/1456/status">Статус</a></li>
<li><a
href="/contest/1456/hacks">Взломы</a></li>
<li><a
href="/contest/1456/room/1">Комната</a></li>
<li><a
href="/contest/1456/standings">Положение</a></li>
<li><a
href="/contest/1456/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_1c58337b222c39570cd83bd58d28c44210953859">
<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$$$ боссов, пронумерованных от $$$1$$$ до $$$n$$$. Боссов можно побеждать в любом порядке. Каждого босса нужно победить <span class="tex-font-style-bf">ровно один</span> раз. Также в игре присутствует параметр, называемый комбо-бонусом, изначально равный $$$0$$$.</p><p>Когда игрок побеждает $$$i$$$-го босса, ко счету игрока добавляется текущее значение комбо-бонуса, а затем значение комбо-бонуса изменяется на величину $$$c_i$$$. Обратите внимание, что величина $$$c_i$$$ может быть отрицательной, что означает, что дальнейшие боссы будут давать меньше очков.</p><p>Кролик нашел в игре лазейку. В любой момент времени он может сбросить прохождение игры и начать новое. Это сбросит текущее значение комбо-бонуса в $$$0$$$, но все побежденные боссы останутся побежденными. Кроме того, текущий счет тоже сохраняется и <span class="tex-font-style-bf">не</span> сбрасывается в ноль после этой операции. Эта лазейка может быть использована <span class="tex-font-style-bf">не более</span> $$$k$$$ раз. Можно сбрасывать игру после победы над любым количеством боссов, в том числе перед или после всех, также можно сбрасывать игру несколько раз подряд, не побеждая ни одного босса между сбросами.</p><p>Помогите кролику определить максимально возможный счет, который он может получить, победив <span class="tex-font-style-bf">всех</span> $$$n$$$ боссов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержатся два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$0 \leq k \leq 5 \cdot 10^5$$$) — количество боссов и максимальное количество сбросов соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$c_1,c_2,\ldots,c_n$$$ ($$$-10^6 \leq c_i \leq 10^6$$$) — влияние на комбо-бонус каждого из $$$n$$$ боссов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><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 0
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1
-1 -2 -3 -4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
11
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
13 2
3 1 4 1 5 -9 -2 -6 -5 -3 -5 -8 -9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
71
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте запрещено делать сбросы. Оптимальное решение будет таким. </p><ul> <li> Победить первого босса $$$(+0)$$$. Комбо-бонус становится равным $$$1$$$. </li><li> Победить второго босса $$$(+1)$$$. Комбо-бонус становится равным $$$2$$$. </li><li> Победить третьего босса $$$(+2)$$$. Комбо-бонус становится равным $$$3$$$. </li></ul> <p>Поэтому ответ в первом примере равен $$$0+1+2=3$$$.</p><p>Во втором примере можно показать, что оптимальное решение будет таким: </p><ul> <li> Победить пятого босса $$$(+0)$$$. Комбо-бонус становится равным $$$5$$$. </li><li> Победить первого босса $$$(+5)$$$. Комбо-бонус становится равным $$$4$$$. </li><li> Победить второго босса $$$(+4)$$$. Комбо-бонус становится равным $$$2$$$. </li><li> Победить третьего босса $$$(+2)$$$. Комбо-бонус становится равным $$$-1$$$. </li><li> Сбросить. Комбо-бонус становится равным $$$0$$$. </li><li> Победить четвертого босса $$$(+0)$$$. Комбо-бонус становится равным $$$-4$$$. </li></ul> <p>Поэтому ответ будет равен $$$0+5+4+2+0=11$$$.</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:17: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:'8124b51f38a6164e',t:'MTY5NjY2NjY0NC40NjUwMDA='};_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\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"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\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", "*2200"] | ||
1456D | 1456 | D | ru | D. Тортики для клонов | <div class="problem-statement"><div class="header"><div class="title">D. Тортики для клонов</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>Вы живете на числовой прямой и изначально (в момент времени $$$t = 0$$$) находитесь в точке $$$x = 0$$$. На прямой происходит $$$n$$$ событий следующего вида: в момент времени $$$t_i$$$ в координате $$$x_i$$$ появляется небольшой тортик. Чтобы получить этот тортик, нужно в этот момент времени находиться в этой координате, иначе тортик сразу портится. Никакие два тортика не появляются в одной и той же точке.</p><p>Вы можете перемещаться на $$$1$$$ единицу длины за единицу времени. Также вы обладаете возможностью мгновенно создавать своего клона в той же позиции, в которой вы сейчас находитесь. Клон не может двигаться, но он будет за вас собирать все тортики, появляющиеся в этой позиции. Клон <span class="tex-font-style-bf">исчезнет</span>, когда вы создадите нового клона. Если новый клон создается в момент времени $$$t$$$, то старый клон может собирать тортики до момента $$$t$$$ включительно, а новый — начиная с момента времени $$$t$$$ включительно.</p><p>Можете ли вы собрать все тортики (сами или с помощью клонов)?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 5000$$$) — количество тортиков.</p><p>Следующие $$$n$$$ строк содержат по два целых числа $$$t_i$$$ и $$$x_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le x_i \le 10^9$$$) — время и координату появления очередного тортика.</p><p>Все времена появления тортиков различны и даны в порядке возрастания, а все координаты появления тортиков <span class="tex-font-style-bf">различны</span>.</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>
3
2 2
5 5
6 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 0
5 5
6 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
2 1
5 5
6 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нужно с самого начала двигаться в сторону координаты $$$5$$$, оставив клона в позиции $$$1$$$ в момент времени $$$1$$$, и собрав тортик в позиции $$$2$$$ в момент времени $$$2$$$. В момент времени $$$5$$$ вы окажетесь в позиции $$$5$$$ и соберете там тортик, а клон соберет последний тортик в момент времени $$$6$$$.</p><p>Во втором примере нужно оставить клона в позиции $$$0$$$ и начать двигаться в сторону координаты $$$5$$$. В момент времени $$$1$$$ клон соберет тортик. В момент времени $$$2$$$ нужно создать нового клона в текущей позиции $$$2$$$, в будущем он соберет последний тортик. Вы сами же как раз успеете собрать второй тортик в позиции $$$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="a5b33c5ac3e4880a0c21e6baee754664"/>
<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="f9cf91e4a82d02a82249de4c5fe377edfb1db011"/>
<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='a5b33c5ac3e4880a0c21e6baee754664'> </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%2F1456%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='a5b33c5ac3e4880a0c21e6baee754664'/>
<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/1456">Codeforces Round 687 (Div. 1, основан на Отборочном раунде 2 Технокубка 2021)</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='a5b33c5ac3e4880a0c21e6baee754664'/>
<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/1456/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="Сложность">
*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='a5b33c5ac3e4880a0c21e6baee754664'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814139"/>
<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='a5b33c5ac3e4880a0c21e6baee754664'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814139"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12468:12469" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12482:12483" 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/1456">Задачи</a></li>
<li><a
href="/contest/1456/submit">Отослать</a></li>
<li><a
href="/contest/1456/my">Мои посылки</a></li>
<li><a
href="/contest/1456/status">Статус</a></li>
<li><a
href="/contest/1456/hacks">Взломы</a></li>
<li><a
href="/contest/1456/room/1">Комната</a></li>
<li><a
href="/contest/1456/standings">Положение</a></li>
<li><a
href="/contest/1456/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_936187695a1b15ed3365d7471d198b73451679dd">
<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>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>Вы живете на числовой прямой и изначально (в момент времени $$$t = 0$$$) находитесь в точке $$$x = 0$$$. На прямой происходит $$$n$$$ событий следующего вида: в момент времени $$$t_i$$$ в координате $$$x_i$$$ появляется небольшой тортик. Чтобы получить этот тортик, нужно в этот момент времени находиться в этой координате, иначе тортик сразу портится. Никакие два тортика не появляются в одной и той же точке.</p><p>Вы можете перемещаться на $$$1$$$ единицу длины за единицу времени. Также вы обладаете возможностью мгновенно создавать своего клона в той же позиции, в которой вы сейчас находитесь. Клон не может двигаться, но он будет за вас собирать все тортики, появляющиеся в этой позиции. Клон <span class="tex-font-style-bf">исчезнет</span>, когда вы создадите нового клона. Если новый клон создается в момент времени $$$t$$$, то старый клон может собирать тортики до момента $$$t$$$ включительно, а новый — начиная с момента времени $$$t$$$ включительно.</p><p>Можете ли вы собрать все тортики (сами или с помощью клонов)?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 5000$$$) — количество тортиков.</p><p>Следующие $$$n$$$ строк содержат по два целых числа $$$t_i$$$ и $$$x_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le x_i \le 10^9$$$) — время и координату появления очередного тортика.</p><p>Все времена появления тортиков различны и даны в порядке возрастания, а все координаты появления тортиков <span class="tex-font-style-bf">различны</span>.</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>
3
2 2
5 5
6 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 0
5 5
6 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
2 1
5 5
6 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нужно с самого начала двигаться в сторону координаты $$$5$$$, оставив клона в позиции $$$1$$$ в момент времени $$$1$$$, и собрав тортик в позиции $$$2$$$ в момент времени $$$2$$$. В момент времени $$$5$$$ вы окажетесь в позиции $$$5$$$ и соберете там тортик, а клон соберет последний тортик в момент времени $$$6$$$.</p><p>Во втором примере нужно оставить клона в позиции $$$0$$$ и начать двигаться в сторону координаты $$$5$$$. В момент времени $$$1$$$ клон соберет тортик. В момент времени $$$2$$$ нужно создать нового клона в текущей позиции $$$2$$$, в будущем он соберет последний тортик. Вы сами же как раз успеете собрать второй тортик в позиции $$$5$$$.</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:17:25</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:'8124b527acb01654',t:'MTY5NjY2NjY0NS44MjMwMDA='};_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", "*2900"] | ||
1456E | 1456 | E | ru | E. XOR-интервалы | <div class="problem-statement"><div class="header"><div class="title">E. XOR-интервалы</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>Даны целые числа $$$c_{0}, c_{1}, \ldots, c_{k-1}$$$. Определим цену числа $$$0 \le x < 2^{k}$$$ как $$$p(x) = \sum_{i=0}^{k-1} \left( \left\lfloor \frac{x}{2^{i}} \right\rfloor \bmod 2 \right) \cdot c_{i}$$$. Иными словами, цена числа $$$x$$$ — это сумма $$$c_{i}$$$ по тем битам $$$x$$$, которые равны 1.</p><p>Определим стоимость массива $$$a$$$ длины $$$n \ge 2$$$, состоящего из целых чисел из полуинтервала $$$[0, 2^{k})$$$ следующим образом: $$$cost(a) = \sum_{i=1}^{n - 1} p(a_{i} \oplus a_{i+1})$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>.</p><p>Вам нужно построить массив длины $$$n$$$ минимальной стоимости, в котором каждый элемент должен принадлежать определенному отрезку: $$$l_{i} \le a_{i} \le r_{i}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 50$$$, $$$1 \le k \le 50$$$) — длина массива и битовая длина рассматриваемых чисел.</p><p>В следующих $$$n$$$ строках перечислены ограничения на элементы массива: в $$$i$$$-й строке находятся целые числа $$$l_{i}$$$ и $$$r_{i}$$$ ($$$0 \le l_{i} \le r_{i} < 2^{k}$$$).</p><p>В последней строке находятся целые числа $$$c_{0}, c_{1}, \ldots, c_{k-1}$$$ ($$$0 \le c_{i} \le 10^{12}$$$).</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 3
3 3
5 5
6 6
1 1
5 2 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
30
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 3
2 2
3 4
4 6
1 10 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
102
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть только один подходящий массив — $$$[3, 5, 6, 1]$$$, — и его стоимость равна $$$cost([3, 5, 6, 1]) = p(3 \oplus 5) + p(5 \oplus 6) + p(6 \oplus 1) = p(6) + p(3) + p(7) = (c_{1} + c_{2}) + (c_{0} + c_{1}) + (c_{0} + c_{1} + c_{2}) = (2 + 7) + (5 + 2) + (5 + 2 + 7) = 30$$$.</p><p>Во втором примере единственный оптимальный массив — $$$[2, 3, 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="2f4974fb5d99cfc887e0701da1ac3700"/>
<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="f9cf91e4a82d02a82249de4c5fe377edfb1db011"/>
<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='2f4974fb5d99cfc887e0701da1ac3700'> </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%2F1456%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='2f4974fb5d99cfc887e0701da1ac3700'/>
<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/1456">Codeforces Round 687 (Div. 1, основан на Отборочном раунде 2 Технокубка 2021)</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='2f4974fb5d99cfc887e0701da1ac3700'/>
<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/1456/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="Сложность">
*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='2f4974fb5d99cfc887e0701da1ac3700'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814140"/>
<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='2f4974fb5d99cfc887e0701da1ac3700'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814140"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12468:12469" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12482:12483" 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/1456">Задачи</a></li>
<li><a
href="/contest/1456/submit">Отослать</a></li>
<li><a
href="/contest/1456/my">Мои посылки</a></li>
<li><a
href="/contest/1456/status">Статус</a></li>
<li><a
href="/contest/1456/hacks">Взломы</a></li>
<li><a
href="/contest/1456/room/1">Комната</a></li>
<li><a
href="/contest/1456/standings">Положение</a></li>
<li><a
href="/contest/1456/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_3a6152beb18829a9735ada1509291d35481df4b0">
<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. XOR-интервалы</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>Даны целые числа $$$c_{0}, c_{1}, \ldots, c_{k-1}$$$. Определим цену числа $$$0 \le x < 2^{k}$$$ как $$$p(x) = \sum_{i=0}^{k-1} \left( \left\lfloor \frac{x}{2^{i}} \right\rfloor \bmod 2 \right) \cdot c_{i}$$$. Иными словами, цена числа $$$x$$$ — это сумма $$$c_{i}$$$ по тем битам $$$x$$$, которые равны 1.</p><p>Определим стоимость массива $$$a$$$ длины $$$n \ge 2$$$, состоящего из целых чисел из полуинтервала $$$[0, 2^{k})$$$ следующим образом: $$$cost(a) = \sum_{i=1}^{n - 1} p(a_{i} \oplus a_{i+1})$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>.</p><p>Вам нужно построить массив длины $$$n$$$ минимальной стоимости, в котором каждый элемент должен принадлежать определенному отрезку: $$$l_{i} \le a_{i} \le r_{i}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 50$$$, $$$1 \le k \le 50$$$) — длина массива и битовая длина рассматриваемых чисел.</p><p>В следующих $$$n$$$ строках перечислены ограничения на элементы массива: в $$$i$$$-й строке находятся целые числа $$$l_{i}$$$ и $$$r_{i}$$$ ($$$0 \le l_{i} \le r_{i} < 2^{k}$$$).</p><p>В последней строке находятся целые числа $$$c_{0}, c_{1}, \ldots, c_{k-1}$$$ ($$$0 \le c_{i} \le 10^{12}$$$).</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 3
3 3
5 5
6 6
1 1
5 2 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
30
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 3
2 2
3 4
4 6
1 10 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
102
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере есть только один подходящий массив — $$$[3, 5, 6, 1]$$$, — и его стоимость равна $$$cost([3, 5, 6, 1]) = p(3 \oplus 5) + p(5 \oplus 6) + p(6 \oplus 1) = p(6) + p(3) + p(7) = (c_{1} + c_{2}) + (c_{0} + c_{1}) + (c_{0} + c_{1} + c_{2}) = (2 + 7) + (5 + 2) + (5 + 2 + 7) = 30$$$.</p><p>Во втором примере единственный оптимальный массив — $$$[2, 3, 6]$$$.</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:17: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:'8124b5302caa16cb',t:'MTY5NjY2NjY0Ny4xNjIwMDA='};_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", "*3500"] | ||
1457A | 1457 | 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$$$ строками и $$$m$$$ столбцами, каждая клетка которой — камера. Таким образом, всего есть $$$n \cdot m$$$ камер. В тюрьме $$$n \cdot m$$$ заключенных, по одному в каждой камере. Обозначим клетку-камеру в $$$i$$$-й строке и в $$$j$$$-м столбце как $$$(i, j)$$$.</p><p>В клетке $$$(r, c)$$$ заключенные прорыли тоннель, который можно использовать для побега! Чтобы не попасться, они будут убегать ночью.</p><p>В начале ночи каждый заключенный находится в своей клетке. Когда наступает ночь, они могут начать двигаться в соседние клетки. Формально, за одну секунду заключенный, находящийся в клетке $$$(i, j)$$$, может переместиться в любую из клеток $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ или $$$( i , j + 1 )$$$, если они находятся на территории тюрьмы. Он также может остаться в клетке $$$(i, j)$$$.</p><p>Заключенные хотят знать минимальное необходимое время для того, чтобы все они смогли собраться в клетке $$$( r , c )$$$. Обратите внимание, что в любой клетке одновременно могут находиться сколько угодно заключенных. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ $$$(1 \le t \le 10^4)$$$ — количество тестовых случаев.</p><p>Каждая из следующих $$$t$$$ строк содержит четыре целых числа $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><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
10 10 1 1
3 5 2 4
10 2 5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
18
4
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="230db09aa4f7ec6d9e22f6734c1952a0"/>
<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="7f72074b8fce01cd9ef8df2ac6803078ff266b22"/>
<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='230db09aa4f7ec6d9e22f6734c1952a0'> </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%2F1457%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='230db09aa4f7ec6d9e22f6734c1952a0'/>
<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/1457">Codeforces Round 687 (Div. 2, основан на Отборочном раунде 2 Технокубка 2021)</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='230db09aa4f7ec6d9e22f6734c1952a0'/>
<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/1457/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='230db09aa4f7ec6d9e22f6734c1952a0'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814141"/>
<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='230db09aa4f7ec6d9e22f6734c1952a0'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814141"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12470:12471" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12484:12485" 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/1457">Задачи</a></li>
<li><a
href="/contest/1457/submit">Отослать</a></li>
<li><a
href="/contest/1457/my">Мои посылки</a></li>
<li><a
href="/contest/1457/status">Статус</a></li>
<li><a
href="/contest/1457/hacks">Взломы</a></li>
<li><a
href="/contest/1457/room/1">Комната</a></li>
<li><a
href="/contest/1457/standings">Положение</a></li>
<li><a
href="/contest/1457/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_4ce05a8fe4b5308a2f20056e0dc37beca4022f7e">
<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$$$ строками и $$$m$$$ столбцами, каждая клетка которой — камера. Таким образом, всего есть $$$n \cdot m$$$ камер. В тюрьме $$$n \cdot m$$$ заключенных, по одному в каждой камере. Обозначим клетку-камеру в $$$i$$$-й строке и в $$$j$$$-м столбце как $$$(i, j)$$$.</p><p>В клетке $$$(r, c)$$$ заключенные прорыли тоннель, который можно использовать для побега! Чтобы не попасться, они будут убегать ночью.</p><p>В начале ночи каждый заключенный находится в своей клетке. Когда наступает ночь, они могут начать двигаться в соседние клетки. Формально, за одну секунду заключенный, находящийся в клетке $$$(i, j)$$$, может переместиться в любую из клеток $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ или $$$( i , j + 1 )$$$, если они находятся на территории тюрьмы. Он также может остаться в клетке $$$(i, j)$$$.</p><p>Заключенные хотят знать минимальное необходимое время для того, чтобы все они смогли собраться в клетке $$$( r , c )$$$. Обратите внимание, что в любой клетке одновременно могут находиться сколько угодно заключенных. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ $$$(1 \le t \le 10^4)$$$ — количество тестовых случаев.</p><p>Каждая из следующих $$$t$$$ строк содержит четыре целых числа $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><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
10 10 1 1
3 5 2 4
10 2 5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
18
4
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:17: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:'8124b5387b3b4979',t:'MTY5NjY2NjY0OC41MjUwMDA='};_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", "*800"] | ||
1457B | 1457 | 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$$$ домов, по порядку пронумерованных от $$$1$$$ до $$$n$$$. Дом номер $$$i$$$ изначально покрашен в цвет $$$c_i$$$. Улица называется красивой, если все дома на ней покрашены в один и тот же цвет. Маляр Том — ответственный за перекраску улицы так, чтобы она стала красивой. Скорость работы Тома определяется целым числом $$$k$$$.</p><p>За один день Том может перекрасить некоторое количество домов, выполнив два следующих шага: </p><ol> <li> Сначала он выбирает два целых числа $$$l$$$ и $$$r$$$ так, что $$$ 1 \le l \le r \le n $$$ и $$$ r - l + 1 = k $$$. </li><li> Затем для всех домов $$$i$$$ таких, что $$$l \le i \le r$$$, он может либо перекрасить этот дом в любой цвет на свой выбор, либо пропустить и не перекрашивать этот дом. </li></ol><p>Обратите внимание, что в один и тот же день Том может перекрашивать дома в разные цвета.</p><p>Том хочет знать минимальное количество дней, необходимое для того, чтобы сделать улицу красивой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$ 1 \le t \le 10^4$$$) — количество тестовых случаев. Далее следуют описания тестовых случаев.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 10^5$$$).</p><p>Вторая строка содержит $$$n$$$ целых чисел. $$$i$$$-е из этих чисел равно $$$c_i$$$ ($$$1 \le c_i \le 100$$$) — цвету, в который покрашен дом номе $$$i$$$ изначально.</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><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
10 2
1 1 2 2 1 1 2 2 2 1
7 1
1 2 3 4 5 6 7
10 3
1 3 3 3 3 1 2 1 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
6
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае Том может покрасить дома 1 и 2 в первый день в цвет 2, дома 5 и 6 во второй день в цвет 2, и последний дом в цвет 2 в третий день.</p><p>Во втором тестовом случае Том может, например, потратить 6 дней на покраску домов 1, 2, 4, 5, 6, 7 в цвет 3.</p><p>В третьем тестовом случае Том может покрасить первый дом в первый день, а дома 6, 7 и 8 во второй день в цвет 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="4bbf0d212e92b9a739ed477755ccd59f"/>
<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="7f72074b8fce01cd9ef8df2ac6803078ff266b22"/>
<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='4bbf0d212e92b9a739ed477755ccd59f'> </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%2F1457%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='4bbf0d212e92b9a739ed477755ccd59f'/>
<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/1457">Codeforces Round 687 (Div. 2, основан на Отборочном раунде 2 Технокубка 2021)</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='4bbf0d212e92b9a739ed477755ccd59f'/>
<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/1457/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='4bbf0d212e92b9a739ed477755ccd59f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814142"/>
<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='4bbf0d212e92b9a739ed477755ccd59f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814142"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12470:12471" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12484:12485" 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/1457">Задачи</a></li>
<li><a
href="/contest/1457/submit">Отослать</a></li>
<li><a
href="/contest/1457/my">Мои посылки</a></li>
<li><a
href="/contest/1457/status">Статус</a></li>
<li><a
href="/contest/1457/hacks">Взломы</a></li>
<li><a
href="/contest/1457/room/1">Комната</a></li>
<li><a
href="/contest/1457/standings">Положение</a></li>
<li><a
href="/contest/1457/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_6910b30c1368a71a499287512102b1c3d6d5f131">
<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$$$ домов, по порядку пронумерованных от $$$1$$$ до $$$n$$$. Дом номер $$$i$$$ изначально покрашен в цвет $$$c_i$$$. Улица называется красивой, если все дома на ней покрашены в один и тот же цвет. Маляр Том — ответственный за перекраску улицы так, чтобы она стала красивой. Скорость работы Тома определяется целым числом $$$k$$$.</p><p>За один день Том может перекрасить некоторое количество домов, выполнив два следующих шага: </p><ol> <li> Сначала он выбирает два целых числа $$$l$$$ и $$$r$$$ так, что $$$ 1 \le l \le r \le n $$$ и $$$ r - l + 1 = k $$$. </li><li> Затем для всех домов $$$i$$$ таких, что $$$l \le i \le r$$$, он может либо перекрасить этот дом в любой цвет на свой выбор, либо пропустить и не перекрашивать этот дом. </li></ol><p>Обратите внимание, что в один и тот же день Том может перекрашивать дома в разные цвета.</p><p>Том хочет знать минимальное количество дней, необходимое для того, чтобы сделать улицу красивой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ ($$$ 1 \le t \le 10^4$$$) — количество тестовых случаев. Далее следуют описания тестовых случаев.</p><p>Первая строка каждого тестового случая содержит одно целое число $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 10^5$$$).</p><p>Вторая строка содержит $$$n$$$ целых чисел. $$$i$$$-е из этих чисел равно $$$c_i$$$ ($$$1 \le c_i \le 100$$$) — цвету, в который покрашен дом номе $$$i$$$ изначально.</p><p>Гарантируется, что сумма $$$n$$$ по всем тестовым случаям не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><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
10 2
1 1 2 2 1 1 2 2 2 1
7 1
1 2 3 4 5 6 7
10 3
1 3 3 3 3 1 2 1 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
6
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае Том может покрасить дома 1 и 2 в первый день в цвет 2, дома 5 и 6 во второй день в цвет 2, и последний дом в цвет 2 в третий день.</p><p>Во втором тестовом случае Том может, например, потратить 6 дней на покраску домов 1, 2, 4, 5, 6, 7 в цвет 3.</p><p>В третьем тестовом случае Том может покрасить первый дом в первый день, а дома 6, 7 и 8 во второй день в цвет 3.</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:17: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:'8124b5410f004975',t:'MTY5NjY2NjY0OS44NzUwMDA='};_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\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1100"] | ||
1457C | 1457 | 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>Вы создаете уровень для некоторой мобильной игры. Уровень состоит из нескольких клеточек, выстроенных в ряд слева направо и пронумерованных последовательными натуральными числами, начиная с $$$1$$$. Каждую клеточку вы можете оставить пустой или расположить там платформу.</p><p>Чтобы пройти уровень, игрок должен бросить мяч слева так, чтобы он сначала упал на платформу в некоторой клеточке $$$p$$$, отскочил от нее, затем отскочил от платформы в клеточке $$$(p + k)$$$, затем от платформы в клеточке $$$(p + 2k)$$$, и так далее от платформы в каждой $$$k$$$-й клеточке до тех пор, пока он не перепрыгнет правее последней клеточки. Если хотя бы одна из этих клеточек не содержит платформы, то уровень с такими значениями $$$p$$$ и $$$k$$$ пройти нельзя.</p><p>У вас уже есть некоторый шаблон уровня, описываемый числами $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, где $$$a_i = 0$$$ означает, что в клеточке $$$i$$$ нет платформы, а $$$a_i = 1$$$ означает, что платформа там есть. Вы хотите модифицировать этот шаблон так, чтобы уровень можно было пройти с заданными $$$p$$$ и $$$k$$$. За $$$x$$$ секунд вы можете добавить платформу в любую пустую клеточку. За $$$y$$$ секунд вы можете полностью убрать первую клеточку, при этом количество клеточек уменьшится на один, а оставшиеся клетки пронумеруются заново, сохраняя порядок. Других изменений вы вносить не можете. Вы <span class="tex-font-style-bf">не можете</span> уменьшить число клеток до меньше $$$p$$$.</p><center> <img class="tex-graphics" height="113px" src="https://espresso.codeforces.com/42f170cf3916d6fb4af8c8ee411ed217f8e79ba7.png" style="max-width: 100.0%;max-height: 100.0%;" width="454px"/> <span class="tex-font-size-small">Иллюстрация к третьему тестовому случаю. Крестами отмечены удаленные клеточки. Синим показана добавленная платформа.</span> </center><p>Какое минимальное количество секунд вам требуется, чтобы сделать возможным прохождение уровня с заданными значениями $$$p$$$ и $$$k$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит количество тестовых случаев $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют описания тестовых случаев.</p><p>Первая строка каждого тестового случая содержит три целых числа $$$n$$$, $$$p$$$ и $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — начальное количество клеточек, номер первой клеточки, которая должна содержать платформу, и требуемый период прыжков мяча.</p><p>Вторая строка каждого тестового случая содержит строку $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ или $$$a_i = 1$$$) — начальный шаблон уровня, записанный <span class="tex-font-style-bf">без пробелов</span>.</p><p>Последняя строка каждого тестового случая содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — время, необходимое для добавления платформы и время, необходимое для удаления первой клеточки, соответственно.</p><p>Сумма $$$n$$$ по всем тестовым случаям не превосходит $$$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>
3
10 3 2
0101010101
2 2
5 4 1
00000
2 10
11 2 3
10110011000
4 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
4
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае лучше всего просто убрать первую клеточку, после чего все необходимые платформы будут на своих местах: <span class="tex-font-style-tt"><span class="tex-font-style-striked">0</span>10<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span></span>. Зачеркнутая цифра удалена, цифры, выделенные жирным — места, где должны быть платформы. Необходимое время равно $$$y = 2$$$.</p><p>Во втором тестовом случае лучше всего добавить платформы в клетки $$$4$$$ и $$$5$$$: <span class="tex-font-style-tt">000<span class="tex-font-style-bf">00</span></span> $$$\to$$$ <span class="tex-font-style-tt">000<span class="tex-font-style-bf">11</span></span>. Необходимое время равно $$$x \cdot 2 = 4$$$.</p><p>В третьем тестовом случае лучше всего удалить первую клеточку дважды и затем добавить платформу в клеточку, которая изначально была $$$10$$$-й: <span class="tex-font-style-tt"><span class="tex-font-style-striked">10</span>1<span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">1</span>10<span class="tex-font-style-bf">0</span>0</span> $$$\to$$$ <span class="tex-font-style-tt"><span class="tex-font-style-striked">10</span>1<span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">1</span>10<span class="tex-font-style-bf">1</span>0</span>. Необходимое время равно $$$y \cdot 2 + x = 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="9c7535127759a2fda1078df786948758"/>
<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="7f72074b8fce01cd9ef8df2ac6803078ff266b22"/>
<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='9c7535127759a2fda1078df786948758'> </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%2F1457%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='9c7535127759a2fda1078df786948758'/>
<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/1457">Codeforces Round 687 (Div. 2, основан на Отборочном раунде 2 Технокубка 2021)</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='9c7535127759a2fda1078df786948758'/>
<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/1457/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="Сложность">
*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='9c7535127759a2fda1078df786948758'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814143"/>
<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='9c7535127759a2fda1078df786948758'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814143"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12470:12471" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12484:12485" 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/1457">Задачи</a></li>
<li><a
href="/contest/1457/submit">Отослать</a></li>
<li><a
href="/contest/1457/my">Мои посылки</a></li>
<li><a
href="/contest/1457/status">Статус</a></li>
<li><a
href="/contest/1457/hacks">Взломы</a></li>
<li><a
href="/contest/1457/room/1">Комната</a></li>
<li><a
href="/contest/1457/standings">Положение</a></li>
<li><a
href="/contest/1457/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_20dbf2989944a90e743180d1bb4595db21b90dca">
<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>Вы создаете уровень для некоторой мобильной игры. Уровень состоит из нескольких клеточек, выстроенных в ряд слева направо и пронумерованных последовательными натуральными числами, начиная с $$$1$$$. Каждую клеточку вы можете оставить пустой или расположить там платформу.</p><p>Чтобы пройти уровень, игрок должен бросить мяч слева так, чтобы он сначала упал на платформу в некоторой клеточке $$$p$$$, отскочил от нее, затем отскочил от платформы в клеточке $$$(p + k)$$$, затем от платформы в клеточке $$$(p + 2k)$$$, и так далее от платформы в каждой $$$k$$$-й клеточке до тех пор, пока он не перепрыгнет правее последней клеточки. Если хотя бы одна из этих клеточек не содержит платформы, то уровень с такими значениями $$$p$$$ и $$$k$$$ пройти нельзя.</p><p>У вас уже есть некоторый шаблон уровня, описываемый числами $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$, где $$$a_i = 0$$$ означает, что в клеточке $$$i$$$ нет платформы, а $$$a_i = 1$$$ означает, что платформа там есть. Вы хотите модифицировать этот шаблон так, чтобы уровень можно было пройти с заданными $$$p$$$ и $$$k$$$. За $$$x$$$ секунд вы можете добавить платформу в любую пустую клеточку. За $$$y$$$ секунд вы можете полностью убрать первую клеточку, при этом количество клеточек уменьшится на один, а оставшиеся клетки пронумеруются заново, сохраняя порядок. Других изменений вы вносить не можете. Вы <span class="tex-font-style-bf">не можете</span> уменьшить число клеток до меньше $$$p$$$.</p><center> <img class="tex-graphics" height="113px" src="https://espresso.codeforces.com/42f170cf3916d6fb4af8c8ee411ed217f8e79ba7.png" style="max-width: 100.0%;max-height: 100.0%;" width="454px" /> <span class="tex-font-size-small">Иллюстрация к третьему тестовому случаю. Крестами отмечены удаленные клеточки. Синим показана добавленная платформа.</span> </center><p>Какое минимальное количество секунд вам требуется, чтобы сделать возможным прохождение уровня с заданными значениями $$$p$$$ и $$$k$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит количество тестовых случаев $$$t$$$ ($$$1 \le t \le 100$$$). Далее следуют описания тестовых случаев.</p><p>Первая строка каждого тестового случая содержит три целых числа $$$n$$$, $$$p$$$ и $$$k$$$ ($$$1 \le p \le n \le 10^5$$$, $$$1 \le k \le n$$$) — начальное количество клеточек, номер первой клеточки, которая должна содержать платформу, и требуемый период прыжков мяча.</p><p>Вторая строка каждого тестового случая содержит строку $$$a_1 a_2 a_3 \ldots a_n$$$ ($$$a_i = 0$$$ или $$$a_i = 1$$$) — начальный шаблон уровня, записанный <span class="tex-font-style-bf">без пробелов</span>.</p><p>Последняя строка каждого тестового случая содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x, y \le 10^4$$$) — время, необходимое для добавления платформы и время, необходимое для удаления первой клеточки, соответственно.</p><p>Сумма $$$n$$$ по всем тестовым случаям не превосходит $$$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>
3
10 3 2
0101010101
2 2
5 4 1
00000
2 10
11 2 3
10110011000
4 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
4
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом случае лучше всего просто убрать первую клеточку, после чего все необходимые платформы будут на своих местах: <span class="tex-font-style-tt"><span class="tex-font-style-striked">0</span>10<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span>0<span class="tex-font-style-bf">1</span></span>. Зачеркнутая цифра удалена, цифры, выделенные жирным — места, где должны быть платформы. Необходимое время равно $$$y = 2$$$.</p><p>Во втором тестовом случае лучше всего добавить платформы в клетки $$$4$$$ и $$$5$$$: <span class="tex-font-style-tt">000<span class="tex-font-style-bf">00</span></span> $$$\to$$$ <span class="tex-font-style-tt">000<span class="tex-font-style-bf">11</span></span>. Необходимое время равно $$$x \cdot 2 = 4$$$.</p><p>В третьем тестовом случае лучше всего удалить первую клеточку дважды и затем добавить платформу в клеточку, которая изначально была $$$10$$$-й: <span class="tex-font-style-tt"><span class="tex-font-style-striked">10</span>1<span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">1</span>10<span class="tex-font-style-bf">0</span>0</span> $$$\to$$$ <span class="tex-font-style-tt"><span class="tex-font-style-striked">10</span>1<span class="tex-font-style-bf">1</span>00<span class="tex-font-style-bf">1</span>10<span class="tex-font-style-bf">1</span>0</span>. Необходимое время равно $$$y \cdot 2 + x = 10$$$.</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:17: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:'8124b54969a100b4',t:'MTY5NjY2NjY1MS4xODQwMDA='};_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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1400"] | ||
1457D | 1457 | D | ru | D. XOR-пушка | <div class="problem-statement"><div class="header"><div class="title">D. XOR-пушка</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> массив натуральных чисел $$$a_1, a_2, \ldots, a_n$$$. Вы завидуете ему и хотите уничтожить это свойство. У вас есть так называемая <span class="tex-font-style-it">XOR-пушка</span>, которую вы можете использовать один или несколько раз.</p><p>За один шаг вы можете выбрать два <span class="tex-font-style-bf">последовательных</span> элемента в массиве, обозначим их за $$$x$$$ и $$$y$$$, удалить их из массива и на их место вставить число $$$x \oplus y$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>. Обратите внимание, что длина массива уменьшается на один в результате этой операции. Вы не можете выполнить эту операцию, если длина массива стала единицей.</p><p>Например, если массив равен $$$[2, 5, 6, 8]$$$, то вы можете выбрать $$$5$$$ и $$$6$$$ и заменить их на $$$5 \oplus 6 = 3$$$. Массив становится равен $$$[2, 3, 8]$$$.</p><p>Вы хотите, чтобы массив перестал быть неубывающим. Какое минимальное количество шагов вам для этого потребуется? Если массив остается неубывающим независимо от того, какие операции вы делаете, выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — начальную длину массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — элементы массива. Гарантируется, что $$$a_i \le a_{i + 1}$$$ для всех $$$1 \le i < n$$$.</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>
4
2 5 6 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
1 2 4 6 20
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно выбрать $$$2$$$ и $$$5$$$, и массив станет равным $$$[7, 6, 8]$$$.</p><p>Во втором примере можно получить только массивы $$$[1, 1]$$$, $$$[3, 3]$$$ и $$$[0]$$$, которые все являются неубывающими.</p><p>В третьем примере можно выбрать $$$1$$$ и $$$2$$$ и массив станет равным $$$[3, 4, 6, 20]$$$. Затем вы можете, например, выбрать $$$3$$$ и $$$4$$$ и массив станет равным $$$[7, 6, 20]$$$. Этот массив не является неубывающим.</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="7ca7f2feafa91675a307f0fd9a93523f"/>
<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="7f72074b8fce01cd9ef8df2ac6803078ff266b22"/>
<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='7ca7f2feafa91675a307f0fd9a93523f'> </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%2F1457%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='7ca7f2feafa91675a307f0fd9a93523f'/>
<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/1457">Codeforces Round 687 (Div. 2, основан на Отборочном раунде 2 Технокубка 2021)</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='7ca7f2feafa91675a307f0fd9a93523f'/>
<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/1457/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="Сложность">
*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='7ca7f2feafa91675a307f0fd9a93523f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814144"/>
<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='7ca7f2feafa91675a307f0fd9a93523f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814144"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12470:12471" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12484:12485" 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/1457">Задачи</a></li>
<li><a
href="/contest/1457/submit">Отослать</a></li>
<li><a
href="/contest/1457/my">Мои посылки</a></li>
<li><a
href="/contest/1457/status">Статус</a></li>
<li><a
href="/contest/1457/hacks">Взломы</a></li>
<li><a
href="/contest/1457/room/1">Комната</a></li>
<li><a
href="/contest/1457/standings">Положение</a></li>
<li><a
href="/contest/1457/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_db358068ab98604544d924a89942c664b9204111">
<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. XOR-пушка</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> массив натуральных чисел $$$a_1, a_2, \ldots, a_n$$$. Вы завидуете ему и хотите уничтожить это свойство. У вас есть так называемая <span class="tex-font-style-it">XOR-пушка</span>, которую вы можете использовать один или несколько раз.</p><p>За один шаг вы можете выбрать два <span class="tex-font-style-bf">последовательных</span> элемента в массиве, обозначим их за $$$x$$$ и $$$y$$$, удалить их из массива и на их место вставить число $$$x \oplus y$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>. Обратите внимание, что длина массива уменьшается на один в результате этой операции. Вы не можете выполнить эту операцию, если длина массива стала единицей.</p><p>Например, если массив равен $$$[2, 5, 6, 8]$$$, то вы можете выбрать $$$5$$$ и $$$6$$$ и заменить их на $$$5 \oplus 6 = 3$$$. Массив становится равен $$$[2, 3, 8]$$$.</p><p>Вы хотите, чтобы массив перестал быть неубывающим. Какое минимальное количество шагов вам для этого потребуется? Если массив остается неубывающим независимо от того, какие операции вы делаете, выведите $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — начальную длину массива.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — элементы массива. Гарантируется, что $$$a_i \le a_{i + 1}$$$ для всех $$$1 \le i < n$$$.</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>
4
2 5 6 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
1 2 4 6 20
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно выбрать $$$2$$$ и $$$5$$$, и массив станет равным $$$[7, 6, 8]$$$.</p><p>Во втором примере можно получить только массивы $$$[1, 1]$$$, $$$[3, 3]$$$ и $$$[0]$$$, которые все являются неубывающими.</p><p>В третьем примере можно выбрать $$$1$$$ и $$$2$$$ и массив станет равным $$$[3, 4, 6, 20]$$$. Затем вы можете, например, выбрать $$$3$$$ и $$$4$$$ и массив станет равным $$$[7, 6, 20]$$$. Этот массив не является неубывающим.</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:17: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:'8124b551bc563a89',t:'MTY5NjY2NjY1Mi41MTYwMDA='};_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\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"] | ["\u0434\u043f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2000"] | ||
1457E | 1457 | 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$$$ боссов, пронумерованных от $$$1$$$ до $$$n$$$. Боссов можно побеждать в любом порядке. Каждого босса нужно победить <span class="tex-font-style-bf">ровно один</span> раз. Также в игре присутствует параметр, называемый комбо-бонусом, изначально равный $$$0$$$.</p><p>Когда игрок побеждает $$$i$$$-го босса, ко счету игрока добавляется текущее значение комбо-бонуса, а затем значение комбо-бонуса изменяется на величину $$$c_i$$$. Обратите внимание, что величина $$$c_i$$$ может быть отрицательной, что означает, что дальнейшие боссы будут давать меньше очков.</p><p>Кролик нашел в игре лазейку. В любой момент времени он может сбросить прохождение игры и начать новое. Это сбросит текущее значение комбо-бонуса в $$$0$$$, но все побежденные боссы останутся побежденными. Кроме того, текущий счет тоже сохраняется и <span class="tex-font-style-bf">не</span> сбрасывается в ноль после этой операции. Эта лазейка может быть использована <span class="tex-font-style-bf">не более</span> $$$k$$$ раз. Можно сбрасывать игру после победы над любым количеством боссов, в том числе перед или после всех, также можно сбрасывать игру несколько раз подряд, не побеждая ни одного босса между сбросами.</p><p>Помогите кролику определить максимально возможный счет, который он может получить, победив <span class="tex-font-style-bf">всех</span> $$$n$$$ боссов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержатся два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$0 \leq k \leq 5 \cdot 10^5$$$) — количество боссов и максимальное количество сбросов соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$c_1,c_2,\ldots,c_n$$$ ($$$-10^6 \leq c_i \leq 10^6$$$) — влияние на комбо-бонус каждого из $$$n$$$ боссов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><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 0
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1
-1 -2 -3 -4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
11
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
13 2
3 1 4 1 5 -9 -2 -6 -5 -3 -5 -8 -9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
71
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте запрещено делать сбросы. Оптимальное решение будет таким. </p><ul> <li> Победить первого босса $$$(+0)$$$. Комбо-бонус становится равным $$$1$$$. </li><li> Победить второго босса $$$(+1)$$$. Комбо-бонус становится равным $$$2$$$. </li><li> Победить третьего босса $$$(+2)$$$. Комбо-бонус становится равным $$$3$$$. </li></ul> <p>Поэтому ответ в первом примере равен $$$0+1+2=3$$$.</p><p>Во втором примере можно показать, что оптимальное решение будет таким: </p><ul> <li> Победить пятого босса $$$(+0)$$$. Комбо-бонус становится равным $$$5$$$. </li><li> Победить первого босса $$$(+5)$$$. Комбо-бонус становится равным $$$4$$$. </li><li> Победить второго босса $$$(+4)$$$. Комбо-бонус становится равным $$$2$$$. </li><li> Победить третьего босса $$$(+2)$$$. Комбо-бонус становится равным $$$-1$$$. </li><li> Сбросить. Комбо-бонус становится равным $$$0$$$. </li><li> Победить четвертого босса $$$(+0)$$$. Комбо-бонус становится равным $$$-4$$$. </li></ul> <p>Поэтому ответ будет равен $$$0+5+4+2+0=11$$$.</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="97770e1dc707e83dae61e5ae3eab1ff8"/>
<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="7f72074b8fce01cd9ef8df2ac6803078ff266b22"/>
<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='97770e1dc707e83dae61e5ae3eab1ff8'> </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%2F1457%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='97770e1dc707e83dae61e5ae3eab1ff8'/>
<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/1457">Codeforces Round 687 (Div. 2, основан на Отборочном раунде 2 Технокубка 2021)</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='97770e1dc707e83dae61e5ae3eab1ff8'/>
<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/1457/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="Сложность">
*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='97770e1dc707e83dae61e5ae3eab1ff8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="814145"/>
<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='97770e1dc707e83dae61e5ae3eab1ff8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="814145"/>
<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/85081" title="Технокубок 2021 — Отборочный Раунд 2 (и открытые рейтинговые раунды Codeforces Round 687 Div.1, Div.2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12470:12471" 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/85118" title="Разбор Технокубок 2021 — Отборочный Раунд 2 (Codeforces Round 687 Div.1, Div.2) " target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12484:12485" 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/1457">Задачи</a></li>
<li><a
href="/contest/1457/submit">Отослать</a></li>
<li><a
href="/contest/1457/my">Мои посылки</a></li>
<li><a
href="/contest/1457/status">Статус</a></li>
<li><a
href="/contest/1457/hacks">Взломы</a></li>
<li><a
href="/contest/1457/room/1">Комната</a></li>
<li><a
href="/contest/1457/standings">Положение</a></li>
<li><a
href="/contest/1457/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_5885a03d17a3230e5032c3533f25ffd93917d7ea">
<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$$$ боссов, пронумерованных от $$$1$$$ до $$$n$$$. Боссов можно побеждать в любом порядке. Каждого босса нужно победить <span class="tex-font-style-bf">ровно один</span> раз. Также в игре присутствует параметр, называемый комбо-бонусом, изначально равный $$$0$$$.</p><p>Когда игрок побеждает $$$i$$$-го босса, ко счету игрока добавляется текущее значение комбо-бонуса, а затем значение комбо-бонуса изменяется на величину $$$c_i$$$. Обратите внимание, что величина $$$c_i$$$ может быть отрицательной, что означает, что дальнейшие боссы будут давать меньше очков.</p><p>Кролик нашел в игре лазейку. В любой момент времени он может сбросить прохождение игры и начать новое. Это сбросит текущее значение комбо-бонуса в $$$0$$$, но все побежденные боссы останутся побежденными. Кроме того, текущий счет тоже сохраняется и <span class="tex-font-style-bf">не</span> сбрасывается в ноль после этой операции. Эта лазейка может быть использована <span class="tex-font-style-bf">не более</span> $$$k$$$ раз. Можно сбрасывать игру после победы над любым количеством боссов, в том числе перед или после всех, также можно сбрасывать игру несколько раз подряд, не побеждая ни одного босса между сбросами.</p><p>Помогите кролику определить максимально возможный счет, который он может получить, победив <span class="tex-font-style-bf">всех</span> $$$n$$$ боссов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержатся два целых числа $$$n$$$ и $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$0 \leq k \leq 5 \cdot 10^5$$$) — количество боссов и максимальное количество сбросов соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$c_1,c_2,\ldots,c_n$$$ ($$$-10^6 \leq c_i \leq 10^6$$$) — влияние на комбо-бонус каждого из $$$n$$$ боссов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><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 0
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1
-1 -2 -3 -4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
11
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
13 2
3 1 4 1 5 -9 -2 -6 -5 -3 -5 -8 -9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
71
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте запрещено делать сбросы. Оптимальное решение будет таким. </p><ul> <li> Победить первого босса $$$(+0)$$$. Комбо-бонус становится равным $$$1$$$. </li><li> Победить второго босса $$$(+1)$$$. Комбо-бонус становится равным $$$2$$$. </li><li> Победить третьего босса $$$(+2)$$$. Комбо-бонус становится равным $$$3$$$. </li></ul> <p>Поэтому ответ в первом примере равен $$$0+1+2=3$$$.</p><p>Во втором примере можно показать, что оптимальное решение будет таким: </p><ul> <li> Победить пятого босса $$$(+0)$$$. Комбо-бонус становится равным $$$5$$$. </li><li> Победить первого босса $$$(+5)$$$. Комбо-бонус становится равным $$$4$$$. </li><li> Победить второго босса $$$(+4)$$$. Комбо-бонус становится равным $$$2$$$. </li><li> Победить третьего босса $$$(+2)$$$. Комбо-бонус становится равным $$$-1$$$. </li><li> Сбросить. Комбо-бонус становится равным $$$0$$$. </li><li> Победить четвертого босса $$$(+0)$$$. Комбо-бонус становится равным $$$-4$$$. </li></ul> <p>Поэтому ответ будет равен $$$0+5+4+2+0=11$$$.</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:17: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:'8124b559e85475bb',t:'MTY5NjY2NjY1My44MTMwMDA='};_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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2200"] | ||
1458A | 1458 | 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>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, \ldots, a_n$$$ и $$$b_1, \ldots, b_m$$$. Для каждого $$$j = 1, \ldots, m$$$ найдите наибольший общий делитель чисел $$$a_1 + b_j, \ldots, a_n + b_j$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 2 \cdot 10^5$$$).</p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^{18})$$$.</p><p>В третьей строке записано $$$m$$$ целых чисел $$$b_1, \ldots, b_m$$$ ($$$1 \leq b_j \leq 10^{18})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел. $$$j$$$-е из этих чисел должно быть равно НОД$$$(a_1 + b_j, \ldots, a_n + b_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 4
1 25 121 169
1 2 7 23
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 8 24
</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="54c179c4bf101a5245373d2e99da26a8"/>
<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="9196c3b48f3e51431b9d97434dd71865cd304b07"/>
<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='54c179c4bf101a5245373d2e99da26a8'> </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%2F1458%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='54c179c4bf101a5245373d2e99da26a8'/>
<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/1458">Codeforces Round 691 (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='54c179c4bf101a5245373d2e99da26a8'/>
<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/1458/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="Сложность">
*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='54c179c4bf101a5245373d2e99da26a8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837942"/>
<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='54c179c4bf101a5245373d2e99da26a8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837942"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12650" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12667" resourceName="Codeforces Round #691 Editorial (finished)"
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/1458">Задачи</a></li>
<li><a
href="/contest/1458/submit">Отослать</a></li>
<li><a
href="/contest/1458/my">Мои посылки</a></li>
<li><a
href="/contest/1458/status">Статус</a></li>
<li><a
href="/contest/1458/hacks">Взломы</a></li>
<li><a
href="/contest/1458/room/1">Комната</a></li>
<li><a
href="/contest/1458/standings">Положение</a></li>
<li><a
href="/contest/1458/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_3b16d680ebe4f27604eadfbd93eeefedd0c04c83">
<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>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, \ldots, a_n$$$ и $$$b_1, \ldots, b_m$$$. Для каждого $$$j = 1, \ldots, m$$$ найдите наибольший общий делитель чисел $$$a_1 + b_j, \ldots, a_n + b_j$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 2 \cdot 10^5$$$).</p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^{18})$$$.</p><p>В третьей строке записано $$$m$$$ целых чисел $$$b_1, \ldots, b_m$$$ ($$$1 \leq b_j \leq 10^{18})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел. $$$j$$$-е из этих чисел должно быть равно НОД$$$(a_1 + b_j, \ldots, a_n + b_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 4
1 25 121 169
1 2 7 23
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 8 24
</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:17: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:'8124b5621d55169f',t:'MTY5NjY2NjY1NS4xODIwMDA='};_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.", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"] | ||
1458B | 1458 | 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>На столе стоит $$$n$$$ стаканов, пронумерованных $$$1, \ldots, n$$$. В стакан $$$i$$$ может поместиться до $$$a_i$$$ единиц объёма воды, и сейчас этот стакан содержит $$$b_i$$$ единиц воды.</p><p>Вы хотите выбрать $$$k$$$ стаканов и собрать в них как можно больше воды. Для этого вы можете сколько угодно раз переливать воду из одного стакана в другой. Однако, из-за очень неудобной формы стаканов (а вовсе не из-за вашей неуклюжести), каждый раз, когда вы пытаетесь перелить любой объём воды, половина этого объёма проливается на пол.</p><p>Формально, пусть стакан $$$i$$$ сейчас содержит $$$c_i$$$ единиц воды, а стакан $$$j$$$ содержит $$$c_j$$$ единиц воды. Пускай вы пытаетесь переместить $$$x$$$ единиц из стакана $$$i$$$ в стакан $$$j$$$ (разумеется, $$$x$$$ не может превосходить $$$c_i$$$). Тогда $$$x / 2$$$ единиц воды проливается на пол. После переливания стакан $$$i$$$ будет содержать $$$c_i - x$$$ единиц воды, а стакан $$$j$$$ будет содержать $$$\min(a_j, c_j + x / 2)$$$ единиц (лишняя вода, которая не помещается в стакан, также проливается).</p><p>Для каждого переливания вы можете произвольно выбрать, из какого стакана $$$i$$$ в какой стакан $$$j$$$ надо переливать, а также переливаемый объём $$$x$$$ может быть произвольным вещественным числом.</p><p>Для каждого $$$k = 1, \ldots, n$$$ определите максимально возможный объём воды, который можно собрать в $$$k$$$ произвольно выбранных стаканах после нуля или более переливаний между стаканами.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 100$$$) — количество стаканов.</p><p>Следующие $$$n$$$ строк описывают стаканы. В $$$i$$$-й из этих строк записано два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$0 \leq b_i \leq a_i \leq 100$$$, $$$a_i > 0$$$) — вместимость и текущее количество воды в стакане $$$i$$$ соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ вещественных чисел — наибольший объём воды, который можно собрать в $$$1, \ldots, n$$$ стаканах соответственно. Ваш ответ будет принят, если каждое число находится в пределах $$$10^{-9}$$$ абсолютной или относительной погрешности от точного ответа.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
6 5
6 5
10 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7.0000000000 11.0000000000 12.0000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере можно действовать так:</p><ul><li> Для $$$k = 1$$$ перельём всю воду из первых двух стаканов в третий. Мы прольём $$$(5 + 5) / 2 = 5$$$ единиц воды и соберём $$$2 + (5 + 5) / 2 = 7$$$ единиц.</li><li> Для $$$k = 2$$$ перельём всю воду из третьего стакана в любой из первых двух. Мы прольём $$$2 / 2 = 1$$$ единиц воды и соберём $$$5 + 5 + 2 / 2 = 11$$$ единиц.</li><li> Для $$$k = 3$$$ ничего не нужно делать. Все $$$5 + 5 + 2 = 12$$$ единиц воды уже собраны.</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="b44467693fbcb4226f29c9cff201040b"/>
<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="9196c3b48f3e51431b9d97434dd71865cd304b07"/>
<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='b44467693fbcb4226f29c9cff201040b'> </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%2F1458%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='b44467693fbcb4226f29c9cff201040b'/>
<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/1458">Codeforces Round 691 (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='b44467693fbcb4226f29c9cff201040b'/>
<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/1458/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="Сложность">
*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='b44467693fbcb4226f29c9cff201040b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837943"/>
<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='b44467693fbcb4226f29c9cff201040b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837943"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12650" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12667" resourceName="Codeforces Round #691 Editorial (finished)"
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/1458">Задачи</a></li>
<li><a
href="/contest/1458/submit">Отослать</a></li>
<li><a
href="/contest/1458/my">Мои посылки</a></li>
<li><a
href="/contest/1458/status">Статус</a></li>
<li><a
href="/contest/1458/hacks">Взломы</a></li>
<li><a
href="/contest/1458/room/1">Комната</a></li>
<li><a
href="/contest/1458/standings">Положение</a></li>
<li><a
href="/contest/1458/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_3f3d2a514baba0b06405ed16268b681a510390e7">
<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>На столе стоит $$$n$$$ стаканов, пронумерованных $$$1, \ldots, n$$$. В стакан $$$i$$$ может поместиться до $$$a_i$$$ единиц объёма воды, и сейчас этот стакан содержит $$$b_i$$$ единиц воды.</p><p>Вы хотите выбрать $$$k$$$ стаканов и собрать в них как можно больше воды. Для этого вы можете сколько угодно раз переливать воду из одного стакана в другой. Однако, из-за очень неудобной формы стаканов (а вовсе не из-за вашей неуклюжести), каждый раз, когда вы пытаетесь перелить любой объём воды, половина этого объёма проливается на пол.</p><p>Формально, пусть стакан $$$i$$$ сейчас содержит $$$c_i$$$ единиц воды, а стакан $$$j$$$ содержит $$$c_j$$$ единиц воды. Пускай вы пытаетесь переместить $$$x$$$ единиц из стакана $$$i$$$ в стакан $$$j$$$ (разумеется, $$$x$$$ не может превосходить $$$c_i$$$). Тогда $$$x / 2$$$ единиц воды проливается на пол. После переливания стакан $$$i$$$ будет содержать $$$c_i - x$$$ единиц воды, а стакан $$$j$$$ будет содержать $$$\min(a_j, c_j + x / 2)$$$ единиц (лишняя вода, которая не помещается в стакан, также проливается).</p><p>Для каждого переливания вы можете произвольно выбрать, из какого стакана $$$i$$$ в какой стакан $$$j$$$ надо переливать, а также переливаемый объём $$$x$$$ может быть произвольным вещественным числом.</p><p>Для каждого $$$k = 1, \ldots, n$$$ определите максимально возможный объём воды, который можно собрать в $$$k$$$ произвольно выбранных стаканах после нуля или более переливаний между стаканами.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 100$$$) — количество стаканов.</p><p>Следующие $$$n$$$ строк описывают стаканы. В $$$i$$$-й из этих строк записано два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$0 \leq b_i \leq a_i \leq 100$$$, $$$a_i > 0$$$) — вместимость и текущее количество воды в стакане $$$i$$$ соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ вещественных чисел — наибольший объём воды, который можно собрать в $$$1, \ldots, n$$$ стаканах соответственно. Ваш ответ будет принят, если каждое число находится в пределах $$$10^{-9}$$$ абсолютной или относительной погрешности от точного ответа.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
6 5
6 5
10 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7.0000000000 11.0000000000 12.0000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере можно действовать так:</p><ul><li> Для $$$k = 1$$$ перельём всю воду из первых двух стаканов в третий. Мы прольём $$$(5 + 5) / 2 = 5$$$ единиц воды и соберём $$$2 + (5 + 5) / 2 = 7$$$ единиц.</li><li> Для $$$k = 2$$$ перельём всю воду из третьего стакана в любой из первых двух. Мы прольём $$$2 / 2 = 1$$$ единиц воды и соберём $$$5 + 5 + 2 / 2 = 11$$$ единиц.</li><li> Для $$$k = 3$$$ ничего не нужно делать. Все $$$5 + 5 + 2 = 12$$$ единиц воды уже собраны.</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:17: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:'8124b56a8a9116a3',t:'MTY5NjY2NjY1Ni41MzcwMDA='};_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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "*2000"] | ||
1458C | 1458 | 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>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$$$. В каждой строке и каждом столбце этой матрицы записана перестановка чисел $$$1$$$, $$$2$$$, $$$\ldots$$$, $$$n$$$. Пусть $$$a_{i, j}$$$ означает число на пересечении $$$i$$$-й строки и $$$j$$$-го столбца для всех $$$1 \leq i, j \leq n$$$. Строки нумеруются $$$1, \ldots, n$$$ сверху вниз, а столбцы нумеруются $$$1, \ldots, n$$$ слева направо.</p><p>Мы совершаем операции шести типов: </p><ul> <li> <span class="tex-font-style-tt">R</span>: циклически сдвинуть все столбцы вправо, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{i, ((j - 2)\bmod n) + 1}$$$; </li><li> <span class="tex-font-style-tt">L</span>: циклически сдвинуть все столбцы влево, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{i, (j\bmod n) + 1}$$$; </li><li> <span class="tex-font-style-tt">D</span>: циклически сдвинуть все строки вниз, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{((i - 2)\bmod n) + 1, j}$$$; </li><li> <span class="tex-font-style-tt">U</span>: циклически сдвинуть все строки вверх, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{(i\bmod n) + 1, j}$$$; </li><li> <span class="tex-font-style-tt">I</span>: заменить перестановку, которую можно прочитать в каждой строке слева направо, на обратную; </li><li> <span class="tex-font-style-tt">C</span>: заменить перестановку, которую можно прочитать в каждом столбце сверху вниз, на обратную. </li></ul><p>Обратной к перестановке $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ является перестановка $$$q_1$$$, $$$q_2$$$, $$$\ldots$$$, $$$q_n$$$, такая что $$$p_{q_i} = i$$$ для каждого $$$1 \leq i \leq n$$$.</p><p>Можно показать, что после любой последовательности операций любая строка и любой столбец матрицы всё ещё будет содержать перестановку чисел $$$1, 2, \ldots, n$$$.</p><p>Вам дано описание исходной матрицы. Нужно совершить $$$m$$$ операций и вывести получившееся состояние матрицы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество тестовых примеров. Далее следует описание $$$t$$$ примеров.</p><p>Первого строка описания каждого примера содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 1000, 1 \leq m \leq 10^5$$$) — размер матрицы и количество операций.</p><p>Каждая из следующих $$$n$$$ строк содержит по $$$n$$$ целых чисел через пробел — элементы матрицы $$$a$$$ ($$$1 \leq a_{i, j} \leq n$$$).</p><p>В последней строке описания записано $$$m$$$ символов, описывающих операции по порядку в формате, описанном выше.</p><p>Сумма всех $$$n$$$ не превосходит $$$1000$$$, а сумма всех $$$m$$$ не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого примера выведите $$$n$$$ строк, по $$$n$$$ чисел в каждой — получившееся состояние матрицы после $$$m$$$ операций.</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 2
1 2 3
2 3 1
3 1 2
DR
3 2
1 2 3
2 3 1
3 1 2
LU
3 1
1 2 3
2 3 1
3 1 2
I
3 1
1 2 3
2 3 1
3 1 2
C
3 16
1 2 3
2 3 1
3 1 2
LDICRUCILDICRUCI
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 1
3 1 2
1 2 3
3 1 2
1 2 3
2 3 1
1 2 3
3 1 2
2 3 1
1 3 2
2 1 3
3 2 1
2 3 1
3 1 2
1 2 3
</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="618fb6d51dc8484995c7f5e92b5f8ef2"/>
<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="9196c3b48f3e51431b9d97434dd71865cd304b07"/>
<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='618fb6d51dc8484995c7f5e92b5f8ef2'> </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%2F1458%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='618fb6d51dc8484995c7f5e92b5f8ef2'/>
<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/1458">Codeforces Round 691 (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='618fb6d51dc8484995c7f5e92b5f8ef2'/>
<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/1458/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="Сложность">
*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='618fb6d51dc8484995c7f5e92b5f8ef2'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837944"/>
<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='618fb6d51dc8484995c7f5e92b5f8ef2'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837944"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12650" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12667" resourceName="Codeforces Round #691 Editorial (finished)"
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/1458">Задачи</a></li>
<li><a
href="/contest/1458/submit">Отослать</a></li>
<li><a
href="/contest/1458/my">Мои посылки</a></li>
<li><a
href="/contest/1458/status">Статус</a></li>
<li><a
href="/contest/1458/hacks">Взломы</a></li>
<li><a
href="/contest/1458/room/1">Комната</a></li>
<li><a
href="/contest/1458/standings">Положение</a></li>
<li><a
href="/contest/1458/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_2df3c12cbbff04098650ae9643f95e67c910526d">
<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>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$$$. В каждой строке и каждом столбце этой матрицы записана перестановка чисел $$$1$$$, $$$2$$$, $$$\ldots$$$, $$$n$$$. Пусть $$$a_{i, j}$$$ означает число на пересечении $$$i$$$-й строки и $$$j$$$-го столбца для всех $$$1 \leq i, j \leq n$$$. Строки нумеруются $$$1, \ldots, n$$$ сверху вниз, а столбцы нумеруются $$$1, \ldots, n$$$ слева направо.</p><p>Мы совершаем операции шести типов: </p><ul> <li> <span class="tex-font-style-tt">R</span>: циклически сдвинуть все столбцы вправо, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{i, ((j - 2)\bmod n) + 1}$$$; </li><li> <span class="tex-font-style-tt">L</span>: циклически сдвинуть все столбцы влево, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{i, (j\bmod n) + 1}$$$; </li><li> <span class="tex-font-style-tt">D</span>: циклически сдвинуть все строки вниз, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{((i - 2)\bmod n) + 1, j}$$$; </li><li> <span class="tex-font-style-tt">U</span>: циклически сдвинуть все строки вверх, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{(i\bmod n) + 1, j}$$$; </li><li> <span class="tex-font-style-tt">I</span>: заменить перестановку, которую можно прочитать в каждой строке слева направо, на обратную; </li><li> <span class="tex-font-style-tt">C</span>: заменить перестановку, которую можно прочитать в каждом столбце сверху вниз, на обратную. </li></ul><p>Обратной к перестановке $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ является перестановка $$$q_1$$$, $$$q_2$$$, $$$\ldots$$$, $$$q_n$$$, такая что $$$p_{q_i} = i$$$ для каждого $$$1 \leq i \leq n$$$.</p><p>Можно показать, что после любой последовательности операций любая строка и любой столбец матрицы всё ещё будет содержать перестановку чисел $$$1, 2, \ldots, n$$$.</p><p>Вам дано описание исходной матрицы. Нужно совершить $$$m$$$ операций и вывести получившееся состояние матрицы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество тестовых примеров. Далее следует описание $$$t$$$ примеров.</p><p>Первого строка описания каждого примера содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 1000, 1 \leq m \leq 10^5$$$) — размер матрицы и количество операций.</p><p>Каждая из следующих $$$n$$$ строк содержит по $$$n$$$ целых чисел через пробел — элементы матрицы $$$a$$$ ($$$1 \leq a_{i, j} \leq n$$$).</p><p>В последней строке описания записано $$$m$$$ символов, описывающих операции по порядку в формате, описанном выше.</p><p>Сумма всех $$$n$$$ не превосходит $$$1000$$$, а сумма всех $$$m$$$ не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого примера выведите $$$n$$$ строк, по $$$n$$$ чисел в каждой — получившееся состояние матрицы после $$$m$$$ операций.</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 2
1 2 3
2 3 1
3 1 2
DR
3 2
1 2 3
2 3 1
3 1 2
LU
3 1
1 2 3
2 3 1
3 1 2
I
3 1
1 2 3
2 3 1
3 1 2
C
3 16
1 2 3
2 3 1
3 1 2
LDICRUCILDICRUCI
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 1
3 1 2
1 2 3
3 1 2
1 2 3
2 3 1
1 2 3
3 1 2
2 3 1
1 3 2
2 1 3
3 2 1
2 3 1
3 1 2
1 2 3
</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=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:17: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:'8124b5731d499da8',t:'MTY5NjY2NjY1Ny44OTAwMDA='};_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\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "*2700"] | ||
1458D | 1458 | 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>Вам дана строка $$$s$$$ из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Вы можете делать преобразование следующего вида:</p><ul><li> выбрать непустую сплошную подстроку $$$s$$$, содержащую одинаковое количество символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>;</li><li> заменить все символы <span class="tex-font-style-tt">0</span> в подстроке на <span class="tex-font-style-tt">1</span>, и наоборот;</li><li> развернуть подстроку. </li></ul><p>Например, рассмотрим $$$s$$$ = <span class="tex-font-style-tt">00111011</span>, и следующее преобразование:</p><ul><li> Выберем в качестве подстроки первые шесть символов: <span class="tex-font-style-tt"><span class="tex-font-style-bf">001110</span>11</span>. Эту подстроку можно выбрать, поскольку в ней количество <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> совпадает. Выбирать подстроки <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">110</span>, или всю строку целиком нельзя.</li><li> Заменим все символы в подстроке на противоположные: <span class="tex-font-style-tt"><span class="tex-font-style-bf">110001</span>11</span>.</li><li> Развернём подстроку: <span class="tex-font-style-tt"><span class="tex-font-style-bf">100011</span>11</span>. </li></ul> <p>Найдите лексикографически минимальную строку, которую можно получить из $$$s$$$ после нуля или более преобразований.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \leq T \leq 5 \cdot 10^5$$$) — количество тестовых примеров. Каждая из следующих $$$T$$$ строк содержит одну непустую последовательность символов — строку $$$s$$$ в соответствующем примере.</p><p>Все строки состоят из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>, и их суммарная длина не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого примера на отдельной строке выведите лексикографически минимальную строку, которую можно получить из $$$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
100101
1100011
10101010
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
010110
0110110
10101010
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере достаточно применить одно преобразование ко всей строке целиком.</p><p>Во втором примере необходимо два преобразования: <span class="tex-font-style-tt"><span class="tex-font-style-bf">011100</span>1</span>, <span class="tex-font-style-tt">011<span class="tex-font-style-bf">0110</span></span>.</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="d18b7f170826f2450545c806ca2a715a"/>
<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="9196c3b48f3e51431b9d97434dd71865cd304b07"/>
<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='d18b7f170826f2450545c806ca2a715a'> </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%2F1458%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='d18b7f170826f2450545c806ca2a715a'/>
<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/1458">Codeforces Round 691 (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='d18b7f170826f2450545c806ca2a715a'/>
<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/1458/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="Сложность">
*3100
</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='d18b7f170826f2450545c806ca2a715a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837945"/>
<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='d18b7f170826f2450545c806ca2a715a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837945"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12650" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12667" resourceName="Codeforces Round #691 Editorial (finished)"
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/1458">Задачи</a></li>
<li><a
href="/contest/1458/submit">Отослать</a></li>
<li><a
href="/contest/1458/my">Мои посылки</a></li>
<li><a
href="/contest/1458/status">Статус</a></li>
<li><a
href="/contest/1458/hacks">Взломы</a></li>
<li><a
href="/contest/1458/room/1">Комната</a></li>
<li><a
href="/contest/1458/standings">Положение</a></li>
<li><a
href="/contest/1458/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_796af1dacbd3ab787520e31aac0730a9156a2b01">
<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>Вам дана строка $$$s$$$ из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Вы можете делать преобразование следующего вида:</p><ul><li> выбрать непустую сплошную подстроку $$$s$$$, содержащую одинаковое количество символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>;</li><li> заменить все символы <span class="tex-font-style-tt">0</span> в подстроке на <span class="tex-font-style-tt">1</span>, и наоборот;</li><li> развернуть подстроку. </li></ul><p>Например, рассмотрим $$$s$$$ = <span class="tex-font-style-tt">00111011</span>, и следующее преобразование:</p><ul><li> Выберем в качестве подстроки первые шесть символов: <span class="tex-font-style-tt"><span class="tex-font-style-bf">001110</span>11</span>. Эту подстроку можно выбрать, поскольку в ней количество <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> совпадает. Выбирать подстроки <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">110</span>, или всю строку целиком нельзя.</li><li> Заменим все символы в подстроке на противоположные: <span class="tex-font-style-tt"><span class="tex-font-style-bf">110001</span>11</span>.</li><li> Развернём подстроку: <span class="tex-font-style-tt"><span class="tex-font-style-bf">100011</span>11</span>. </li></ul> <p>Найдите лексикографически минимальную строку, которую можно получить из $$$s$$$ после нуля или более преобразований.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \leq T \leq 5 \cdot 10^5$$$) — количество тестовых примеров. Каждая из следующих $$$T$$$ строк содержит одну непустую последовательность символов — строку $$$s$$$ в соответствующем примере.</p><p>Все строки состоят из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>, и их суммарная длина не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого примера на отдельной строке выведите лексикографически минимальную строку, которую можно получить из $$$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
100101
1100011
10101010
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
010110
0110110
10101010
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере достаточно применить одно преобразование ко всей строке целиком.</p><p>Во втором примере необходимо два преобразования: <span class="tex-font-style-tt"><span class="tex-font-style-bf">011100</span>1</span>, <span class="tex-font-style-tt">011<span class="tex-font-style-bf">0110</span></span>.</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:17: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:'8124b57b8c389d46',t:'MTY5NjY2NjY1OS4yNTkwMDA='};_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", "\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"] | ["\u0433\u0440\u0430\u0444\u044b", "\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", "*3100"] | ||
1458E | 1458 | 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>После успеха вашей первой мобильной игры «Ним» вы решили выпустить сиквел под названием «Ним 2». Новая игра будет развивать успех проверенной формулы Нима, и добавит столь ожидаемую пользователями вторую кучку! </p><p>В игре есть две кучки, в каждой из которых содержится неотрицательное число камней. Два игрока ходят по очереди. На своём ходу игрок может взять любое положительное число камней из одной из кучек. Игрок, который не может сделать ход, проигрывает.</p><p>Чтобы упростить тестирование игры, вы добавили секреты, известные только разработчику. Есть $$$n$$$ секретных позиций $$$(x_1, y_1), \ldots, (x_n, y_n)$$$, которые влияют на игру следующим образом. Пусть перед ходом одного из игроков первая и вторая кучка содержат $$$x$$$ и $$$y$$$ камней соответственно. Если пара чисел $$$(x, y)$$$ совпадает с одной из пар $$$(x_i, y_i)$$$, то игрок, который должен ходить следующим, немедленно проигрывает, в противном случае этот игрок ходит как обычно. Обратите внимание, что в описании выше кучки и все пары <span class="tex-font-style-bf">упорядочены</span>, то есть, $$$x$$$ обязательно означают размер первой кучки, а $$$y$$$ обязательно означают размер второй кучки.</p><p>После слишком бурного празднования релиза вы вдруг обнаружили, что секреты для разработчика попали в официальное обновление игры! Теперь игроки жалуются, что в некоторых уровнях компьютерный оппонент стал непобедим. Вам требуется написать программу, которая для набора исходных позиций определяла бы, может ли тот игрок, который делает первый ход, победить при любых действиях соперника.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$) — количество секретных позиций и количество исходных позиций для оценки соответственно.</p><p>Следующие $$$n$$$ строк описывают секретные позиции. В $$$i$$$-й из этих строк записано два целых числа $$$x_i, y_i$$$ ($$$0 \leq x_i, y_i \leq 10^9$$$). Гарантируется, что все секретные позиции различны.</p><p>Следующие $$$m$$$ строк описывают исходные позиции. В $$$i$$$-й из этих строк записано два целых числа $$$a_i, b_i$$$ ($$$0 \leq a_i, b_i \leq 10^9$$$) — количество камней в первой и второй кучке соответственно. Гарантируется, что все исходные позиции различны. Однако, некоторые исходные позиции могут совпадать с секретными позициями.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой исходной позиции на отдельной строке выведите «<span class="tex-font-style-tt">WIN</span>», если игрок, совершающий первый ход, заведомо может победить. В противном случае выведите «<span class="tex-font-style-tt">LOSE</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 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
LOSE
WIN
LOSE
WIN
LOSE
</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="95232ce25c67da8fa27f5914dad0bb4d"/>
<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="9196c3b48f3e51431b9d97434dd71865cd304b07"/>
<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='95232ce25c67da8fa27f5914dad0bb4d'> </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%2F1458%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='95232ce25c67da8fa27f5914dad0bb4d'/>
<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/1458">Codeforces Round 691 (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='95232ce25c67da8fa27f5914dad0bb4d'/>
<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/1458/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="Сложность">
*3100
</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='95232ce25c67da8fa27f5914dad0bb4d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837946"/>
<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='95232ce25c67da8fa27f5914dad0bb4d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837946"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12650" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12667" resourceName="Codeforces Round #691 Editorial (finished)"
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/1458">Задачи</a></li>
<li><a
href="/contest/1458/submit">Отослать</a></li>
<li><a
href="/contest/1458/my">Мои посылки</a></li>
<li><a
href="/contest/1458/status">Статус</a></li>
<li><a
href="/contest/1458/hacks">Взломы</a></li>
<li><a
href="/contest/1458/room/1">Комната</a></li>
<li><a
href="/contest/1458/standings">Положение</a></li>
<li><a
href="/contest/1458/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_a300e117e934a9614732a29738881a807b0c534e">
<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>После успеха вашей первой мобильной игры «Ним» вы решили выпустить сиквел под названием «Ним 2». Новая игра будет развивать успех проверенной формулы Нима, и добавит столь ожидаемую пользователями вторую кучку! </p><p>В игре есть две кучки, в каждой из которых содержится неотрицательное число камней. Два игрока ходят по очереди. На своём ходу игрок может взять любое положительное число камней из одной из кучек. Игрок, который не может сделать ход, проигрывает.</p><p>Чтобы упростить тестирование игры, вы добавили секреты, известные только разработчику. Есть $$$n$$$ секретных позиций $$$(x_1, y_1), \ldots, (x_n, y_n)$$$, которые влияют на игру следующим образом. Пусть перед ходом одного из игроков первая и вторая кучка содержат $$$x$$$ и $$$y$$$ камней соответственно. Если пара чисел $$$(x, y)$$$ совпадает с одной из пар $$$(x_i, y_i)$$$, то игрок, который должен ходить следующим, немедленно проигрывает, в противном случае этот игрок ходит как обычно. Обратите внимание, что в описании выше кучки и все пары <span class="tex-font-style-bf">упорядочены</span>, то есть, $$$x$$$ обязательно означают размер первой кучки, а $$$y$$$ обязательно означают размер второй кучки.</p><p>После слишком бурного празднования релиза вы вдруг обнаружили, что секреты для разработчика попали в официальное обновление игры! Теперь игроки жалуются, что в некоторых уровнях компьютерный оппонент стал непобедим. Вам требуется написать программу, которая для набора исходных позиций определяла бы, может ли тот игрок, который делает первый ход, победить при любых действиях соперника.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$) — количество секретных позиций и количество исходных позиций для оценки соответственно.</p><p>Следующие $$$n$$$ строк описывают секретные позиции. В $$$i$$$-й из этих строк записано два целых числа $$$x_i, y_i$$$ ($$$0 \leq x_i, y_i \leq 10^9$$$). Гарантируется, что все секретные позиции различны.</p><p>Следующие $$$m$$$ строк описывают исходные позиции. В $$$i$$$-й из этих строк записано два целых числа $$$a_i, b_i$$$ ($$$0 \leq a_i, b_i \leq 10^9$$$) — количество камней в первой и второй кучке соответственно. Гарантируется, что все исходные позиции различны. Однако, некоторые исходные позиции могут совпадать с секретными позициями.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждой исходной позиции на отдельной строке выведите «<span class="tex-font-style-tt">WIN</span>», если игрок, совершающий первый ход, заведомо может победить. В противном случае выведите «<span class="tex-font-style-tt">LOSE</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 5
3 0
0 1
2 2
0 0
1 1
2 2
3 3
5 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
LOSE
WIN
LOSE
WIN
LOSE
</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:17: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:'8124b583fb340004',t:'MTY5NjY2NjY2MC41NzMwMDA='};_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\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\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"] | ["\u0438\u0433\u0440\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3100"] | ||
1458F | 1458 | F | ru | F. Сумма диаметров | <div class="problem-statement"><div class="header"><div class="title">F. Сумма диаметров</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>Вам дано дерево с $$$n$$$ вершинами, пронумерованными $$$1, \ldots, n$$$. Дерево — это связный простой граф без циклов.</p><p>Пусть $$$\mathrm{dist}(u, v)$$$ означает количество рёбер на единственном простом пути между вершинами $$$u$$$ и $$$v$$$.</p><p>Пусть $$$\mathrm{diam}(l, r) = \max \mathrm{dist}(u, v)$$$ по всем парам $$$u, v$$$, таким что $$$l \leq u, v \leq r$$$.</p><p>Вычислите $$$\sum_{1 \leq l \leq r \leq n} \mathrm{diam}(l, r)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количесто вершин в дереве.</p><p>Следующие $$$n - 1$$$ строк описывают рёбра дерева. Каждая из этих строк содержит два целых числа $$$u, v$$$ ($$$1 \leq u, v \leq n$$$) — номера концов очередного ребра. Гарантируется, что данный список рёбер действительно задаёт дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — $$$\sum_{1 \leq l \leq r \leq n} \mathrm{diam}(l, r)$$$.</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 2
2 4
3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 8
2 9
5 6
4 8
4 2
7 9
3 6
10 4
3 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
224
</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="05af61f4f4de61158f8fa9e542d2074b"/>
<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="9196c3b48f3e51431b9d97434dd71865cd304b07"/>
<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='05af61f4f4de61158f8fa9e542d2074b'> </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%2F1458%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='05af61f4f4de61158f8fa9e542d2074b'/>
<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/1458">Codeforces Round 691 (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='05af61f4f4de61158f8fa9e542d2074b'/>
<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/1458/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="Сложность">
*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='05af61f4f4de61158f8fa9e542d2074b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837947"/>
<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='05af61f4f4de61158f8fa9e542d2074b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837947"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12650" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12667" resourceName="Codeforces Round #691 Editorial (finished)"
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/1458">Задачи</a></li>
<li><a
href="/contest/1458/submit">Отослать</a></li>
<li><a
href="/contest/1458/my">Мои посылки</a></li>
<li><a
href="/contest/1458/status">Статус</a></li>
<li><a
href="/contest/1458/hacks">Взломы</a></li>
<li><a
href="/contest/1458/room/1">Комната</a></li>
<li><a
href="/contest/1458/standings">Положение</a></li>
<li><a
href="/contest/1458/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_46cbff710e4cbd3ddee99aef4b01ecf6166034bc">
<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>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>Вам дано дерево с $$$n$$$ вершинами, пронумерованными $$$1, \ldots, n$$$. Дерево — это связный простой граф без циклов.</p><p>Пусть $$$\mathrm{dist}(u, v)$$$ означает количество рёбер на единственном простом пути между вершинами $$$u$$$ и $$$v$$$.</p><p>Пусть $$$\mathrm{diam}(l, r) = \max \mathrm{dist}(u, v)$$$ по всем парам $$$u, v$$$, таким что $$$l \leq u, v \leq r$$$.</p><p>Вычислите $$$\sum_{1 \leq l \leq r \leq n} \mathrm{diam}(l, r)$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — количесто вершин в дереве.</p><p>Следующие $$$n - 1$$$ строк описывают рёбра дерева. Каждая из этих строк содержит два целых числа $$$u, v$$$ ($$$1 \leq u, v \leq n$$$) — номера концов очередного ребра. Гарантируется, что данный список рёбер действительно задаёт дерево.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — $$$\sum_{1 \leq l \leq r \leq n} \mathrm{diam}(l, r)$$$.</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 2
2 4
3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1 8
2 9
5 6
4 8
4 2
7 9
3 6
10 4
3 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
224
</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:17: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:'8124b58c3d4a7b4b',t:'MTY5NjY2NjY2MS44OTQwMDA='};_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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3500"] | ||
1459A | 1459 | 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>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$$$ карточек, пронумерованных числами $$$1, \ldots, n$$$. На карточке $$$i$$$ написана красная цифра $$$r_i$$$ и синяя цифра $$$b_i$$$.</p><p>Мы переупорядочиваем все $$$n$$$ карточек слева направо в случайном порядке, так что все перестановки $$$1, \ldots, n$$$ равновероятны. Затем мы читаем все красные цифры слева направо, и получаем целое число $$$R$$$. Аналогично мы читаем все синие цифры и получаем число $$$B$$$. Ведущие нули в числах игнорируются. Если все цифры в числе равны нулю, то такое число равно $$$0$$$. Ниже изображено одно из возможных переупорядочиваний трёх карт, и пример того, как определять $$$R$$$ и $$$B$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f70539e203b4ec50b85f54ccb854c3948606cedd.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Два игрока, Красный и Синий, заключают пари. Красный ставит на то, что после перемешивания $$$R > B$$$, а Синий ставит на то, что $$$R < B$$$. Если в итоге $$$R = B$$$, то объявляется ничья и никто не выигрывает спор.</p><p>Определите, кто из двух игроков имеет лучшие шансы выиграть спор, либо что шансы игроков одинаковы. Для формального описания того, как сравниваются вероятности, см. секцию Примечание.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \leq T \leq 100$$$) — количество тестовых примеров.</p><p>Далее следуют описания $$$T$$$ примеров. Описание каждого примера начинается со строки с одним целым числом $$$n$$$ ($$$1 \leq n \leq 1000$$$) — количеством карточек.</p><p>В следующей строке записано $$$n$$$ цифр $$$r_1, \ldots, r_n$$$ — красные цифры на карточках $$$1, \ldots, n$$$ соответственно.</p><p>В следующей строке записано $$$n$$$ цифр $$$b_1, \ldots, b_n$$$ — синие цифры на карточках $$$1, \ldots, n$$$ соответственно.</p><p>Цифры в каждой строке записаны без разделителей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ ответов на примеры по порядку, по одному ответу на строку.</p><p>Если шансы Красного игрока на победу <span class="tex-font-style-bf">строго выше</span>, выведите «<span class="tex-font-style-tt">RED</span>».</p><p>Если шансы Синего игрока на победу <span class="tex-font-style-bf">строго выше</span>, выведите «<span class="tex-font-style-tt">BLUE</span>».</p><p>Если шансы игроков совпадают, выведите «<span class="tex-font-style-tt">EQUAL</span>».</p><p>Обратите внимание, что <span class="tex-font-style-bf">регистр</span> всех ответов <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>
3
3
777
111
3
314
159
5
09281
09281
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
RED
BLUE
EQUAL
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Формально, пусть $$$n_R$$$ равно количеству перестановок карточек $$$1, \ldots, n$$$, при которых получающиеся числа $$$R$$$ и $$$B$$$ удовлетворяют $$$R > B$$$. Аналогично, пусть $$$n_B$$$ равно количеству перестановок, при которых $$$R < B$$$. Если $$$n_R > n_B$$$, вам нужно вывести «<span class="tex-font-style-tt">RED</span>». Если $$$n_R < n_B$$$, нужно вывести «<span class="tex-font-style-tt">BLUE</span>». Если $$$n_R = n_B$$$, выведите «<span class="tex-font-style-tt">EQUAL</span>».</p><p>В первом примере $$$R = 777$$$ и $$$B = 111$$$ независимо от порядка карт, поэтому Красный всегда выигрывает.</p><p>Во втором примере существует две перестановки карт, при которых выигрывает Красный, и четыре перестановки, при которых выигрывает Синий:</p><ul><li> перестановка $$$1, 2, 3$$$: $$$314 > 159$$$;</li><li> перестановка $$$1, 3, 2$$$: $$$341 > 195$$$;</li><li> перестановка $$$2, 1, 3$$$: $$$134 < 519$$$;</li><li> перестановка $$$2, 3, 1$$$: $$$143 < 591$$$;</li><li> перестановка $$$3, 1, 2$$$: $$$431 < 915$$$;</li><li> перестановка $$$3, 2, 1$$$: $$$413 < 951$$$.</li></ul><p>Поскольку $$$R < B$$$ происходит более часто, вывести нужно «<span class="tex-font-style-tt">BLUE</span>».</p><p>В третьем примере $$$R = 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="ae826df369133ea36634633b9f22aaea"/>
<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="5218e2cbbc405c348ab51957b9d1ede47ace8993"/>
<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='ae826df369133ea36634633b9f22aaea'> </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%2F1459%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='ae826df369133ea36634633b9f22aaea'/>
<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/1459">Codeforces Round 691 (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='ae826df369133ea36634633b9f22aaea'/>
<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/1459/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='ae826df369133ea36634633b9f22aaea'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837948"/>
<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='ae826df369133ea36634633b9f22aaea'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837948"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12651" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12666" resourceName="Codeforces Round #691 Editorial (finished)"
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/1459">Задачи</a></li>
<li><a
href="/contest/1459/submit">Отослать</a></li>
<li><a
href="/contest/1459/my">Мои посылки</a></li>
<li><a
href="/contest/1459/status">Статус</a></li>
<li><a
href="/contest/1459/hacks">Взломы</a></li>
<li><a
href="/contest/1459/room/1">Комната</a></li>
<li><a
href="/contest/1459/standings">Положение</a></li>
<li><a
href="/contest/1459/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_f68f51a4c574fd06f9f0b410aa241188d6e1712d">
<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>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$$$ карточек, пронумерованных числами $$$1, \ldots, n$$$. На карточке $$$i$$$ написана красная цифра $$$r_i$$$ и синяя цифра $$$b_i$$$.</p><p>Мы переупорядочиваем все $$$n$$$ карточек слева направо в случайном порядке, так что все перестановки $$$1, \ldots, n$$$ равновероятны. Затем мы читаем все красные цифры слева направо, и получаем целое число $$$R$$$. Аналогично мы читаем все синие цифры и получаем число $$$B$$$. Ведущие нули в числах игнорируются. Если все цифры в числе равны нулю, то такое число равно $$$0$$$. Ниже изображено одно из возможных переупорядочиваний трёх карт, и пример того, как определять $$$R$$$ и $$$B$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f70539e203b4ec50b85f54ccb854c3948606cedd.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Два игрока, Красный и Синий, заключают пари. Красный ставит на то, что после перемешивания $$$R > B$$$, а Синий ставит на то, что $$$R < B$$$. Если в итоге $$$R = B$$$, то объявляется ничья и никто не выигрывает спор.</p><p>Определите, кто из двух игроков имеет лучшие шансы выиграть спор, либо что шансы игроков одинаковы. Для формального описания того, как сравниваются вероятности, см. секцию Примечание.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \leq T \leq 100$$$) — количество тестовых примеров.</p><p>Далее следуют описания $$$T$$$ примеров. Описание каждого примера начинается со строки с одним целым числом $$$n$$$ ($$$1 \leq n \leq 1000$$$) — количеством карточек.</p><p>В следующей строке записано $$$n$$$ цифр $$$r_1, \ldots, r_n$$$ — красные цифры на карточках $$$1, \ldots, n$$$ соответственно.</p><p>В следующей строке записано $$$n$$$ цифр $$$b_1, \ldots, b_n$$$ — синие цифры на карточках $$$1, \ldots, n$$$ соответственно.</p><p>Цифры в каждой строке записаны без разделителей.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ ответов на примеры по порядку, по одному ответу на строку.</p><p>Если шансы Красного игрока на победу <span class="tex-font-style-bf">строго выше</span>, выведите «<span class="tex-font-style-tt">RED</span>».</p><p>Если шансы Синего игрока на победу <span class="tex-font-style-bf">строго выше</span>, выведите «<span class="tex-font-style-tt">BLUE</span>».</p><p>Если шансы игроков совпадают, выведите «<span class="tex-font-style-tt">EQUAL</span>».</p><p>Обратите внимание, что <span class="tex-font-style-bf">регистр</span> всех ответов <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>
3
3
777
111
3
314
159
5
09281
09281
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
RED
BLUE
EQUAL
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Формально, пусть $$$n_R$$$ равно количеству перестановок карточек $$$1, \ldots, n$$$, при которых получающиеся числа $$$R$$$ и $$$B$$$ удовлетворяют $$$R > B$$$. Аналогично, пусть $$$n_B$$$ равно количеству перестановок, при которых $$$R < B$$$. Если $$$n_R > n_B$$$, вам нужно вывести «<span class="tex-font-style-tt">RED</span>». Если $$$n_R < n_B$$$, нужно вывести «<span class="tex-font-style-tt">BLUE</span>». Если $$$n_R = n_B$$$, выведите «<span class="tex-font-style-tt">EQUAL</span>».</p><p>В первом примере $$$R = 777$$$ и $$$B = 111$$$ независимо от порядка карт, поэтому Красный всегда выигрывает.</p><p>Во втором примере существует две перестановки карт, при которых выигрывает Красный, и четыре перестановки, при которых выигрывает Синий:</p><ul><li> перестановка $$$1, 2, 3$$$: $$$314 > 159$$$;</li><li> перестановка $$$1, 3, 2$$$: $$$341 > 195$$$;</li><li> перестановка $$$2, 1, 3$$$: $$$134 < 519$$$;</li><li> перестановка $$$2, 3, 1$$$: $$$143 < 591$$$;</li><li> перестановка $$$3, 1, 2$$$: $$$431 < 915$$$;</li><li> перестановка $$$3, 2, 1$$$: $$$413 < 951$$$.</li></ul><p>Поскольку $$$R < B$$$ происходит более часто, вывести нужно «<span class="tex-font-style-tt">BLUE</span>».</p><p>В третьем примере $$$R = B$$$ независимо от порядка карт, поэтому спор всегда заканчивается вничью, и шансы обоих игроков на победу равны нулю.</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:17: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:'8124b594b9261683',t:'MTY5NjY2NjY2My4zOTQwMDA='};_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.", "\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"] | ["\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", "*800"] | ||
1459B | 1459 | 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>В начале координат бесконечной двумерной плоскости находится робот. Каждую секунду робот перещается ровно на $$$1$$$ метр в одном из четырёх направлений: на север, юг, запад или восток. Робот <span class="tex-font-style-bf">может выбрать произвольное направление</span> для первого шага, но после этого в конце каждой секунды он <span class="tex-font-style-bf">обязан повернуть</span> на 90 градусов влево или вправо относительно направления, в котором только что двигался. Например, если робот только что переместился на север или юг, его следующий шаг должен быть на запад или восток, и наоборот.</p><p>Робот совершает <span class="tex-font-style-bf">ровно</span> $$$n$$$ шагов из начального положения в соответствиями с правилами выше. В скольких различных точках робот может оказаться в итоге? Финальное направление робота можно игнорировать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 1000$$$) — количество шагов робота.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество различных возможных положений робота после <span class="tex-font-style-bf">ровно</span> $$$n$$$ шагов.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере робот переместится на 1 метр на север, юг, запад или восток в зависимости от исходного направления.</p><p>Во втором примере робот всегда окажется в $$$\sqrt{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="47c5e48d203ff47f4c52ec3b908a7b62"/>
<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="5218e2cbbc405c348ab51957b9d1ede47ace8993"/>
<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='47c5e48d203ff47f4c52ec3b908a7b62'> </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%2F1459%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='47c5e48d203ff47f4c52ec3b908a7b62'/>
<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/1459">Codeforces Round 691 (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='47c5e48d203ff47f4c52ec3b908a7b62'/>
<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/1459/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="Сложность">
*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='47c5e48d203ff47f4c52ec3b908a7b62'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837949"/>
<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='47c5e48d203ff47f4c52ec3b908a7b62'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837949"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12651" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12666" resourceName="Codeforces Round #691 Editorial (finished)"
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/1459">Задачи</a></li>
<li><a
href="/contest/1459/submit">Отослать</a></li>
<li><a
href="/contest/1459/my">Мои посылки</a></li>
<li><a
href="/contest/1459/status">Статус</a></li>
<li><a
href="/contest/1459/hacks">Взломы</a></li>
<li><a
href="/contest/1459/room/1">Комната</a></li>
<li><a
href="/contest/1459/standings">Положение</a></li>
<li><a
href="/contest/1459/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_1f27bb42016038036e0d3e0bba4a9e187888a0f6">
<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>В начале координат бесконечной двумерной плоскости находится робот. Каждую секунду робот перещается ровно на $$$1$$$ метр в одном из четырёх направлений: на север, юг, запад или восток. Робот <span class="tex-font-style-bf">может выбрать произвольное направление</span> для первого шага, но после этого в конце каждой секунды он <span class="tex-font-style-bf">обязан повернуть</span> на 90 градусов влево или вправо относительно направления, в котором только что двигался. Например, если робот только что переместился на север или юг, его следующий шаг должен быть на запад или восток, и наоборот.</p><p>Робот совершает <span class="tex-font-style-bf">ровно</span> $$$n$$$ шагов из начального положения в соответствиями с правилами выше. В скольких различных точках робот может оказаться в итоге? Финальное направление робота можно игнорировать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 1000$$$) — количество шагов робота.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество различных возможных положений робота после <span class="tex-font-style-bf">ровно</span> $$$n$$$ шагов.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере робот переместится на 1 метр на север, юг, запад или восток в зависимости от исходного направления.</p><p>Во втором примере робот всегда окажется в $$$\sqrt{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:17: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:'8124b59def4d1672',t:'MTY5NjY2NjY2NC43MTQwMDA='};_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", "*1300"] | ||
1459C | 1459 | 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>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, \ldots, a_n$$$ и $$$b_1, \ldots, b_m$$$. Для каждого $$$j = 1, \ldots, m$$$ найдите наибольший общий делитель чисел $$$a_1 + b_j, \ldots, a_n + b_j$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 2 \cdot 10^5$$$).</p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^{18})$$$.</p><p>В третьей строке записано $$$m$$$ целых чисел $$$b_1, \ldots, b_m$$$ ($$$1 \leq b_j \leq 10^{18})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел. $$$j$$$-е из этих чисел должно быть равно НОД$$$(a_1 + b_j, \ldots, a_n + b_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 4
1 25 121 169
1 2 7 23
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 8 24
</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="a3696a018dfb8e93d491589d67245b4a"/>
<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="5218e2cbbc405c348ab51957b9d1ede47ace8993"/>
<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='a3696a018dfb8e93d491589d67245b4a'> </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%2F1459%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='a3696a018dfb8e93d491589d67245b4a'/>
<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/1459">Codeforces Round 691 (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='a3696a018dfb8e93d491589d67245b4a'/>
<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/1459/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="Сложность">
*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='a3696a018dfb8e93d491589d67245b4a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837950"/>
<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='a3696a018dfb8e93d491589d67245b4a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837950"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12651" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12666" resourceName="Codeforces Round #691 Editorial (finished)"
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/1459">Задачи</a></li>
<li><a
href="/contest/1459/submit">Отослать</a></li>
<li><a
href="/contest/1459/my">Мои посылки</a></li>
<li><a
href="/contest/1459/status">Статус</a></li>
<li><a
href="/contest/1459/hacks">Взломы</a></li>
<li><a
href="/contest/1459/room/1">Комната</a></li>
<li><a
href="/contest/1459/standings">Положение</a></li>
<li><a
href="/contest/1459/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_230267fa296026e8bae950eb15a2f98461611392">
<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>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, \ldots, a_n$$$ и $$$b_1, \ldots, b_m$$$. Для каждого $$$j = 1, \ldots, m$$$ найдите наибольший общий делитель чисел $$$a_1 + b_j, \ldots, a_n + b_j$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n, m \leq 2 \cdot 10^5$$$).</p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^{18})$$$.</p><p>В третьей строке записано $$$m$$$ целых чисел $$$b_1, \ldots, b_m$$$ ($$$1 \leq b_j \leq 10^{18})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел. $$$j$$$-е из этих чисел должно быть равно НОД$$$(a_1 + b_j, \ldots, a_n + b_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 4
1 25 121 169
1 2 7 23
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 8 24
</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:17: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:'8124b5a62dd99d4f',t:'MTY5NjY2NjY2Ni4wMDEwMDA='};_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.", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1600"] | ||
1459D | 1459 | 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$$$ стаканов, пронумерованных $$$1, \ldots, n$$$. В стакан $$$i$$$ может поместиться до $$$a_i$$$ единиц объёма воды, и сейчас этот стакан содержит $$$b_i$$$ единиц воды.</p><p>Вы хотите выбрать $$$k$$$ стаканов и собрать в них как можно больше воды. Для этого вы можете сколько угодно раз переливать воду из одного стакана в другой. Однако, из-за очень неудобной формы стаканов (а вовсе не из-за вашей неуклюжести), каждый раз, когда вы пытаетесь перелить любой объём воды, половина этого объёма проливается на пол.</p><p>Формально, пусть стакан $$$i$$$ сейчас содержит $$$c_i$$$ единиц воды, а стакан $$$j$$$ содержит $$$c_j$$$ единиц воды. Пускай вы пытаетесь переместить $$$x$$$ единиц из стакана $$$i$$$ в стакан $$$j$$$ (разумеется, $$$x$$$ не может превосходить $$$c_i$$$). Тогда $$$x / 2$$$ единиц воды проливается на пол. После переливания стакан $$$i$$$ будет содержать $$$c_i - x$$$ единиц воды, а стакан $$$j$$$ будет содержать $$$\min(a_j, c_j + x / 2)$$$ единиц (лишняя вода, которая не помещается в стакан, также проливается).</p><p>Для каждого переливания вы можете произвольно выбрать, из какого стакана $$$i$$$ в какой стакан $$$j$$$ надо переливать, а также переливаемый объём $$$x$$$ может быть произвольным вещественным числом.</p><p>Для каждого $$$k = 1, \ldots, n$$$ определите максимально возможный объём воды, который можно собрать в $$$k$$$ произвольно выбранных стаканах после нуля или более переливаний между стаканами.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 100$$$) — количество стаканов.</p><p>Следующие $$$n$$$ строк описывают стаканы. В $$$i$$$-й из этих строк записано два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$0 \leq b_i \leq a_i \leq 100$$$, $$$a_i > 0$$$) — вместимость и текущее количество воды в стакане $$$i$$$ соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ вещественных чисел — наибольший объём воды, который можно собрать в $$$1, \ldots, n$$$ стаканах соответственно. Ваш ответ будет принят, если каждое число находится в пределах $$$10^{-9}$$$ абсолютной или относительной погрешности от точного ответа.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
6 5
6 5
10 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7.0000000000 11.0000000000 12.0000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере можно действовать так:</p><ul><li> Для $$$k = 1$$$ перельём всю воду из первых двух стаканов в третий. Мы прольём $$$(5 + 5) / 2 = 5$$$ единиц воды и соберём $$$2 + (5 + 5) / 2 = 7$$$ единиц.</li><li> Для $$$k = 2$$$ перельём всю воду из третьего стакана в любой из первых двух. Мы прольём $$$2 / 2 = 1$$$ единиц воды и соберём $$$5 + 5 + 2 / 2 = 11$$$ единиц.</li><li> Для $$$k = 3$$$ ничего не нужно делать. Все $$$5 + 5 + 2 = 12$$$ единиц воды уже собраны.</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="66e8b53e8503abf90f032d86932bbe36"/>
<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="5218e2cbbc405c348ab51957b9d1ede47ace8993"/>
<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='66e8b53e8503abf90f032d86932bbe36'> </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%2F1459%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='66e8b53e8503abf90f032d86932bbe36'/>
<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/1459">Codeforces Round 691 (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='66e8b53e8503abf90f032d86932bbe36'/>
<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/1459/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="Сложность">
*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='66e8b53e8503abf90f032d86932bbe36'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837951"/>
<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='66e8b53e8503abf90f032d86932bbe36'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837951"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12651" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12666" resourceName="Codeforces Round #691 Editorial (finished)"
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/1459">Задачи</a></li>
<li><a
href="/contest/1459/submit">Отослать</a></li>
<li><a
href="/contest/1459/my">Мои посылки</a></li>
<li><a
href="/contest/1459/status">Статус</a></li>
<li><a
href="/contest/1459/hacks">Взломы</a></li>
<li><a
href="/contest/1459/room/1">Комната</a></li>
<li><a
href="/contest/1459/standings">Положение</a></li>
<li><a
href="/contest/1459/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_7de274a4856c97207415acdd19644250a336c68b">
<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$$$ стаканов, пронумерованных $$$1, \ldots, n$$$. В стакан $$$i$$$ может поместиться до $$$a_i$$$ единиц объёма воды, и сейчас этот стакан содержит $$$b_i$$$ единиц воды.</p><p>Вы хотите выбрать $$$k$$$ стаканов и собрать в них как можно больше воды. Для этого вы можете сколько угодно раз переливать воду из одного стакана в другой. Однако, из-за очень неудобной формы стаканов (а вовсе не из-за вашей неуклюжести), каждый раз, когда вы пытаетесь перелить любой объём воды, половина этого объёма проливается на пол.</p><p>Формально, пусть стакан $$$i$$$ сейчас содержит $$$c_i$$$ единиц воды, а стакан $$$j$$$ содержит $$$c_j$$$ единиц воды. Пускай вы пытаетесь переместить $$$x$$$ единиц из стакана $$$i$$$ в стакан $$$j$$$ (разумеется, $$$x$$$ не может превосходить $$$c_i$$$). Тогда $$$x / 2$$$ единиц воды проливается на пол. После переливания стакан $$$i$$$ будет содержать $$$c_i - x$$$ единиц воды, а стакан $$$j$$$ будет содержать $$$\min(a_j, c_j + x / 2)$$$ единиц (лишняя вода, которая не помещается в стакан, также проливается).</p><p>Для каждого переливания вы можете произвольно выбрать, из какого стакана $$$i$$$ в какой стакан $$$j$$$ надо переливать, а также переливаемый объём $$$x$$$ может быть произвольным вещественным числом.</p><p>Для каждого $$$k = 1, \ldots, n$$$ определите максимально возможный объём воды, который можно собрать в $$$k$$$ произвольно выбранных стаканах после нуля или более переливаний между стаканами.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 100$$$) — количество стаканов.</p><p>Следующие $$$n$$$ строк описывают стаканы. В $$$i$$$-й из этих строк записано два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$0 \leq b_i \leq a_i \leq 100$$$, $$$a_i > 0$$$) — вместимость и текущее количество воды в стакане $$$i$$$ соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ вещественных чисел — наибольший объём воды, который можно собрать в $$$1, \ldots, n$$$ стаканах соответственно. Ваш ответ будет принят, если каждое число находится в пределах $$$10^{-9}$$$ абсолютной или относительной погрешности от точного ответа.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
6 5
6 5
10 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7.0000000000 11.0000000000 12.0000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере можно действовать так:</p><ul><li> Для $$$k = 1$$$ перельём всю воду из первых двух стаканов в третий. Мы прольём $$$(5 + 5) / 2 = 5$$$ единиц воды и соберём $$$2 + (5 + 5) / 2 = 7$$$ единиц.</li><li> Для $$$k = 2$$$ перельём всю воду из третьего стакана в любой из первых двух. Мы прольём $$$2 / 2 = 1$$$ единиц воды и соберём $$$5 + 5 + 2 / 2 = 11$$$ единиц.</li><li> Для $$$k = 3$$$ ничего не нужно делать. Все $$$5 + 5 + 2 = 12$$$ единиц воды уже собраны.</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:17: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:'8124b5ae39e376b5',t:'MTY5NjY2NjY2Ny4zMDcwMDA='};_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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2000"] | ||
1459E | 1459 | 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>Вам дана квадратная матрица размера $$$n$$$. В каждой строке и каждом столбце этой матрицы записана перестановка чисел $$$1$$$, $$$2$$$, $$$\ldots$$$, $$$n$$$. Пусть $$$a_{i, j}$$$ означает число на пересечении $$$i$$$-й строки и $$$j$$$-го столбца для всех $$$1 \leq i, j \leq n$$$. Строки нумеруются $$$1, \ldots, n$$$ сверху вниз, а столбцы нумеруются $$$1, \ldots, n$$$ слева направо.</p><p>Мы совершаем операции шести типов: </p><ul> <li> <span class="tex-font-style-tt">R</span>: циклически сдвинуть все столбцы вправо, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{i, ((j - 2)\bmod n) + 1}$$$; </li><li> <span class="tex-font-style-tt">L</span>: циклически сдвинуть все столбцы влево, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{i, (j\bmod n) + 1}$$$; </li><li> <span class="tex-font-style-tt">D</span>: циклически сдвинуть все строки вниз, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{((i - 2)\bmod n) + 1, j}$$$; </li><li> <span class="tex-font-style-tt">U</span>: циклически сдвинуть все строки вверх, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{(i\bmod n) + 1, j}$$$; </li><li> <span class="tex-font-style-tt">I</span>: заменить перестановку, которую можно прочитать в каждой строке слева направо, на обратную; </li><li> <span class="tex-font-style-tt">C</span>: заменить перестановку, которую можно прочитать в каждом столбце сверху вниз, на обратную. </li></ul><p>Обратной к перестановке $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ является перестановка $$$q_1$$$, $$$q_2$$$, $$$\ldots$$$, $$$q_n$$$, такая что $$$p_{q_i} = i$$$ для каждого $$$1 \leq i \leq n$$$.</p><p>Можно показать, что после любой последовательности операций любая строка и любой столбец матрицы всё ещё будет содержать перестановку чисел $$$1, 2, \ldots, n$$$.</p><p>Вам дано описание исходной матрицы. Нужно совершить $$$m$$$ операций и вывести получившееся состояние матрицы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество тестовых примеров. Далее следует описание $$$t$$$ примеров.</p><p>Первого строка описания каждого примера содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 1000, 1 \leq m \leq 10^5$$$) — размер матрицы и количество операций.</p><p>Каждая из следующих $$$n$$$ строк содержит по $$$n$$$ целых чисел через пробел — элементы матрицы $$$a$$$ ($$$1 \leq a_{i, j} \leq n$$$).</p><p>В последней строке описания записано $$$m$$$ символов, описывающих операции по порядку в формате, описанном выше.</p><p>Сумма всех $$$n$$$ не превосходит $$$1000$$$, а сумма всех $$$m$$$ не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого примера выведите $$$n$$$ строк, по $$$n$$$ чисел в каждой — получившееся состояние матрицы после $$$m$$$ операций.</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 2
1 2 3
2 3 1
3 1 2
DR
3 2
1 2 3
2 3 1
3 1 2
LU
3 1
1 2 3
2 3 1
3 1 2
I
3 1
1 2 3
2 3 1
3 1 2
C
3 16
1 2 3
2 3 1
3 1 2
LDICRUCILDICRUCI
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 1
3 1 2
1 2 3
3 1 2
1 2 3
2 3 1
1 2 3
3 1 2
2 3 1
1 3 2
2 1 3
3 2 1
2 3 1
3 1 2
1 2 3
</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="3e90982bec2d293265c3e045341e868e"/>
<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="5218e2cbbc405c348ab51957b9d1ede47ace8993"/>
<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='3e90982bec2d293265c3e045341e868e'> </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%2F1459%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='3e90982bec2d293265c3e045341e868e'/>
<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/1459">Codeforces Round 691 (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='3e90982bec2d293265c3e045341e868e'/>
<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/1459/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="Сложность">
*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='3e90982bec2d293265c3e045341e868e'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837952"/>
<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='3e90982bec2d293265c3e045341e868e'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837952"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12651" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12666" resourceName="Codeforces Round #691 Editorial (finished)"
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/1459">Задачи</a></li>
<li><a
href="/contest/1459/submit">Отослать</a></li>
<li><a
href="/contest/1459/my">Мои посылки</a></li>
<li><a
href="/contest/1459/status">Статус</a></li>
<li><a
href="/contest/1459/hacks">Взломы</a></li>
<li><a
href="/contest/1459/room/1">Комната</a></li>
<li><a
href="/contest/1459/standings">Положение</a></li>
<li><a
href="/contest/1459/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_89b4e62668e50e87150bbc7f217e739666081d34">
<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>Вам дана квадратная матрица размера $$$n$$$. В каждой строке и каждом столбце этой матрицы записана перестановка чисел $$$1$$$, $$$2$$$, $$$\ldots$$$, $$$n$$$. Пусть $$$a_{i, j}$$$ означает число на пересечении $$$i$$$-й строки и $$$j$$$-го столбца для всех $$$1 \leq i, j \leq n$$$. Строки нумеруются $$$1, \ldots, n$$$ сверху вниз, а столбцы нумеруются $$$1, \ldots, n$$$ слева направо.</p><p>Мы совершаем операции шести типов: </p><ul> <li> <span class="tex-font-style-tt">R</span>: циклически сдвинуть все столбцы вправо, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{i, ((j - 2)\bmod n) + 1}$$$; </li><li> <span class="tex-font-style-tt">L</span>: циклически сдвинуть все столбцы влево, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{i, (j\bmod n) + 1}$$$; </li><li> <span class="tex-font-style-tt">D</span>: циклически сдвинуть все строки вниз, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{((i - 2)\bmod n) + 1, j}$$$; </li><li> <span class="tex-font-style-tt">U</span>: циклически сдвинуть все строки вверх, формально, заменить значение каждого $$$a_{i, j}$$$ на $$$a_{(i\bmod n) + 1, j}$$$; </li><li> <span class="tex-font-style-tt">I</span>: заменить перестановку, которую можно прочитать в каждой строке слева направо, на обратную; </li><li> <span class="tex-font-style-tt">C</span>: заменить перестановку, которую можно прочитать в каждом столбце сверху вниз, на обратную. </li></ul><p>Обратной к перестановке $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ является перестановка $$$q_1$$$, $$$q_2$$$, $$$\ldots$$$, $$$q_n$$$, такая что $$$p_{q_i} = i$$$ для каждого $$$1 \leq i \leq n$$$.</p><p>Можно показать, что после любой последовательности операций любая строка и любой столбец матрицы всё ещё будет содержать перестановку чисел $$$1, 2, \ldots, n$$$.</p><p>Вам дано описание исходной матрицы. Нужно совершить $$$m$$$ операций и вывести получившееся состояние матрицы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество тестовых примеров. Далее следует описание $$$t$$$ примеров.</p><p>Первого строка описания каждого примера содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 1000, 1 \leq m \leq 10^5$$$) — размер матрицы и количество операций.</p><p>Каждая из следующих $$$n$$$ строк содержит по $$$n$$$ целых чисел через пробел — элементы матрицы $$$a$$$ ($$$1 \leq a_{i, j} \leq n$$$).</p><p>В последней строке описания записано $$$m$$$ символов, описывающих операции по порядку в формате, описанном выше.</p><p>Сумма всех $$$n$$$ не превосходит $$$1000$$$, а сумма всех $$$m$$$ не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого примера выведите $$$n$$$ строк, по $$$n$$$ чисел в каждой — получившееся состояние матрицы после $$$m$$$ операций.</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 2
1 2 3
2 3 1
3 1 2
DR
3 2
1 2 3
2 3 1
3 1 2
LU
3 1
1 2 3
2 3 1
3 1 2
I
3 1
1 2 3
2 3 1
3 1 2
C
3 16
1 2 3
2 3 1
3 1 2
LDICRUCILDICRUCI
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 3 1
3 1 2
1 2 3
3 1 2
1 2 3
2 3 1
1 2 3
3 1 2
2 3 1
1 3 2
2 1 3
3 2 1
2 3 1
3 1 2
1 2 3
</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=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:17: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:'8124b5b658a69d34',t:'MTY5NjY2NjY2OC43ODQwMDA='};_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\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "*2700"] | ||
1459F | 1459 | 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>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>Вам дана строка $$$s$$$ из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Вы можете делать преобразование следующего вида:</p><ul><li> выбрать непустую сплошную подстроку $$$s$$$, содержащую одинаковое количество символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>;</li><li> заменить все символы <span class="tex-font-style-tt">0</span> в подстроке на <span class="tex-font-style-tt">1</span>, и наоборот;</li><li> развернуть подстроку. </li></ul><p>Например, рассмотрим $$$s$$$ = <span class="tex-font-style-tt">00111011</span>, и следующее преобразование:</p><ul><li> Выберем в качестве подстроки первые шесть символов: <span class="tex-font-style-tt"><span class="tex-font-style-bf">001110</span>11</span>. Эту подстроку можно выбрать, поскольку в ней количество <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> совпадает. Выбирать подстроки <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">110</span>, или всю строку целиком нельзя.</li><li> Заменим все символы в подстроке на противоположные: <span class="tex-font-style-tt"><span class="tex-font-style-bf">110001</span>11</span>.</li><li> Развернём подстроку: <span class="tex-font-style-tt"><span class="tex-font-style-bf">100011</span>11</span>. </li></ul> <p>Найдите лексикографически минимальную строку, которую можно получить из $$$s$$$ после нуля или более преобразований.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \leq T \leq 5 \cdot 10^5$$$) — количество тестовых примеров. Каждая из следующих $$$T$$$ строк содержит одну непустую последовательность символов — строку $$$s$$$ в соответствующем примере.</p><p>Все строки состоят из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>, и их суммарная длина не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого примера на отдельной строке выведите лексикографически минимальную строку, которую можно получить из $$$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
100101
1100011
10101010
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
010110
0110110
10101010
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере достаточно применить одно преобразование ко всей строке целиком.</p><p>Во втором примере необходимо два преобразования: <span class="tex-font-style-tt"><span class="tex-font-style-bf">011100</span>1</span>, <span class="tex-font-style-tt">011<span class="tex-font-style-bf">0110</span></span>.</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="d475ab91c203d98e558e120611ad474a"/>
<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="5218e2cbbc405c348ab51957b9d1ede47ace8993"/>
<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='d475ab91c203d98e558e120611ad474a'> </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%2F1459%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='d475ab91c203d98e558e120611ad474a'/>
<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/1459">Codeforces Round 691 (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='d475ab91c203d98e558e120611ad474a'/>
<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/1459/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="Сложность">
*3100
</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='d475ab91c203d98e558e120611ad474a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="837953"/>
<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='d475ab91c203d98e558e120611ad474a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="837953"/>
<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/85673" title="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12651" resourceName="Codeforces Round #691, based on ByteDance — Moscow Workshops Online Contest"
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/85750" title="Codeforces Round #691 Editorial (finished)" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12666" resourceName="Codeforces Round #691 Editorial (finished)"
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/1459">Задачи</a></li>
<li><a
href="/contest/1459/submit">Отослать</a></li>
<li><a
href="/contest/1459/my">Мои посылки</a></li>
<li><a
href="/contest/1459/status">Статус</a></li>
<li><a
href="/contest/1459/hacks">Взломы</a></li>
<li><a
href="/contest/1459/room/1">Комната</a></li>
<li><a
href="/contest/1459/standings">Положение</a></li>
<li><a
href="/contest/1459/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_8393dd6c7c82b2c30db7597d520f38a383e4784d">
<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>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>Вам дана строка $$$s$$$ из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Вы можете делать преобразование следующего вида:</p><ul><li> выбрать непустую сплошную подстроку $$$s$$$, содержащую одинаковое количество символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>;</li><li> заменить все символы <span class="tex-font-style-tt">0</span> в подстроке на <span class="tex-font-style-tt">1</span>, и наоборот;</li><li> развернуть подстроку. </li></ul><p>Например, рассмотрим $$$s$$$ = <span class="tex-font-style-tt">00111011</span>, и следующее преобразование:</p><ul><li> Выберем в качестве подстроки первые шесть символов: <span class="tex-font-style-tt"><span class="tex-font-style-bf">001110</span>11</span>. Эту подстроку можно выбрать, поскольку в ней количество <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span> совпадает. Выбирать подстроки <span class="tex-font-style-tt">0</span>, <span class="tex-font-style-tt">110</span>, или всю строку целиком нельзя.</li><li> Заменим все символы в подстроке на противоположные: <span class="tex-font-style-tt"><span class="tex-font-style-bf">110001</span>11</span>.</li><li> Развернём подстроку: <span class="tex-font-style-tt"><span class="tex-font-style-bf">100011</span>11</span>. </li></ul> <p>Найдите лексикографически минимальную строку, которую можно получить из $$$s$$$ после нуля или более преобразований.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \leq T \leq 5 \cdot 10^5$$$) — количество тестовых примеров. Каждая из следующих $$$T$$$ строк содержит одну непустую последовательность символов — строку $$$s$$$ в соответствующем примере.</p><p>Все строки состоят из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>, и их суммарная длина не превосходит $$$5 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого примера на отдельной строке выведите лексикографически минимальную строку, которую можно получить из $$$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
100101
1100011
10101010
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
010110
0110110
10101010
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере достаточно применить одно преобразование ко всей строке целиком.</p><p>Во втором примере необходимо два преобразования: <span class="tex-font-style-tt"><span class="tex-font-style-bf">011100</span>1</span>, <span class="tex-font-style-tt">011<span class="tex-font-style-bf">0110</span></span>.</p><p>В третьем примере строка в результате любого преобразования не меняется.</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:17: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:'8124b5bf8fae3a56',t:'MTY5NjY2NjY3MC4wOTEwMDA='};_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", "\u0416\u0430\u0434\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", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*3100"] | ||
1461A | 1461 | 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$$$. Казалось бы, в этом нет ничего сложного, однако Джо должен был сгенерировать свою строку по следующим правилам:</p><ul> <li> строка может содержать только символы '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' или '<span class="tex-font-style-tt">c</span>'; </li><li> максимальная длина подстроки данной строки, которая является палиндромом, не превосходит $$$k$$$. </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/10d6acb7a5a08122f364198611f17101e3601362.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Строка $$$a$$$ является подстрокой строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца. Например, строки «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">bc</span>», «<span class="tex-font-style-tt">abc</span>» являются подстроками строки «<span class="tex-font-style-tt">abc</span>», а строки «<span class="tex-font-style-tt">ac</span>», «<span class="tex-font-style-tt">ba</span>», «<span class="tex-font-style-tt">cba</span>» — нет.</p><p>Строка называется палиндромом, если она одинаково читается слева направо и справа налево. Например, строки «<span class="tex-font-style-tt">abccba</span>», «<span class="tex-font-style-tt">abbba</span>», «<span class="tex-font-style-tt">aba</span>», «<span class="tex-font-style-tt">abacaba</span>», «<span class="tex-font-style-tt">a</span>» и «<span class="tex-font-style-tt">bacab</span>» — палиндромы, а строки «<span class="tex-font-style-tt">abcbba</span>», «<span class="tex-font-style-tt">abb</span>» и «<span class="tex-font-style-tt">ab</span>» — нет.</p><p>Теперь Джо интересует, как может выглядеть любая подходящая строка. Помогите ему! Можно доказать, что при заданных ограничениях ответ всегда существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10$$$).</p><p>Единственная строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 1\,000$$$) — требуемый размер строки и максимальную длину палиндромной подстроки соответственно.</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 2
4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
aab
acba
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных палиндромной подстрокой с максимальной длиной является подстрока «<span class="tex-font-style-tt">aa</span>». Её длина не превосходит $$$2$$$, а значит она является подходящей.</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="8068356aae99271503b21cd29eebb59b"/>
<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="7be811eb81959d035abc8ce94f9c8dc4388d2cac"/>
<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='8068356aae99271503b21cd29eebb59b'> </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%2F1461%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='8068356aae99271503b21cd29eebb59b'/>
<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/1461">Codeforces Round 689 (Div. 2, based on Zed Code Competition)</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='8068356aae99271503b21cd29eebb59b'/>
<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/1461/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='8068356aae99271503b21cd29eebb59b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="829206"/>
<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='8068356aae99271503b21cd29eebb59b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="829206"/>
<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/85463" title="Codeforces Round #689 (Div. 2), основанный на Zed Code Competition 2020" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12598:12599" 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/85491" title="Разбор Codeforces Round #689 (Div. 2)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12605:12606" 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="//www.youtube.com/watch?v=Ler9YWK4Wag" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12634" resourceName="watch"
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/1461">Задачи</a></li>
<li><a
href="/contest/1461/submit">Отослать</a></li>
<li><a
href="/contest/1461/my">Мои посылки</a></li>
<li><a
href="/contest/1461/status">Статус</a></li>
<li><a
href="/contest/1461/hacks">Взломы</a></li>
<li><a
href="/contest/1461/room/1">Комната</a></li>
<li><a
href="/contest/1461/standings">Положение</a></li>
<li><a
href="/contest/1461/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_72aa80055951722ca14dc68553f6718f729532e0">
<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$$$. Казалось бы, в этом нет ничего сложного, однако Джо должен был сгенерировать свою строку по следующим правилам:</p><ul> <li> строка может содержать только символы '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' или '<span class="tex-font-style-tt">c</span>'; </li><li> максимальная длина подстроки данной строки, которая является палиндромом, не превосходит $$$k$$$. </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/10d6acb7a5a08122f364198611f17101e3601362.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Строка $$$a$$$ является подстрокой строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца. Например, строки «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">bc</span>», «<span class="tex-font-style-tt">abc</span>» являются подстроками строки «<span class="tex-font-style-tt">abc</span>», а строки «<span class="tex-font-style-tt">ac</span>», «<span class="tex-font-style-tt">ba</span>», «<span class="tex-font-style-tt">cba</span>» — нет.</p><p>Строка называется палиндромом, если она одинаково читается слева направо и справа налево. Например, строки «<span class="tex-font-style-tt">abccba</span>», «<span class="tex-font-style-tt">abbba</span>», «<span class="tex-font-style-tt">aba</span>», «<span class="tex-font-style-tt">abacaba</span>», «<span class="tex-font-style-tt">a</span>» и «<span class="tex-font-style-tt">bacab</span>» — палиндромы, а строки «<span class="tex-font-style-tt">abcbba</span>», «<span class="tex-font-style-tt">abb</span>» и «<span class="tex-font-style-tt">ab</span>» — нет.</p><p>Теперь Джо интересует, как может выглядеть любая подходящая строка. Помогите ему! Можно доказать, что при заданных ограничениях ответ всегда существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10$$$).</p><p>Единственная строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 1\,000$$$) — требуемый размер строки и максимальную длину палиндромной подстроки соответственно.</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 2
4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
aab
acba
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных палиндромной подстрокой с максимальной длиной является подстрока «<span class="tex-font-style-tt">aa</span>». Её длина не превосходит $$$2$$$, а значит она является подходящей.</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:17: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:'8124b5c7dc677b7b',t:'MTY5NjY2NjY3MS40NTMwMDA='};_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", "\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", "*800"] | ||
1461B | 1461 | 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 \times m$$$, состоящей из символов «<span class="tex-font-style-tt">*</span>» и «<span class="tex-font-style-tt">.</span>».</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/de6f4ca24249c636f20e413d172d76d941856a43.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Для того, чтобы найти все ели, сперва дадим определение ели в матрице. Набор ячеек из матрицы называется елью с высотой $$$k$$$ и вершиной в точке $$$(x, y)$$$, если:</p><ul> <li> Все ячейки из набора являются символами «<span class="tex-font-style-tt">*</span>». </li><li> Для всех $$$1 \le i \le k$$$ все ячейки с номером строки $$$x+i-1$$$ и с номерами столбцов в диапазоне $$$[y - i + 1, y + i - 1]$$$ должны принадлежать набору. Все остальные ячейки не могут принадлежать набору. </li></ul> <p>Примеры корректных и некорректных елок:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2eb9d90211d4d63f383e27062cacaac1cdcb9b64.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Теперь Рику стало интересно, сколько елей существует в его матрице $$$n \times m$$$. Помогите ему ответить на этот вопрос.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10$$$).</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 500$$$) — размер матрицы.</p><p>Следующие $$$n$$$ строк каждого из наборов содержат по $$$m$$$ символов $$$c_{i, j}$$$ — описание матрицы. Гарантируется, что $$$c_{i, j}$$$ является либо символом «<span class="tex-font-style-tt">.</span>», либо символом «<span class="tex-font-style-tt">*</span>».</p><p>Гарантируется, что сумма $$$n \cdot m$$$ по всем тестовым наборам не превосходит $$$500^2$$$ ($$$\sum n \cdot m \le 500^2$$$).</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
2 3
.*.
***
2 3
.*.
**.
4 5
.***.
*****
*****
*.*.*
5 7
..*.*..
.*****.
*******
.*****.
..*.*..
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
3
23
34
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере первая ель имеет вершину в точке $$$(1, 2)$$$ и высоту $$$2$$$, вторая ель имеет вершину в точке $$$(1, 2)$$$ и высоту $$$1$$$, третья ель имеет вершину в точке $$$(2, 1)$$$ и высоту $$$1$$$, четвертая ель имеет вершину в точке $$$(2, 2)$$$ и высоту $$$1$$$, пятая ель имеет вершину в точке $$$(2, 3)$$$ и высоту $$$1$$$.</p><p>Во втором тестовом примере первая ель имеет вершину в точке $$$(1, 2)$$$ и высоту $$$1$$$, вторая ель имеет вершину в точке $$$(2, 1)$$$ и высоту $$$1$$$, третья ель имеет вершину в точке $$$(2, 2)$$$ и высоту $$$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="323e5044ad99d8590ec537c6e9152acd"/>
<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="7be811eb81959d035abc8ce94f9c8dc4388d2cac"/>
<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='323e5044ad99d8590ec537c6e9152acd'> </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%2F1461%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='323e5044ad99d8590ec537c6e9152acd'/>
<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/1461">Codeforces Round 689 (Div. 2, based on Zed Code Competition)</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='323e5044ad99d8590ec537c6e9152acd'/>
<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/1461/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='323e5044ad99d8590ec537c6e9152acd'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="829207"/>
<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='323e5044ad99d8590ec537c6e9152acd'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="829207"/>
<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/85463" title="Codeforces Round #689 (Div. 2), основанный на Zed Code Competition 2020" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12598:12599" 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/85491" title="Разбор Codeforces Round #689 (Div. 2)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12605:12606" 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="//www.youtube.com/watch?v=Ler9YWK4Wag" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12634" resourceName="watch"
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/1461">Задачи</a></li>
<li><a
href="/contest/1461/submit">Отослать</a></li>
<li><a
href="/contest/1461/my">Мои посылки</a></li>
<li><a
href="/contest/1461/status">Статус</a></li>
<li><a
href="/contest/1461/hacks">Взломы</a></li>
<li><a
href="/contest/1461/room/1">Комната</a></li>
<li><a
href="/contest/1461/standings">Положение</a></li>
<li><a
href="/contest/1461/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_584edf38374dba7e03705b29da6cf8a72ad2df35">
<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 \times m$$$, состоящей из символов «<span class="tex-font-style-tt">*</span>» и «<span class="tex-font-style-tt">.</span>».</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/de6f4ca24249c636f20e413d172d76d941856a43.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Для того, чтобы найти все ели, сперва дадим определение ели в матрице. Набор ячеек из матрицы называется елью с высотой $$$k$$$ и вершиной в точке $$$(x, y)$$$, если:</p><ul> <li> Все ячейки из набора являются символами «<span class="tex-font-style-tt">*</span>». </li><li> Для всех $$$1 \le i \le k$$$ все ячейки с номером строки $$$x+i-1$$$ и с номерами столбцов в диапазоне $$$[y - i + 1, y + i - 1]$$$ должны принадлежать набору. Все остальные ячейки не могут принадлежать набору. </li></ul> <p>Примеры корректных и некорректных елок:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2eb9d90211d4d63f383e27062cacaac1cdcb9b64.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Теперь Рику стало интересно, сколько елей существует в его матрице $$$n \times m$$$. Помогите ему ответить на этот вопрос.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 10$$$).</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 500$$$) — размер матрицы.</p><p>Следующие $$$n$$$ строк каждого из наборов содержат по $$$m$$$ символов $$$c_{i, j}$$$ — описание матрицы. Гарантируется, что $$$c_{i, j}$$$ является либо символом «<span class="tex-font-style-tt">.</span>», либо символом «<span class="tex-font-style-tt">*</span>».</p><p>Гарантируется, что сумма $$$n \cdot m$$$ по всем тестовым наборам не превосходит $$$500^2$$$ ($$$\sum n \cdot m \le 500^2$$$).</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
2 3
.*.
***
2 3
.*.
**.
4 5
.***.
*****
*****
*.*.*
5 7
..*.*..
.*****.
*******
.*****.
..*.*..
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
3
23
34
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере первая ель имеет вершину в точке $$$(1, 2)$$$ и высоту $$$2$$$, вторая ель имеет вершину в точке $$$(1, 2)$$$ и высоту $$$1$$$, третья ель имеет вершину в точке $$$(2, 1)$$$ и высоту $$$1$$$, четвертая ель имеет вершину в точке $$$(2, 2)$$$ и высоту $$$1$$$, пятая ель имеет вершину в точке $$$(2, 3)$$$ и высоту $$$1$$$.</p><p>Во втором тестовом примере первая ель имеет вершину в точке $$$(1, 2)$$$ и высоту $$$1$$$, вторая ель имеет вершину в точке $$$(2, 1)$$$ и высоту $$$1$$$, третья ель имеет вершину в точке $$$(2, 2)$$$ и высоту $$$1$$$.</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:17: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:'8124b5d04eda00b0',t:'MTY5NjY2NjY3Mi43NDUwMDA='};_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", "\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1400"] | ||
1461C | 1461 | 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$$$ длины $$$n$$$.</p><p>Перестановкой длины $$$n$$$ является массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$ в произвольном порядке. Например, $$$[2,3,1,5,4]$$$ — перестановка, но $$$[1,2,2]$$$ — не перестановка ($$$2$$$ встречается в массиве дважды) и $$$[1,3,4]$$$ тоже не перестановка ($$$n=3$$$, но в массиве встречается $$$4$$$).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/dbe13c0f7e97d640bfabd11556af2c86891af614.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Над перестановкой Рона ставится $$$m$$$ экспериментов следующего вида: ($$$r_i$$$, $$$p_i$$$). Это обозначает, что элементы в диапазоне $$$[1, r_i]$$$ (другими словами, префикс длины $$$r_i$$$) будут отсортированы в возрастающем порядке с вероятностью $$$p_i$$$. Все эксперименты проводятся в том же порядке, в котором задаются во входных данных.</p><p>Для примера рассмотрим перестановку $$$[4, 2, 1, 5, 3]$$$ и эксперимент ($$$3, 0.6$$$). После такого эксперимента с вероятностью $$$60\%$$$ перестановка примет вид $$$[1, 2, 4, 5, 3]$$$, а с вероятностью $$$40\%$$$ останется без изменений.</p><p>Вам требуется определить, с какой вероятностью перестановка станет полностью отсортированной по возрастанию после $$$m$$$ экспериментов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$).</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$m$$$ $$$(1 \le n, m \le 10^5)$$$ — количество элементов в перестановке и количество экспериментов.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le n)$$$ — описание перестановки.</p><p>Каждая из следующих $$$m$$$ входных данных содержат целое число $$$r_i$$$ и вещественное число $$$p_i$$$ $$$(1 \le r_i \le n, 0 \le p_i \le 1)$$$ — длина префикса массива и вероятность, с которой он отсортируется. Все вероятности даны с точностью не более $$$6$$$ знаков после запятой.</p><p>Гарантируется, что сумма $$$n$$$ и сумма $$$m$$$ не превосходят $$$10^5$$$ ($$$\sum n, \sum m \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное число — вероятность, что после всех экспериментов перестановка окажется отсортированной. Ваш ответ будет считаться правильным, если его абсолютная или относительная ошибка не превосходит $$$10^{-6}$$$.</p><p>Формально, пусть ваш ответ равен $$$a$$$, а ответ жюри равен $$$b$$$. Ваш ответ будет зачтен, если и только если $$$\frac{|a - b|}{\max{(1, |b|)}} \le 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>
4
4 3
4 3 2 1
1 0.3
3 1
4 0.6
5 3
4 2 1 3 5
3 0.8
4 0.6
5 0.3
6 5
1 3 2 4 5 6
4 0.9
5 0.3
2 0.4
6 0.7
3 0.5
4 2
1 2 3 4
2 0.5
4 0.1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0.600000
0.720000
0.989500
1.000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных можно показать, что только от того, выполнится ли сортировка с помощью правила $$$(4, 0.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="4fa9d1bec084fa0beda68f1443876696"/>
<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="7be811eb81959d035abc8ce94f9c8dc4388d2cac"/>
<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='4fa9d1bec084fa0beda68f1443876696'> </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%2F1461%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='4fa9d1bec084fa0beda68f1443876696'/>
<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/1461">Codeforces Round 689 (Div. 2, based on Zed Code Competition)</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='4fa9d1bec084fa0beda68f1443876696'/>
<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/1461/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="Сложность">
*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='4fa9d1bec084fa0beda68f1443876696'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="829208"/>
<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='4fa9d1bec084fa0beda68f1443876696'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="829208"/>
<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/85463" title="Codeforces Round #689 (Div. 2), основанный на Zed Code Competition 2020" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12598:12599" 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/85491" title="Разбор Codeforces Round #689 (Div. 2)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12605:12606" 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="//www.youtube.com/watch?v=Ler9YWK4Wag" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12634" resourceName="watch"
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/1461">Задачи</a></li>
<li><a
href="/contest/1461/submit">Отослать</a></li>
<li><a
href="/contest/1461/my">Мои посылки</a></li>
<li><a
href="/contest/1461/status">Статус</a></li>
<li><a
href="/contest/1461/hacks">Взломы</a></li>
<li><a
href="/contest/1461/room/1">Комната</a></li>
<li><a
href="/contest/1461/standings">Положение</a></li>
<li><a
href="/contest/1461/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_9cbc8d976f3f529db751f54fd68cb29179f00b43">
<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$$$ длины $$$n$$$.</p><p>Перестановкой длины $$$n$$$ является массив, состоящий из $$$n$$$ различных целых чисел от $$$1$$$ до $$$n$$$ в произвольном порядке. Например, $$$[2,3,1,5,4]$$$ — перестановка, но $$$[1,2,2]$$$ — не перестановка ($$$2$$$ встречается в массиве дважды) и $$$[1,3,4]$$$ тоже не перестановка ($$$n=3$$$, но в массиве встречается $$$4$$$).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/dbe13c0f7e97d640bfabd11556af2c86891af614.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Над перестановкой Рона ставится $$$m$$$ экспериментов следующего вида: ($$$r_i$$$, $$$p_i$$$). Это обозначает, что элементы в диапазоне $$$[1, r_i]$$$ (другими словами, префикс длины $$$r_i$$$) будут отсортированы в возрастающем порядке с вероятностью $$$p_i$$$. Все эксперименты проводятся в том же порядке, в котором задаются во входных данных.</p><p>Для примера рассмотрим перестановку $$$[4, 2, 1, 5, 3]$$$ и эксперимент ($$$3, 0.6$$$). После такого эксперимента с вероятностью $$$60\%$$$ перестановка примет вид $$$[1, 2, 4, 5, 3]$$$, а с вероятностью $$$40\%$$$ останется без изменений.</p><p>Вам требуется определить, с какой вероятностью перестановка станет полностью отсортированной по возрастанию после $$$m$$$ экспериментов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$).</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$m$$$ $$$(1 \le n, m \le 10^5)$$$ — количество элементов в перестановке и количество экспериментов.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le n)$$$ — описание перестановки.</p><p>Каждая из следующих $$$m$$$ входных данных содержат целое число $$$r_i$$$ и вещественное число $$$p_i$$$ $$$(1 \le r_i \le n, 0 \le p_i \le 1)$$$ — длина префикса массива и вероятность, с которой он отсортируется. Все вероятности даны с точностью не более $$$6$$$ знаков после запятой.</p><p>Гарантируется, что сумма $$$n$$$ и сумма $$$m$$$ не превосходят $$$10^5$$$ ($$$\sum n, \sum m \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное число — вероятность, что после всех экспериментов перестановка окажется отсортированной. Ваш ответ будет считаться правильным, если его абсолютная или относительная ошибка не превосходит $$$10^{-6}$$$.</p><p>Формально, пусть ваш ответ равен $$$a$$$, а ответ жюри равен $$$b$$$. Ваш ответ будет зачтен, если и только если $$$\frac{|a - b|}{\max{(1, |b|)}} \le 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>
4
4 3
4 3 2 1
1 0.3
3 1
4 0.6
5 3
4 2 1 3 5
3 0.8
4 0.6
5 0.3
6 5
1 3 2 4 5 6
4 0.9
5 0.3
2 0.4
6 0.7
3 0.5
4 2
1 2 3 4
2 0.5
4 0.1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0.600000
0.720000
0.989500
1.000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных можно показать, что только от того, выполнится ли сортировка с помощью правила $$$(4, 0.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:17: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:'8124b5d868b99d64',t:'MTY5NjY2NjY3NC4wNDEwMDA='};_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.", "\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", "\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", "*1500"] | ||
1461D | 1461 | 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$$$ длины $$$n$$$ и решил протестировать, насколько он красивый.</p><p>Массив пройдет $$$i$$$-й тест на красоту, если существует способ из изначального массива путем некоторого (возможно, нулевого) количества операций разреза получить массив с суммой элементов, равной $$$s_i$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fdeacd91d145812a0cf9b927a977b59f14289198.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Операция разреза массива происходит следующим образом: </p><ul> <li> Вычисляется $$$mid = \lfloor\frac{max(array) + min(array)}{2}\rfloor$$$, где $$$max$$$ и $$$min$$$ — это функции нахождения максимального и минимального элемента массива. Иными словами, $$$mid$$$ равно сумме максимального и минимального элементов $$$array$$$, деленной на $$$2$$$ с округлением вниз. </li><li> Далее массив разделяется на две части $$$\mathit{left}$$$ и $$$right$$$. В $$$\mathit{left}$$$ попадают все элементы массива, которые имеют значение меньшее либо равное $$$mid$$$, а в массив $$$right$$$ попадают все элементы, которые больше $$$mid$$$. Элементы в $$$\mathit{left}$$$ и $$$right$$$ сохраняют свой относительный порядок, который был в $$$array$$$. </li><li> Третьим шагом выбирается, какой из массивов $$$\mathit{left}$$$ или $$$right$$$ мы хотим оставить. Выбранный массив заменит собой текущий, а другой навсегда удалится. </li></ul><p>Вам требуется помочь Майку определить результаты $$$q$$$ тестов на красоту.</p><p>Заметьте, что вы тестируете красоту массива $$$a$$$, поэтому вы начинаете каждый тест на красоту с изначальным (заданным) массивом $$$a$$$. Таким образом, первый разрез (если он необходим) всегда совершается над массивом $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$).</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$q$$$ $$$(1 \le n, q \le 10^5)$$$ — длину массива $$$a$$$ и количество тестов на красоту соответственно.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, ..., a_n$$$ $$$(1 \le a_i \le 10^6)$$$ — описание массива $$$a$$$.</p><p>Следующие $$$q$$$ строк каждого набора входных данных содержат по одному целому числу $$$s_i$$$ $$$(1 \le s_i \le 10^9)$$$ — сумму элементов, которую хочет добиться Майк в $$$i$$$-м тесте на красоту.</p><p>Гарантируется, что сумма $$$n$$$ и сумма $$$q$$$ не превосходят $$$10^5$$$ ($$$\sum n, \sum q \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$q$$$ строк, каждая из которых должна содержать «<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>
2
5 5
1 2 3 4 5
1
8
9
12
6
5 5
3 1 3 1 3
1
2
3
9
11
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
No
Yes
No
Yes
No
Yes
No
Yes
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-bf">Объяснение первого набора входных данных:</span></p><ol><li> Получить массив с суммой $$$s_1 = 1$$$ мы можем следующим способом:<p> 1.1 $$$a = [1, 2, 3, 4, 5]$$$, $$$mid = \frac{1+5}{2} = 3$$$, $$$\mathit{left} = [1, 2, 3]$$$, $$$right = [4, 5]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$.</p><p> 1.2 $$$a = [1, 2, 3]$$$, $$$mid = \frac{1+3}{2} = 2$$$, $$$\mathit{left} = [1, 2]$$$, $$$right = [3]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$.</p><p> 1.3 $$$a = [1, 2]$$$, $$$mid = \frac{1+2}{2} = 1$$$, $$$\mathit{left} = [1]$$$, $$$right = [2]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$ с суммой, равной $$$1$$$.</p></li><li> Массив с суммой $$$s_2 = 8$$$ можно показать, что получить невозможно. </li><li> Получить массив с суммой $$$s_3 = 9$$$ мы можем следующим способом:<p> 3.1 $$$a = [1, 2, 3, 4, 5]$$$, $$$mid = \frac{1+5}{2} = 3$$$, $$$\mathit{left} = [1, 2, 3]$$$, $$$right = [4, 5]$$$. Мы выбираем оставить массив $$$right$$$ с суммой, равной $$$9$$$. </p></li><li> Массив с суммой $$$s_4 = 12$$$ можно показать, что получить невозможно. </li><li> Получить массив с суммой $$$s_5 = 6$$$ мы можем следующим способом:<p> 5.1 $$$a = [1, 2, 3, 4, 5]$$$, $$$mid = \frac{1+5}{2} = 3$$$, $$$\mathit{left} = [1, 2, 3]$$$, $$$right = [4, 5]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$ с суммой, равной $$$6$$$. </p></li></ol><p><span class="tex-font-style-bf">Объяснение второго набора входных данных:</span> </p><ol> <li> Массив с суммой $$$s_1 = 1$$$ можно показать, что получить невозможно. </li><li> Получить массив с суммой $$$s_2 = 2$$$ мы можем следующим способом:<p> 2.1 $$$a = [3, 1, 3, 1, 3]$$$, $$$mid = \frac{1+3}{2} = 2$$$, $$$\mathit{left} = [1, 1]$$$, $$$right = [3, 3, 3]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$ с суммой $$$2$$$. </p></li><li> Массив с суммой $$$s_3 = 3$$$ можно показать, что получить невозможно. </li><li> Получить массив с суммой $$$s_4 = 9$$$ мы можем следующим способом:<p> 4.1 $$$a = [3, 1, 3, 1, 3]$$$, $$$mid = \frac{1+3}{2} = 2$$$, $$$\mathit{left} = [1, 1]$$$, $$$right = [3, 3, 3]$$$. Мы выбираем оставить массив $$$right$$$ с суммой $$$9$$$.</p></li><li> Мы можем получить $$$s_5 = 11$$$ без операций разреза, потому что изначальная сумма уже была равна $$$11$$$.</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="b1a5ad2dde678ce50d4ca5d6d121f730"/>
<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="7be811eb81959d035abc8ce94f9c8dc4388d2cac"/>
<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='b1a5ad2dde678ce50d4ca5d6d121f730'> </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%2F1461%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='b1a5ad2dde678ce50d4ca5d6d121f730'/>
<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/1461">Codeforces Round 689 (Div. 2, based on Zed Code Competition)</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='b1a5ad2dde678ce50d4ca5d6d121f730'/>
<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/1461/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="Сложность">
*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='b1a5ad2dde678ce50d4ca5d6d121f730'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="829209"/>
<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='b1a5ad2dde678ce50d4ca5d6d121f730'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="829209"/>
<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/85463" title="Codeforces Round #689 (Div. 2), основанный на Zed Code Competition 2020" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12598:12599" 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/85491" title="Разбор Codeforces Round #689 (Div. 2)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12605:12606" 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="//www.youtube.com/watch?v=Ler9YWK4Wag" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12634" resourceName="watch"
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/1461">Задачи</a></li>
<li><a
href="/contest/1461/submit">Отослать</a></li>
<li><a
href="/contest/1461/my">Мои посылки</a></li>
<li><a
href="/contest/1461/status">Статус</a></li>
<li><a
href="/contest/1461/hacks">Взломы</a></li>
<li><a
href="/contest/1461/room/1">Комната</a></li>
<li><a
href="/contest/1461/standings">Положение</a></li>
<li><a
href="/contest/1461/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_ab65ea398ca36864236b28244275190379ebee9f">
<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$$$ длины $$$n$$$ и решил протестировать, насколько он красивый.</p><p>Массив пройдет $$$i$$$-й тест на красоту, если существует способ из изначального массива путем некоторого (возможно, нулевого) количества операций разреза получить массив с суммой элементов, равной $$$s_i$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fdeacd91d145812a0cf9b927a977b59f14289198.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Операция разреза массива происходит следующим образом: </p><ul> <li> Вычисляется $$$mid = \lfloor\frac{max(array) + min(array)}{2}\rfloor$$$, где $$$max$$$ и $$$min$$$ — это функции нахождения максимального и минимального элемента массива. Иными словами, $$$mid$$$ равно сумме максимального и минимального элементов $$$array$$$, деленной на $$$2$$$ с округлением вниз. </li><li> Далее массив разделяется на две части $$$\mathit{left}$$$ и $$$right$$$. В $$$\mathit{left}$$$ попадают все элементы массива, которые имеют значение меньшее либо равное $$$mid$$$, а в массив $$$right$$$ попадают все элементы, которые больше $$$mid$$$. Элементы в $$$\mathit{left}$$$ и $$$right$$$ сохраняют свой относительный порядок, который был в $$$array$$$. </li><li> Третьим шагом выбирается, какой из массивов $$$\mathit{left}$$$ или $$$right$$$ мы хотим оставить. Выбранный массив заменит собой текущий, а другой навсегда удалится. </li></ul><p>Вам требуется помочь Майку определить результаты $$$q$$$ тестов на красоту.</p><p>Заметьте, что вы тестируете красоту массива $$$a$$$, поэтому вы начинаете каждый тест на красоту с изначальным (заданным) массивом $$$a$$$. Таким образом, первый разрез (если он необходим) всегда совершается над массивом $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Каждый тест содержит один или несколько наборов входных данных. В первой строке записано количество наборов входных данных $$$t$$$ ($$$1 \le t \le 100$$$).</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$q$$$ $$$(1 \le n, q \le 10^5)$$$ — длину массива $$$a$$$ и количество тестов на красоту соответственно.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, ..., a_n$$$ $$$(1 \le a_i \le 10^6)$$$ — описание массива $$$a$$$.</p><p>Следующие $$$q$$$ строк каждого набора входных данных содержат по одному целому числу $$$s_i$$$ $$$(1 \le s_i \le 10^9)$$$ — сумму элементов, которую хочет добиться Майк в $$$i$$$-м тесте на красоту.</p><p>Гарантируется, что сумма $$$n$$$ и сумма $$$q$$$ не превосходят $$$10^5$$$ ($$$\sum n, \sum q \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите $$$q$$$ строк, каждая из которых должна содержать «<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>
2
5 5
1 2 3 4 5
1
8
9
12
6
5 5
3 1 3 1 3
1
2
3
9
11
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
No
Yes
No
Yes
No
Yes
No
Yes
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p><span class="tex-font-style-bf">Объяснение первого набора входных данных:</span></p><ol><li> Получить массив с суммой $$$s_1 = 1$$$ мы можем следующим способом:<p> 1.1 $$$a = [1, 2, 3, 4, 5]$$$, $$$mid = \frac{1+5}{2} = 3$$$, $$$\mathit{left} = [1, 2, 3]$$$, $$$right = [4, 5]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$.</p><p> 1.2 $$$a = [1, 2, 3]$$$, $$$mid = \frac{1+3}{2} = 2$$$, $$$\mathit{left} = [1, 2]$$$, $$$right = [3]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$.</p><p> 1.3 $$$a = [1, 2]$$$, $$$mid = \frac{1+2}{2} = 1$$$, $$$\mathit{left} = [1]$$$, $$$right = [2]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$ с суммой, равной $$$1$$$.</p></li><li> Массив с суммой $$$s_2 = 8$$$ можно показать, что получить невозможно. </li><li> Получить массив с суммой $$$s_3 = 9$$$ мы можем следующим способом:<p> 3.1 $$$a = [1, 2, 3, 4, 5]$$$, $$$mid = \frac{1+5}{2} = 3$$$, $$$\mathit{left} = [1, 2, 3]$$$, $$$right = [4, 5]$$$. Мы выбираем оставить массив $$$right$$$ с суммой, равной $$$9$$$. </p></li><li> Массив с суммой $$$s_4 = 12$$$ можно показать, что получить невозможно. </li><li> Получить массив с суммой $$$s_5 = 6$$$ мы можем следующим способом:<p> 5.1 $$$a = [1, 2, 3, 4, 5]$$$, $$$mid = \frac{1+5}{2} = 3$$$, $$$\mathit{left} = [1, 2, 3]$$$, $$$right = [4, 5]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$ с суммой, равной $$$6$$$. </p></li></ol><p><span class="tex-font-style-bf">Объяснение второго набора входных данных:</span> </p><ol> <li> Массив с суммой $$$s_1 = 1$$$ можно показать, что получить невозможно. </li><li> Получить массив с суммой $$$s_2 = 2$$$ мы можем следующим способом:<p> 2.1 $$$a = [3, 1, 3, 1, 3]$$$, $$$mid = \frac{1+3}{2} = 2$$$, $$$\mathit{left} = [1, 1]$$$, $$$right = [3, 3, 3]$$$. Мы выбираем оставить массив $$$\mathit{left}$$$ с суммой $$$2$$$. </p></li><li> Массив с суммой $$$s_3 = 3$$$ можно показать, что получить невозможно. </li><li> Получить массив с суммой $$$s_4 = 9$$$ мы можем следующим способом:<p> 4.1 $$$a = [3, 1, 3, 1, 3]$$$, $$$mid = \frac{1+3}{2} = 2$$$, $$$\mathit{left} = [1, 1]$$$, $$$right = [3, 3, 3]$$$. Мы выбираем оставить массив $$$right$$$ с суммой $$$9$$$.</p></li><li> Мы можем получить $$$s_5 = 11$$$ без операций разреза, потому что изначальная сумма уже была равна $$$11$$$.</li></ol></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:17: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:'8124b5e05fc59d3a',t:'MTY5NjY2NjY3NS4zMzEwMDA='};_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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\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", "*1600"] | ||
1461E | 1461 | 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>Джон очень успешно обосновался на своей новой работе в офисе. Но Джон не любит сидеть без дела, пока его код компилируется, поэтому он сразу же нашел себе достаточно интересное занятие, которое заключается в поддержании уровня воды в кулере, который используют другие зебры.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ac2268109fcd066c50c451f3c1b332ab01f46a46.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Изначально в кулере находится ровно $$$k$$$ литров воды. Джон решил, что уровень воды всегда должен быть не менее $$$l$$$ литров и не более $$$r$$$ литров. Джон будет находиться в офисе ровно $$$t$$$ дней. Он знает, что каждый день из кулера будут выпивать ровно $$$x$$$ литров воды. Джон перед началом каждого дня может налить в кулер ровно $$$y$$$ литров воды. При этом в любой момент времени количество воды в кулере должно находиться в диапазоне $$$[l, r]$$$.</p><p>Теперь Джону стало интересно, сможет ли он в течение $$$t$$$ дней поддерживать количество воды в кулере. Помогите ему ответить на этот вопрос!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит шесть целых чисел $$$k$$$, $$$l$$$, $$$r$$$, $$$t$$$, $$$x$$$ и $$$y$$$ ($$$1 \le l \le k \le r \le 10^{18}; 1 \le t \le 10^{18}; 1 \le x \le 10^6; 1 \le y \le 10^{18}$$$) — изначальное количество воды, требуемый диапазон, количество дней, ежедневные потери воды и допустимое добавляемое количество воды соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">Yes</span>», если Джон сможет поддерживать уровень воды в течение $$$t$$$ дней, и «<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>
8 1 10 2 6 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8 1 10 2 6 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
9 1 10 9 2 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
20 15 25 3 5 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере Джон не может увеличить запас воды в начале первого дня, так как он превысит лимит $$$r$$$. Поэтому после первого дня в кулере будет $$$2$$$ литра. Далее Джон увеличивает запас на $$$4$$$ литра, однако теряет $$$6$$$ литров. В итоге у Джона останется $$$0$$$ литров воды, то есть объём не будет в диапазоне $$$[1, 10]$$$.</p><p>Во втором тестовом примере после первого дня у Джона останется $$$2$$$ литра воды. Далее, в начале второго дня он добавит $$$5$$$ литров, а потом объём воды уменьшится на $$$6$$$ литров. В итоге у Джона останется $$$1$$$ литр воды, что входит в диапазон $$$[1, 10]$$$.</p><p>В третьем тестовом примере после первого дня у Джона останется $$$7$$$ литров воды, после второго — $$$5$$$ литров, после четвёртого — $$$1$$$ литр. Далее, в начале пятого дня Джон добавит $$$9$$$ литров, а после потеряет $$$2$$$ литра. Значит, после пятого дня у него останется $$$8$$$ литров. Далее, каждый день уровень воды будет понижаться на $$$2$$$ литра, в итоге после восьмого дня у Джона останется $$$2$$$ литра воды, а после девятого — $$$0$$$ литров. $$$0$$$ не входит в диапазон $$$[1, 10]$$$, поэтому ответ «<span class="tex-font-style-tt">No</span>».</p><p>В четвёртом тестовом примере после первого дня у Джона останется $$$15$$$ литров воды. В начале второго дня он добавит $$$7$$$ литров, а после потеряет $$$5$$$, а значит после второго дня у него останется $$$17$$$ литров воды. В начале третьего дня он добавит $$$7$$$ литров воды, а после потеряет $$$5$$$, значит после третьего дня у него останется $$$19$$$ литров воды. $$$19$$$ входит в диапазон $$$[15, 25]$$$, поэтому ответ «<span class="tex-font-style-tt">Yes</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="98d9f46f00b6bf70c02559f6e6428f6d"/>
<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="7be811eb81959d035abc8ce94f9c8dc4388d2cac"/>
<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='98d9f46f00b6bf70c02559f6e6428f6d'> </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%2F1461%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='98d9f46f00b6bf70c02559f6e6428f6d'/>
<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/1461">Codeforces Round 689 (Div. 2, based on Zed Code Competition)</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='98d9f46f00b6bf70c02559f6e6428f6d'/>
<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/1461/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="Сложность">
*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='98d9f46f00b6bf70c02559f6e6428f6d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="829210"/>
<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='98d9f46f00b6bf70c02559f6e6428f6d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="829210"/>
<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/85463" title="Codeforces Round #689 (Div. 2), основанный на Zed Code Competition 2020" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12598:12599" 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/85491" title="Разбор Codeforces Round #689 (Div. 2)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12605:12606" 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="//www.youtube.com/watch?v=Ler9YWK4Wag" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12634" resourceName="watch"
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/1461">Задачи</a></li>
<li><a
href="/contest/1461/submit">Отослать</a></li>
<li><a
href="/contest/1461/my">Мои посылки</a></li>
<li><a
href="/contest/1461/status">Статус</a></li>
<li><a
href="/contest/1461/hacks">Взломы</a></li>
<li><a
href="/contest/1461/room/1">Комната</a></li>
<li><a
href="/contest/1461/standings">Положение</a></li>
<li><a
href="/contest/1461/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_77354fbf2bd6f99d6dd16535686dd86d718e04f3">
<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>Джон очень успешно обосновался на своей новой работе в офисе. Но Джон не любит сидеть без дела, пока его код компилируется, поэтому он сразу же нашел себе достаточно интересное занятие, которое заключается в поддержании уровня воды в кулере, который используют другие зебры.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ac2268109fcd066c50c451f3c1b332ab01f46a46.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Изначально в кулере находится ровно $$$k$$$ литров воды. Джон решил, что уровень воды всегда должен быть не менее $$$l$$$ литров и не более $$$r$$$ литров. Джон будет находиться в офисе ровно $$$t$$$ дней. Он знает, что каждый день из кулера будут выпивать ровно $$$x$$$ литров воды. Джон перед началом каждого дня может налить в кулер ровно $$$y$$$ литров воды. При этом в любой момент времени количество воды в кулере должно находиться в диапазоне $$$[l, r]$$$.</p><p>Теперь Джону стало интересно, сможет ли он в течение $$$t$$$ дней поддерживать количество воды в кулере. Помогите ему ответить на этот вопрос!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит шесть целых чисел $$$k$$$, $$$l$$$, $$$r$$$, $$$t$$$, $$$x$$$ и $$$y$$$ ($$$1 \le l \le k \le r \le 10^{18}; 1 \le t \le 10^{18}; 1 \le x \le 10^6; 1 \le y \le 10^{18}$$$) — изначальное количество воды, требуемый диапазон, количество дней, ежедневные потери воды и допустимое добавляемое количество воды соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">Yes</span>», если Джон сможет поддерживать уровень воды в течение $$$t$$$ дней, и «<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>
8 1 10 2 6 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8 1 10 2 6 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
9 1 10 9 2 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
20 15 25 3 5 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере Джон не может увеличить запас воды в начале первого дня, так как он превысит лимит $$$r$$$. Поэтому после первого дня в кулере будет $$$2$$$ литра. Далее Джон увеличивает запас на $$$4$$$ литра, однако теряет $$$6$$$ литров. В итоге у Джона останется $$$0$$$ литров воды, то есть объём не будет в диапазоне $$$[1, 10]$$$.</p><p>Во втором тестовом примере после первого дня у Джона останется $$$2$$$ литра воды. Далее, в начале второго дня он добавит $$$5$$$ литров, а потом объём воды уменьшится на $$$6$$$ литров. В итоге у Джона останется $$$1$$$ литр воды, что входит в диапазон $$$[1, 10]$$$.</p><p>В третьем тестовом примере после первого дня у Джона останется $$$7$$$ литров воды, после второго — $$$5$$$ литров, после четвёртого — $$$1$$$ литр. Далее, в начале пятого дня Джон добавит $$$9$$$ литров, а после потеряет $$$2$$$ литра. Значит, после пятого дня у него останется $$$8$$$ литров. Далее, каждый день уровень воды будет понижаться на $$$2$$$ литра, в итоге после восьмого дня у Джона останется $$$2$$$ литра воды, а после девятого — $$$0$$$ литров. $$$0$$$ не входит в диапазон $$$[1, 10]$$$, поэтому ответ «<span class="tex-font-style-tt">No</span>».</p><p>В четвёртом тестовом примере после первого дня у Джона останется $$$15$$$ литров воды. В начале второго дня он добавит $$$7$$$ литров, а после потеряет $$$5$$$, а значит после второго дня у него останется $$$17$$$ литров воды. В начале третьего дня он добавит $$$7$$$ литров воды, а после потеряет $$$5$$$, значит после третьего дня у него останется $$$19$$$ литров воды. $$$19$$$ входит в диапазон $$$[15, 25]$$$, поэтому ответ «<span class="tex-font-style-tt">Yes</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:17: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:'8124b5e88cae16b3',t:'MTY5NjY2NjY3Ni42MzQwMDA='};_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", "\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", "\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"] | ["\u0433\u0440\u0430\u0444\u044b", "\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2200"] | ||
1461F | 1461 | F | ru | F. Математическое выражение | <div class="problem-statement"><div class="header"><div class="title">F. Математическое выражение</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, a_2, \ldots, a_n$$$, без каких-либо арифметических знаков. Учитель объяснил Барбаре, что ей требуется лишь расставить разрешенные знаки между числами так, чтобы получившееся выражение имело максимально возможное значение. Для того чтобы узнать разрешенные знаки, учитель дал Барбаре строку $$$s$$$, которая содержит данную информацию.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fa8eeb748dec6668e7e6103baad1712d8a290885.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Легко заметить, что Барбаре требуется поставить $$$n - 1$$$ знак между соседними числами. Выражение должно начинаться с числа и все знаки должны быть разрешены (содержаться в строке $$$s$$$). Обратите внимание, что умножение имеет приоритет выше, чем сложение или вычитание, а сложение и вычитание имеют одинаковый приоритет и выполняются слева направо. Помогите Барбаре и составьте требуемое выражение!</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$$$ ($$$0 \le a_i \le 9$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</p><p>Третья строка входных данных содержит строку $$$s$$$ ($$$1 \le |s| \le 3$$$) — разрешенные в выражении знаки. Гарантируется, что строка может состоять только из символов «<span class="tex-font-style-tt">-</span>», «<span class="tex-font-style-tt">+</span>» и «<span class="tex-font-style-tt">*</span>». Также гарантируется, что все символы строки различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ чисел, разделённых $$$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
2 2 0
+-*
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2*2-0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
2 1 1 2
+*
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2+1+1+2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере также подходят ответы: «<span class="tex-font-style-tt">2+2+0</span>», «<span class="tex-font-style-tt">2+2-0</span>», «<span class="tex-font-style-tt">2*2+0</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="9b8f9c17c3dbe3e54c17e76a7ceb5c8b"/>
<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="7be811eb81959d035abc8ce94f9c8dc4388d2cac"/>
<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='9b8f9c17c3dbe3e54c17e76a7ceb5c8b'> </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%2F1461%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='9b8f9c17c3dbe3e54c17e76a7ceb5c8b'/>
<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/1461">Codeforces Round 689 (Div. 2, based on Zed Code Competition)</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='9b8f9c17c3dbe3e54c17e76a7ceb5c8b'/>
<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/1461/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="Сложность">
*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='9b8f9c17c3dbe3e54c17e76a7ceb5c8b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="829211"/>
<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='9b8f9c17c3dbe3e54c17e76a7ceb5c8b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="829211"/>
<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/85463" title="Codeforces Round #689 (Div. 2), основанный на Zed Code Competition 2020" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12598:12599" 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/85491" title="Разбор Codeforces Round #689 (Div. 2)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12605:12606" 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="//www.youtube.com/watch?v=Ler9YWK4Wag" title="watch" target="_blank">watch <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12634" resourceName="watch"
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/1461">Задачи</a></li>
<li><a
href="/contest/1461/submit">Отослать</a></li>
<li><a
href="/contest/1461/my">Мои посылки</a></li>
<li><a
href="/contest/1461/status">Статус</a></li>
<li><a
href="/contest/1461/hacks">Взломы</a></li>
<li><a
href="/contest/1461/room/1">Комната</a></li>
<li><a
href="/contest/1461/standings">Положение</a></li>
<li><a
href="/contest/1461/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_9b045219b2441257041a7ff3e50baf150baa5421">
<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>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, a_2, \ldots, a_n$$$, без каких-либо арифметических знаков. Учитель объяснил Барбаре, что ей требуется лишь расставить разрешенные знаки между числами так, чтобы получившееся выражение имело максимально возможное значение. Для того чтобы узнать разрешенные знаки, учитель дал Барбаре строку $$$s$$$, которая содержит данную информацию.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/fa8eeb748dec6668e7e6103baad1712d8a290885.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Легко заметить, что Барбаре требуется поставить $$$n - 1$$$ знак между соседними числами. Выражение должно начинаться с числа и все знаки должны быть разрешены (содержаться в строке $$$s$$$). Обратите внимание, что умножение имеет приоритет выше, чем сложение или вычитание, а сложение и вычитание имеют одинаковый приоритет и выполняются слева направо. Помогите Барбаре и составьте требуемое выражение!</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$$$ ($$$0 \le a_i \le 9$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</p><p>Третья строка входных данных содержит строку $$$s$$$ ($$$1 \le |s| \le 3$$$) — разрешенные в выражении знаки. Гарантируется, что строка может состоять только из символов «<span class="tex-font-style-tt">-</span>», «<span class="tex-font-style-tt">+</span>» и «<span class="tex-font-style-tt">*</span>». Также гарантируется, что все символы строки различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ чисел, разделённых $$$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
2 2 0
+-*
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2*2-0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
2 1 1 2
+*
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2+1+1+2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере также подходят ответы: «<span class="tex-font-style-tt">2+2+0</span>», «<span class="tex-font-style-tt">2+2-0</span>», «<span class="tex-font-style-tt">2*2+0</span>».</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:17: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:'8124b5f09cbe00b4',t:'MTY5NjY2NjY3Ny45MTAwMDA='};_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", "\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"] | ["\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", "*2700"] | ||
1462A | 1462 | 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>У Поликарпа есть любимая последовательность $$$a[1 \dots n]$$$, которая состоит из $$$n$$$ целых чисел. Он выписал ее на доску следующим образом:</p><ul> <li> максимально слева (в начале доски) он написал число $$$a_1$$$; </li><li> максимально справа (в конце доски) он написал число $$$a_2$$$; </li><li> потом максимально слева (но правее, чем $$$a_1$$$) он написал число $$$a_3$$$; </li><li> потом максимально справа (но левее, чем $$$a_2$$$) он написал число $$$a_4$$$; </li><li> Поликарп продолжил действовать также, пока не выписал на доску всю последовательность. </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cb8722f608b54c6bb30e3157ab5143a0b99ec00b.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Вот что будет изображено после четырёх действий (конечно, если $$$n \ge 4$$$).</span> </center><p>Например, если $$$n=7$$$ и $$$a=[3, 1, 4, 1, 5, 9, 2]$$$, то Поликарп выпишет на доску последовательность $$$[3, 4, 5, 2, 9, 1, 1]$$$.</p><p>Вы увидели последовательность на доске и теперь хотите узнать, какая была любимая последовательность Поликарпа.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 300$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится целое число $$$n$$$ ($$$1 \le n \le 300$$$) — длина последовательности, записанной на доске.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$b_1, b_2,\ldots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) — последовательность на доске.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных. Каждый ответ — это последовательность $$$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
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных последовательность $$$a$$$ совпадает с последовательностью из условия. Состояния доски после каждого шага выглядят так:</p><p>$$$[3] \Rightarrow [3, 1] \Rightarrow [3, 4, 1] \Rightarrow [3, 4, 1, 1] \Rightarrow [3, 4, 5, 1, 1] \Rightarrow [3, 4, 5, 9, 1, 1] \Rightarrow [3, 4, 5, 2, 9, 1, 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="c03241ef8c6801e93cce4291d1e37d73"/>
<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="6d265d6f991f5773f7a9d8229ff08048f46e2bdd"/>
<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='c03241ef8c6801e93cce4291d1e37d73'> </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%2F1462%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='c03241ef8c6801e93cce4291d1e37d73'/>
<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/1462">Codeforces Round 690 (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='c03241ef8c6801e93cce4291d1e37d73'/>
<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/1462/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='c03241ef8c6801e93cce4291d1e37d73'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="833569"/>
<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='c03241ef8c6801e93cce4291d1e37d73'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="833569"/>
<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/85573" title="Codeforces Round #690 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12631:12632" 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/85594" title="Разбор Codeforces Round #690 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12642:12643" 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/1462">Задачи</a></li>
<li><a
href="/contest/1462/submit">Отослать</a></li>
<li><a
href="/contest/1462/my">Мои посылки</a></li>
<li><a
href="/contest/1462/status">Статус</a></li>
<li><a
href="/contest/1462/hacks">Взломы</a></li>
<li><a
href="/contest/1462/standings">Положение</a></li>
<li><a
href="/contest/1462/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_1750594d0efb4de4138fc6ebee7858da035889a2">
<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>У Поликарпа есть любимая последовательность $$$a[1 \dots n]$$$, которая состоит из $$$n$$$ целых чисел. Он выписал ее на доску следующим образом:</p><ul> <li> максимально слева (в начале доски) он написал число $$$a_1$$$; </li><li> максимально справа (в конце доски) он написал число $$$a_2$$$; </li><li> потом максимально слева (но правее, чем $$$a_1$$$) он написал число $$$a_3$$$; </li><li> потом максимально справа (но левее, чем $$$a_2$$$) он написал число $$$a_4$$$; </li><li> Поликарп продолжил действовать также, пока не выписал на доску всю последовательность. </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/cb8722f608b54c6bb30e3157ab5143a0b99ec00b.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Вот что будет изображено после четырёх действий (конечно, если $$$n \ge 4$$$).</span> </center><p>Например, если $$$n=7$$$ и $$$a=[3, 1, 4, 1, 5, 9, 2]$$$, то Поликарп выпишет на доску последовательность $$$[3, 4, 5, 2, 9, 1, 1]$$$.</p><p>Вы увидели последовательность на доске и теперь хотите узнать, какая была любимая последовательность Поликарпа.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 300$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится целое число $$$n$$$ ($$$1 \le n \le 300$$$) — длина последовательности, записанной на доске.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$b_1, b_2,\ldots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) — последовательность на доске.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных. Каждый ответ — это последовательность $$$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
7
3 4 5 2 9 1 1
4
9 2 7 1
11
8 4 3 1 2 7 8 7 9 4 2
1
42
2
11 7
8
1 1 1 1 1 1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 1 4 1 5 9 2
9 1 2 7
8 2 4 4 3 9 1 7 2 8 7
42
11 7
1 1 1 1 1 1 1 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных последовательность $$$a$$$ совпадает с последовательностью из условия. Состояния доски после каждого шага выглядят так:</p><p>$$$[3] \Rightarrow [3, 1] \Rightarrow [3, 4, 1] \Rightarrow [3, 4, 1, 1] \Rightarrow [3, 4, 5, 1, 1] \Rightarrow [3, 4, 5, 9, 1, 1] \Rightarrow [3, 4, 5, 2, 9, 1, 1]$$$.</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:17:59</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:'8124b5f89cf415f6',t:'MTY5NjY2NjY3OS4yOTMwMDA='};_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", "\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\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"] | ||
1462B | 1462 | 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[1 \dots n]$$$ длины $$$n$$$, состоящая из десятичных цифр. Поликарп делает следующую операцию со строкой $$$s$$$ <span class="tex-font-style-bf">не более одного раза</span> (то есть делает операцию $$$0$$$ или $$$1$$$ раз): </p><ul> <li> Поликарп выбирает два числа $$$i$$$ и $$$j$$$ ($$$1 \leq i \leq j \leq n$$$) и удаляет из строки $$$s$$$ символы на позициях $$$i, i+1, i+2, \ldots, j$$$ (то есть удаляет подстроку $$$s[i \dots j]$$$). Более формально, Поликарп превращает строку $$$s$$$ в строку $$$s_1 s_2 \ldots s_{i-1} s_{j+1} s_{j+2} \ldots s_{n}$$$. </li></ul><p>Например, строку $$$s = $$$«<span class="tex-font-style-tt">20192020</span>» Поликарп может превратить в строки: </p><ul> <li> «<span class="tex-font-style-tt">2020</span>» (в таком случае $$$(i, j)=(3, 6)$$$ или $$$(i, j)=(1, 4)$$$); </li><li> «<span class="tex-font-style-tt">2019220</span>» (в таком случае $$$(i, j)=(6, 6)$$$); </li><li> «<span class="tex-font-style-tt">020</span>» (в таком случае $$$(i, j)=(1, 5)$$$); </li><li> возможны и другие ходы, выше перечислены лишь только некоторые из них. </li></ul><p>Поликарпу очень нравится строка «<span class="tex-font-style-tt">2020</span>», поэтому ему интересно, можно ли превратить строку $$$s$$$ в строку «<span class="tex-font-style-tt">2020</span>» не более чем за одну операцию? Заметьте, что проводить ноль операций допустимо.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \leq t \leq 1000 $$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора содержится целое число $$$n$$$ ($$$4 \leq n \leq 200$$$) — длина строки $$$s$$$. В следующей строке находится строка $$$s$$$ длины $$$n$$$, состоящая из десятичных цифр. Допустимо, что строка $$$s$$$ начинается с цифры <span class="tex-font-style-tt">0</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных в отдельной строке выведите: </p><ul> <li> «<span class="tex-font-style-tt">YES</span>», если Поликарп может превратить строку $$$s$$$ в строку «<span class="tex-font-style-tt">2020</span>» не более чем за одну операцию (то есть за $$$0$$$ или $$$1$$$ операцию); </li><li> «<span class="tex-font-style-tt">NO</span>» в противном случае. </li></ul><p>Вы можете выводить «<span class="tex-font-style-tt">YES</span>» и «<span class="tex-font-style-tt">NO</span>» в любом регистре (например, строки <span class="tex-font-style-tt">yEs</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">Yes</span> и <span class="tex-font-style-tt">YES</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
8
20192020
8
22019020
4
2020
5
20002
6
729040
6
200200
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
YES
NO
NO
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Поликарп мог выбрать $$$i=3$$$ и $$$j=6$$$.</p><p>Во втором наборе входных данных Поликарп мог выбрать $$$i=2$$$ и $$$j=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="cda83fee495ec05de0623ee62269788b"/>
<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="6d265d6f991f5773f7a9d8229ff08048f46e2bdd"/>
<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='cda83fee495ec05de0623ee62269788b'> </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%2F1462%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='cda83fee495ec05de0623ee62269788b'/>
<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/1462">Codeforces Round 690 (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='cda83fee495ec05de0623ee62269788b'/>
<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/1462/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="Сложность">
*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='cda83fee495ec05de0623ee62269788b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="833570"/>
<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='cda83fee495ec05de0623ee62269788b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="833570"/>
<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/85573" title="Codeforces Round #690 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12631:12632" 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/85594" title="Разбор Codeforces Round #690 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12642:12643" 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/1462">Задачи</a></li>
<li><a
href="/contest/1462/submit">Отослать</a></li>
<li><a
href="/contest/1462/my">Мои посылки</a></li>
<li><a
href="/contest/1462/status">Статус</a></li>
<li><a
href="/contest/1462/hacks">Взломы</a></li>
<li><a
href="/contest/1462/standings">Положение</a></li>
<li><a
href="/contest/1462/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_0fdc7bc5cf4934570a4fabac705d7c1c7515b155">
<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[1 \dots n]$$$ длины $$$n$$$, состоящая из десятичных цифр. Поликарп делает следующую операцию со строкой $$$s$$$ <span class="tex-font-style-bf">не более одного раза</span> (то есть делает операцию $$$0$$$ или $$$1$$$ раз): </p><ul> <li> Поликарп выбирает два числа $$$i$$$ и $$$j$$$ ($$$1 \leq i \leq j \leq n$$$) и удаляет из строки $$$s$$$ символы на позициях $$$i, i+1, i+2, \ldots, j$$$ (то есть удаляет подстроку $$$s[i \dots j]$$$). Более формально, Поликарп превращает строку $$$s$$$ в строку $$$s_1 s_2 \ldots s_{i-1} s_{j+1} s_{j+2} \ldots s_{n}$$$. </li></ul><p>Например, строку $$$s = $$$«<span class="tex-font-style-tt">20192020</span>» Поликарп может превратить в строки: </p><ul> <li> «<span class="tex-font-style-tt">2020</span>» (в таком случае $$$(i, j)=(3, 6)$$$ или $$$(i, j)=(1, 4)$$$); </li><li> «<span class="tex-font-style-tt">2019220</span>» (в таком случае $$$(i, j)=(6, 6)$$$); </li><li> «<span class="tex-font-style-tt">020</span>» (в таком случае $$$(i, j)=(1, 5)$$$); </li><li> возможны и другие ходы, выше перечислены лишь только некоторые из них. </li></ul><p>Поликарпу очень нравится строка «<span class="tex-font-style-tt">2020</span>», поэтому ему интересно, можно ли превратить строку $$$s$$$ в строку «<span class="tex-font-style-tt">2020</span>» не более чем за одну операцию? Заметьте, что проводить ноль операций допустимо.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$t$$$ ($$$1 \leq t \leq 1000 $$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора содержится целое число $$$n$$$ ($$$4 \leq n \leq 200$$$) — длина строки $$$s$$$. В следующей строке находится строка $$$s$$$ длины $$$n$$$, состоящая из десятичных цифр. Допустимо, что строка $$$s$$$ начинается с цифры <span class="tex-font-style-tt">0</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных в отдельной строке выведите: </p><ul> <li> «<span class="tex-font-style-tt">YES</span>», если Поликарп может превратить строку $$$s$$$ в строку «<span class="tex-font-style-tt">2020</span>» не более чем за одну операцию (то есть за $$$0$$$ или $$$1$$$ операцию); </li><li> «<span class="tex-font-style-tt">NO</span>» в противном случае. </li></ul><p>Вы можете выводить «<span class="tex-font-style-tt">YES</span>» и «<span class="tex-font-style-tt">NO</span>» в любом регистре (например, строки <span class="tex-font-style-tt">yEs</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">Yes</span> и <span class="tex-font-style-tt">YES</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
8
20192020
8
22019020
4
2020
5
20002
6
729040
6
200200
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
YES
YES
NO
NO
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Поликарп мог выбрать $$$i=3$$$ и $$$j=6$$$.</p><p>Во втором наборе входных данных Поликарп мог выбрать $$$i=2$$$ и $$$j=5$$$.</p><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:18: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:'8124b60139889daa',t:'MTY5NjY2NjY4MC42NDQwMDA='};_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\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", "*800"] | ||
1462C | 1462 | 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>Вам задано натуральное число $$$x$$$. Найдите наименьшее натуральное число, у которого сумма цифр равна $$$x$$$ и все цифры <span class="tex-font-style-bf">различны</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 50$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных состоит из одного натурального числа $$$x$$$ ($$$1 \le x \le 50$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных: </p><ul> <li> если натуральное число, у которого сумма цифр равна $$$x$$$ и все цифры различны существует, то выведите наименьшее такое число; </li><li> В противном случае выведите <span class="tex-font-style-tt">-1</span>. </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
5
15
50
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
5
69
-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="6a67f9e7ea05b0359f8eba2bed5c7e30"/>
<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="6d265d6f991f5773f7a9d8229ff08048f46e2bdd"/>
<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='6a67f9e7ea05b0359f8eba2bed5c7e30'> </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%2F1462%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='6a67f9e7ea05b0359f8eba2bed5c7e30'/>
<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/1462">Codeforces Round 690 (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='6a67f9e7ea05b0359f8eba2bed5c7e30'/>
<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/1462/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='6a67f9e7ea05b0359f8eba2bed5c7e30'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="833571"/>
<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='6a67f9e7ea05b0359f8eba2bed5c7e30'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="833571"/>
<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/85573" title="Codeforces Round #690 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12631:12632" 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/85594" title="Разбор Codeforces Round #690 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12642:12643" 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/1462">Задачи</a></li>
<li><a
href="/contest/1462/submit">Отослать</a></li>
<li><a
href="/contest/1462/my">Мои посылки</a></li>
<li><a
href="/contest/1462/status">Статус</a></li>
<li><a
href="/contest/1462/hacks">Взломы</a></li>
<li><a
href="/contest/1462/standings">Положение</a></li>
<li><a
href="/contest/1462/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_d9f455685826cf5f16ce8d3d4370b876f4b57ddf">
<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>Вам задано натуральное число $$$x$$$. Найдите наименьшее натуральное число, у которого сумма цифр равна $$$x$$$ и все цифры <span class="tex-font-style-bf">различны</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 50$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных состоит из одного натурального числа $$$x$$$ ($$$1 \le x \le 50$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных: </p><ul> <li> если натуральное число, у которого сумма цифр равна $$$x$$$ и все цифры различны существует, то выведите наименьшее такое число; </li><li> В противном случае выведите <span class="tex-font-style-tt">-1</span>. </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
5
15
50
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
5
69
-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:18: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:'8124b609aee5759f',t:'MTY5NjY2NjY4Mi4wMjEwMDA='};_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", "*900"] | ||
1462D | 1462 | D | ru | D. Прибавления в соседей | <div class="problem-statement"><div class="header"><div class="title">D. Прибавления в соседей</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[1 \dots n]$$$ из $$$n$$$ целых чисел. Он может производить с массивом $$$a$$$ следующую операцию не более $$$n$$$ раз: </p><ul> <li> Поликарп выбирает индекс $$$i$$$ и прибавляет в <span class="tex-font-style-bf">одного на свой выбор</span> из его соседей значение $$$a_i$$$. Более формально, Поликарп прибавляет значение $$$a_i$$$ либо к $$$a_{i-1}$$$, либо к $$$a_{i+1}$$$ (если такого соседа не существует, то и прибавить в него нельзя); </li><li> После прибавления Поликарп удаляет $$$i$$$-й элемент из массива $$$a$$$ (заметим, что в процессе удаления длина массива $$$a$$$ уменьшается на $$$1$$$). </li></ul><p>Два пункта выше совместно обозначают одну операцию.</p><p>Например, если у Поликарпа есть массив $$$a = [3, 1, 6, 6, 2]$$$, то он может произвести с ним следующую последовательность операций:</p><ul> <li> Поликарп выбирает $$$i = 2$$$ и прибавляет значение $$$a_i$$$ к $$$(i-1)$$$-у элементу: $$$a = [4, 6, 6, 2]$$$; </li><li> Поликарп выбирает $$$i = 1$$$ и прибавляет значение $$$a_i$$$ к $$$(i+1)$$$-у элементу: $$$a = [10, 6, 2]$$$; </li><li> Поликарп выбирает $$$i = 3$$$ и прибавляет значение $$$a_i$$$ к $$$(i-1)$$$-у элементу: $$$a = [10, 8]$$$; </li><li> Поликарп выбирает $$$i = 2$$$ и прибавляет значение $$$a_i$$$ к $$$(i-1)$$$-у элементу: $$$a = [18]$$$; </li></ul> <p>Заметьте, что Поликарп мог прекратить производить операции в любой из моментов.</p><p>Поликарпу стало интересно, сколько минимум операций ему надо произвести, чтобы все элементы массива $$$a$$$ стали одинаковыми (то есть, он хочет, чтобы все $$$a_i$$$ были равны между собой).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \leq t \leq 3000$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора содержится одно целое число $$$n$$$ ($$$1 \leq n \leq 3000$$$) — длина массива. В следующей строке содержатся $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — массив $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$3000$$$.</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>
4
5
3 1 6 6 2
4
1 2 2 1
3
2 2 2
4
6 3 2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
2
0
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных ответ может быть получен следующим образом (один из возможных вариантов):</p><p>$$$[3, 1, 6, 6, 2]$$$ $$$\xrightarrow[]{i=4,~прибавляет~влево}$$$ $$$[3, 1, 12, 2]$$$ $$$\xrightarrow[]{i=2,~прибавляет~вправо}$$$ $$$[3, 13, 2]$$$ $$$\xrightarrow[]{i=1,~прибавляет~вправо}$$$ $$$[16, 2]$$$ $$$\xrightarrow[]{i=2,~прибавляет~влево}$$$ $$$[18]$$$. Все элементы в массиве $$$[18]$$$ одинаковые.</p><p>Во втором наборе входных данных ответ может быть получен следующим образом (один из возможных вариантов):</p><p>$$$[1, 2, 2, 1]$$$ $$$\xrightarrow[]{i=1,~прибавляет~вправо}$$$ $$$[3, 2, 1]$$$ $$$\xrightarrow[]{i=3,~прибавляет~влево}$$$ $$$[3, 3]$$$. Все элементы в массиве $$$[3, 3]$$$ одинаковые.</p><p>В третьем наборе входных данных Поликарпу не надо производить ни одну операцию, так как массив $$$[2, 2, 2]$$$ уже содержит одинаковые элементы.</p><p>В четвертом наборе входных данных ответ может быть получен следующим образом (один из возможных вариантов):</p><p>$$$[6, 3, 2, 1]$$$ $$$\xrightarrow[]{i=3,~прибавляет~вправо}$$$ $$$[6, 3, 3]$$$ $$$\xrightarrow[]{i=3,~прибавляет~влево}$$$ $$$[6, 6]$$$. Все элементы в массиве $$$[6, 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="ad7952fedde112489f0bd14182ce1661"/>
<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="6d265d6f991f5773f7a9d8229ff08048f46e2bdd"/>
<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='ad7952fedde112489f0bd14182ce1661'> </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%2F1462%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='ad7952fedde112489f0bd14182ce1661'/>
<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/1462">Codeforces Round 690 (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='ad7952fedde112489f0bd14182ce1661'/>
<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/1462/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='ad7952fedde112489f0bd14182ce1661'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="833572"/>
<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='ad7952fedde112489f0bd14182ce1661'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="833572"/>
<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/85573" title="Codeforces Round #690 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12631:12632" 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/85594" title="Разбор Codeforces Round #690 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12642:12643" 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/1462">Задачи</a></li>
<li><a
href="/contest/1462/submit">Отослать</a></li>
<li><a
href="/contest/1462/my">Мои посылки</a></li>
<li><a
href="/contest/1462/status">Статус</a></li>
<li><a
href="/contest/1462/hacks">Взломы</a></li>
<li><a
href="/contest/1462/standings">Положение</a></li>
<li><a
href="/contest/1462/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_721837e68a11cb0c6c1f5cdfca54439ddd7951a3">
<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>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[1 \dots n]$$$ из $$$n$$$ целых чисел. Он может производить с массивом $$$a$$$ следующую операцию не более $$$n$$$ раз: </p><ul> <li> Поликарп выбирает индекс $$$i$$$ и прибавляет в <span class="tex-font-style-bf">одного на свой выбор</span> из его соседей значение $$$a_i$$$. Более формально, Поликарп прибавляет значение $$$a_i$$$ либо к $$$a_{i-1}$$$, либо к $$$a_{i+1}$$$ (если такого соседа не существует, то и прибавить в него нельзя); </li><li> После прибавления Поликарп удаляет $$$i$$$-й элемент из массива $$$a$$$ (заметим, что в процессе удаления длина массива $$$a$$$ уменьшается на $$$1$$$). </li></ul><p>Два пункта выше совместно обозначают одну операцию.</p><p>Например, если у Поликарпа есть массив $$$a = [3, 1, 6, 6, 2]$$$, то он может произвести с ним следующую последовательность операций:</p><ul> <li> Поликарп выбирает $$$i = 2$$$ и прибавляет значение $$$a_i$$$ к $$$(i-1)$$$-у элементу: $$$a = [4, 6, 6, 2]$$$; </li><li> Поликарп выбирает $$$i = 1$$$ и прибавляет значение $$$a_i$$$ к $$$(i+1)$$$-у элементу: $$$a = [10, 6, 2]$$$; </li><li> Поликарп выбирает $$$i = 3$$$ и прибавляет значение $$$a_i$$$ к $$$(i-1)$$$-у элементу: $$$a = [10, 8]$$$; </li><li> Поликарп выбирает $$$i = 2$$$ и прибавляет значение $$$a_i$$$ к $$$(i-1)$$$-у элементу: $$$a = [18]$$$; </li></ul> <p>Заметьте, что Поликарп мог прекратить производить операции в любой из моментов.</p><p>Поликарпу стало интересно, сколько минимум операций ему надо произвести, чтобы все элементы массива $$$a$$$ стали одинаковыми (то есть, он хочет, чтобы все $$$a_i$$$ были равны между собой).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \leq t \leq 3000$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора содержится одно целое число $$$n$$$ ($$$1 \leq n \leq 3000$$$) — длина массива. В следующей строке содержатся $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^5$$$) — массив $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$3000$$$.</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>
4
5
3 1 6 6 2
4
1 2 2 1
3
2 2 2
4
6 3 2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
2
0
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных ответ может быть получен следующим образом (один из возможных вариантов):</p><p>$$$[3, 1, 6, 6, 2]$$$ $$$\xrightarrow[]{i=4,~прибавляет~влево}$$$ $$$[3, 1, 12, 2]$$$ $$$\xrightarrow[]{i=2,~прибавляет~вправо}$$$ $$$[3, 13, 2]$$$ $$$\xrightarrow[]{i=1,~прибавляет~вправо}$$$ $$$[16, 2]$$$ $$$\xrightarrow[]{i=2,~прибавляет~влево}$$$ $$$[18]$$$. Все элементы в массиве $$$[18]$$$ одинаковые.</p><p>Во втором наборе входных данных ответ может быть получен следующим образом (один из возможных вариантов):</p><p>$$$[1, 2, 2, 1]$$$ $$$\xrightarrow[]{i=1,~прибавляет~вправо}$$$ $$$[3, 2, 1]$$$ $$$\xrightarrow[]{i=3,~прибавляет~влево}$$$ $$$[3, 3]$$$. Все элементы в массиве $$$[3, 3]$$$ одинаковые.</p><p>В третьем наборе входных данных Поликарпу не надо производить ни одну операцию, так как массив $$$[2, 2, 2]$$$ уже содержит одинаковые элементы.</p><p>В четвертом наборе входных данных ответ может быть получен следующим образом (один из возможных вариантов):</p><p>$$$[6, 3, 2, 1]$$$ $$$\xrightarrow[]{i=3,~прибавляет~вправо}$$$ $$$[6, 3, 3]$$$ $$$\xrightarrow[]{i=3,~прибавляет~влево}$$$ $$$[6, 6]$$$. Все элементы в массиве $$$[6, 6]$$$ одинаковые.</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:18: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:'8124b6123c54009d',t:'MTY5NjY2NjY4My4zNDcwMDA='};_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.", "\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", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1400"] | ||
1462E1 | 1462 | E1 | ru | E1. Близкие наборы (простая версия) | <div class="problem-statement"><div class="header"><div class="title">E1. Близкие наборы (простая версия)</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">Это простая версия этой задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$k$$$ и $$$m$$$ (в этой версии $$$k=2$$$, $$$m=3$$$). Также в этой версии задачи НЕ НУЖНО выводить ответ по какому-либо модулю.</span></p><p>Вам задана последовательность $$$a$$$ длины $$$n$$$, состоящая из целых чисел от $$$1$$$ до $$$n$$$. <span class="tex-font-style-bf">Среди чисел могут быть одинаковые</span>.</p><p>Найдите количество наборов из $$$m = 3$$$ элементов, таких что максимальное число в наборе отличается от минимального не больше, чем на $$$k = 2$$$. Формально, в этой задаче вам нужно найти количество троек индексов $$$i < j < z$$$, таких что</p><p>$$$$$$\max(a_i, a_j, a_z) - \min(a_i, a_j, a_z) \le 2.$$$$$$</p><p>Например, если $$$n=4$$$ и $$$a=[1,2,4,3]$$$, то существуют две такие тройки ($$$i=1, j=2, z=4$$$ и $$$i=2, j=3, z=4$$$). Если же $$$n=4$$$ и $$$a=[1,1,1,1]$$$, то все четыре возможные тройки подходят.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длина последовательности $$$a$$$.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$a_1, a_2,\ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — последовательность $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных. Каждый ответ — это количество упорядоченных троек элементов, таких что максимальное число в тройке отличается от минимального не больше, чем на $$$2$$$. Обратите внимание, что в отличии от сложной версии задачи, здесь <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 2 4 3
4
1 1 1 1
1
1
10
5 6 1 3 2 9 8 1 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
4
0
15
</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="a0ff87f4da69b96e20f9ad77fe236634"/>
<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="6d265d6f991f5773f7a9d8229ff08048f46e2bdd"/>
<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='a0ff87f4da69b96e20f9ad77fe236634'> </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%2F1462%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='a0ff87f4da69b96e20f9ad77fe236634'/>
<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/1462">Codeforces Round 690 (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='a0ff87f4da69b96e20f9ad77fe236634'/>
<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/1462/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='a0ff87f4da69b96e20f9ad77fe236634'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="833573"/>
<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='a0ff87f4da69b96e20f9ad77fe236634'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="833573"/>
<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/85573" title="Codeforces Round #690 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12631:12632" 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/85594" title="Разбор Codeforces Round #690 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12642:12643" 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/1462">Задачи</a></li>
<li><a
href="/contest/1462/submit">Отослать</a></li>
<li><a
href="/contest/1462/my">Мои посылки</a></li>
<li><a
href="/contest/1462/status">Статус</a></li>
<li><a
href="/contest/1462/hacks">Взломы</a></li>
<li><a
href="/contest/1462/standings">Положение</a></li>
<li><a
href="/contest/1462/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_b5173a8479be8094da6382587853741d1e91b8b2">
<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>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">Это простая версия этой задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$k$$$ и $$$m$$$ (в этой версии $$$k=2$$$, $$$m=3$$$). Также в этой версии задачи НЕ НУЖНО выводить ответ по какому-либо модулю.</span></p><p>Вам задана последовательность $$$a$$$ длины $$$n$$$, состоящая из целых чисел от $$$1$$$ до $$$n$$$. <span class="tex-font-style-bf">Среди чисел могут быть одинаковые</span>.</p><p>Найдите количество наборов из $$$m = 3$$$ элементов, таких что максимальное число в наборе отличается от минимального не больше, чем на $$$k = 2$$$. Формально, в этой задаче вам нужно найти количество троек индексов $$$i < j < z$$$, таких что</p><p>$$$$$$\max(a_i, a_j, a_z) - \min(a_i, a_j, a_z) \le 2.$$$$$$</p><p>Например, если $$$n=4$$$ и $$$a=[1,2,4,3]$$$, то существуют две такие тройки ($$$i=1, j=2, z=4$$$ и $$$i=2, j=3, z=4$$$). Если же $$$n=4$$$ и $$$a=[1,1,1,1]$$$, то все четыре возможные тройки подходят.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — длина последовательности $$$a$$$.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$a_1, a_2,\ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — последовательность $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных. Каждый ответ — это количество упорядоченных троек элементов, таких что максимальное число в тройке отличается от минимального не больше, чем на $$$2$$$. Обратите внимание, что в отличии от сложной версии задачи, здесь <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 2 4 3
4
1 1 1 1
1
1
10
5 6 1 3 2 9 8 1 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
4
0
15
</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:18: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:'8124b61a8d949d99',t:'MTY5NjY2NjY4NC42MzkwMDA='};_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", "\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.", "\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", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1500"] | ||
1462E2 | 1462 | E2 | ru | E2. Близкие наборы (сложная версия) | <div class="problem-statement"><div class="header"><div class="title">E2. Близкие наборы (сложная версия)</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">Это сложная версия этой задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$k$$$ и $$$m$$$. В этой версии задачи нужно выводить ответ по модулю $$$10^9+7$$$.</span></p><p>Вам задана последовательность $$$a$$$ длины $$$n$$$, состоящая из целых чисел от $$$1$$$ до $$$n$$$. <span class="tex-font-style-bf">Среди чисел могут быть одинаковые</span>.</p><p>Найдите количество наборов из $$$m$$$ элементов, таких что максимальное число в наборе отличается от минимального не больше, чем на $$$k$$$. Формально, вам нужно найти количество наборов из $$$m$$$ индексов $$$i_1 < i_2 < \ldots < i_m$$$, таких что</p><p>$$$$$$\max(a_{i_1}, a_{i_2}, \ldots, a_{i_m}) - \min(a_{i_1}, a_{i_2}, \ldots, a_{i_m}) \le k.$$$$$$</p><p>Например, если $$$n=4$$$, $$$m=3$$$, $$$k=2$$$, $$$a=[1,2,4,3]$$$, то существуют две такие тройки ($$$i=1, j=2, z=4$$$ и $$$i=2, j=3, z=4$$$). Если же $$$n=4$$$, $$$m=2$$$, $$$k=1$$$, $$$a=[1,1,1,1]$$$, то все шесть возможных пар подходят.</p><p><span class="tex-font-style-bf">Поскольку ответ может быть достаточно большим, вам нужно посчитать его по модулю $$$10^9 + 7$$$ (остаток при делении на число $$$10^9 + 7$$$).</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится три целых числа $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 100$$$, $$$1 \le k \le n$$$) — длина последовательности $$$a$$$, количество элементов в искомых наборах и максимальная разница элементов в наборе.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$a_1, a_2,\ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — последовательность $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных. Каждый ответ — это количество наборов из $$$m$$$ элементов по модулю $$$10^9 + 7$$$, таких что максимальное число в наборе отличается от минимального не больше, чем на $$$k$$$.</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 4 3
4 2 1
1 1 1 1
1 1 1
1
10 4 3
5 6 1 3 2 9 8 1 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
6
1
20
</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="02b252448ec02805bbb4f3b72170c432"/>
<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="6d265d6f991f5773f7a9d8229ff08048f46e2bdd"/>
<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='02b252448ec02805bbb4f3b72170c432'> </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%2F1462%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='02b252448ec02805bbb4f3b72170c432'/>
<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/1462">Codeforces Round 690 (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='02b252448ec02805bbb4f3b72170c432'/>
<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/1462/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="Сложность">
*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='02b252448ec02805bbb4f3b72170c432'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="833574"/>
<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='02b252448ec02805bbb4f3b72170c432'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="833574"/>
<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/85573" title="Codeforces Round #690 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12631:12632" 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/85594" title="Разбор Codeforces Round #690 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12642:12643" 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/1462">Задачи</a></li>
<li><a
href="/contest/1462/submit">Отослать</a></li>
<li><a
href="/contest/1462/my">Мои посылки</a></li>
<li><a
href="/contest/1462/status">Статус</a></li>
<li><a
href="/contest/1462/hacks">Взломы</a></li>
<li><a
href="/contest/1462/standings">Положение</a></li>
<li><a
href="/contest/1462/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_60e2d013931a396114d29b90ecbb02c1ccb43250">
<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>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">Это сложная версия этой задачи. Единственное различие между простой и сложной версиями заключается в ограничениях на $$$k$$$ и $$$m$$$. В этой версии задачи нужно выводить ответ по модулю $$$10^9+7$$$.</span></p><p>Вам задана последовательность $$$a$$$ длины $$$n$$$, состоящая из целых чисел от $$$1$$$ до $$$n$$$. <span class="tex-font-style-bf">Среди чисел могут быть одинаковые</span>.</p><p>Найдите количество наборов из $$$m$$$ элементов, таких что максимальное число в наборе отличается от минимального не больше, чем на $$$k$$$. Формально, вам нужно найти количество наборов из $$$m$$$ индексов $$$i_1 < i_2 < \ldots < i_m$$$, таких что</p><p>$$$$$$\max(a_{i_1}, a_{i_2}, \ldots, a_{i_m}) - \min(a_{i_1}, a_{i_2}, \ldots, a_{i_m}) \le k.$$$$$$</p><p>Например, если $$$n=4$$$, $$$m=3$$$, $$$k=2$$$, $$$a=[1,2,4,3]$$$, то существуют две такие тройки ($$$i=1, j=2, z=4$$$ и $$$i=2, j=3, z=4$$$). Если же $$$n=4$$$, $$$m=2$$$, $$$k=1$$$, $$$a=[1,1,1,1]$$$, то все шесть возможных пар подходят.</p><p><span class="tex-font-style-bf">Поскольку ответ может быть достаточно большим, вам нужно посчитать его по модулю $$$10^9 + 7$$$ (остаток при делении на число $$$10^9 + 7$$$).</span></p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>В первой строке каждого набора входных данных находится три целых числа $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 100$$$, $$$1 \le k \le n$$$) — длина последовательности $$$a$$$, количество элементов в искомых наборах и максимальная разница элементов в наборе.</p><p>В следующей строке находятся $$$n$$$ целых чисел $$$a_1, a_2,\ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — последовательность $$$a$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы входных данных. Каждый ответ — это количество наборов из $$$m$$$ элементов по модулю $$$10^9 + 7$$$, таких что максимальное число в наборе отличается от минимального не больше, чем на $$$k$$$.</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 4 3
4 2 1
1 1 1 1
1 1 1
1
10 4 3
5 6 1 3 2 9 8 1 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
6
1
20
</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:18: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:'8124b622ae279d3d',t:'MTY5NjY2NjY4Ni4wMDcwMDA='};_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", "\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.", "\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"] | ["\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", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\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", "*1700"] | ||
1462F | 1462 | 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$$$ отрезков. Отрезок с номером $$$i$$$ характеризуется двумя целыми числами $$$l_i$$$ и $$$r_i$$$ — координаты начала и конца отрезка, соответственно. Поликарп понял, что ему нужны не все отрезки, поэтому он хочет удалить некоторые из них. </p><p>Поликарп считает, что набор из $$$k$$$ отрезков хороший, если существует отрезок $$$[l_i, r_i]$$$ ($$$1 \leq i \leq k$$$) из набора, такой что он пересекает каждый отрезок из набора (пересечение должно быть <span class="tex-font-style-bf">точкой или отрезком</span>). Например, набор из $$$3$$$ отрезков $$$[[1, 4], [2, 3], [3, 6]]$$$ является хорошим, так как отрезок $$$[2, 3]$$$ пересекает каждый отрезок из набора. Набор из $$$4$$$ отрезков $$$[[1, 2], [2, 3], [3, 5], [4, 5]]$$$ хорошим не является.</p><p>Поликарпу интересно, какое минимальное количество отрезков ему надо удалить, чтобы набор из оставшихся отрезков стал хорошим?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^5$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных даннных.</p><p>В первой строке каждого набора входных данных находится одно целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — количество отрезков в наборе. Далее следуют $$$n$$$ строк с описанием отрезков.</p><p>Каждый отрезок описывается двумя целыми числами $$$l$$$ и $$$r$$$ ($$$1 \leq l \leq r \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>
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
2
0
</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="17160569dfa37963cd32c36c8a2c26d5"/>
<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="6d265d6f991f5773f7a9d8229ff08048f46e2bdd"/>
<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='17160569dfa37963cd32c36c8a2c26d5'> </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%2F1462%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='17160569dfa37963cd32c36c8a2c26d5'/>
<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/1462">Codeforces Round 690 (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='17160569dfa37963cd32c36c8a2c26d5'/>
<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/1462/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='17160569dfa37963cd32c36c8a2c26d5'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="833575"/>
<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='17160569dfa37963cd32c36c8a2c26d5'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="833575"/>
<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/85573" title="Codeforces Round #690 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12631:12632" 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/85594" title="Разбор Codeforces Round #690 (Div. 3)" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12642:12643" 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/1462">Задачи</a></li>
<li><a
href="/contest/1462/submit">Отослать</a></li>
<li><a
href="/contest/1462/my">Мои посылки</a></li>
<li><a
href="/contest/1462/status">Статус</a></li>
<li><a
href="/contest/1462/hacks">Взломы</a></li>
<li><a
href="/contest/1462/standings">Положение</a></li>
<li><a
href="/contest/1462/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_b9d7a8090eaa6203469aa4ae2a885b51a9f049c2">
<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$$$ отрезков. Отрезок с номером $$$i$$$ характеризуется двумя целыми числами $$$l_i$$$ и $$$r_i$$$ — координаты начала и конца отрезка, соответственно. Поликарп понял, что ему нужны не все отрезки, поэтому он хочет удалить некоторые из них. </p><p>Поликарп считает, что набор из $$$k$$$ отрезков хороший, если существует отрезок $$$[l_i, r_i]$$$ ($$$1 \leq i \leq k$$$) из набора, такой что он пересекает каждый отрезок из набора (пересечение должно быть <span class="tex-font-style-bf">точкой или отрезком</span>). Например, набор из $$$3$$$ отрезков $$$[[1, 4], [2, 3], [3, 6]]$$$ является хорошим, так как отрезок $$$[2, 3]$$$ пересекает каждый отрезок из набора. Набор из $$$4$$$ отрезков $$$[[1, 2], [2, 3], [3, 5], [4, 5]]$$$ хорошим не является.</p><p>Поликарпу интересно, какое минимальное количество отрезков ему надо удалить, чтобы набор из оставшихся отрезков стал хорошим?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^5$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных даннных.</p><p>В первой строке каждого набора входных данных находится одно целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — количество отрезков в наборе. Далее следуют $$$n$$$ строк с описанием отрезков.</p><p>Каждый отрезок описывается двумя целыми числами $$$l$$$ и $$$r$$$ ($$$1 \leq l \leq r \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>
4
3
1 4
2 3
3 6
4
1 2
2 3
3 5
4 5
5
1 2
3 8
4 5
6 7
9 10
5
1 5
2 4
3 5
3 8
4 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
2
0
</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:18: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:'8124b62b3ff77b4f',t:'MTY5NjY2NjY4Ny4zODMwMDA='};_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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1800"] | ||
1463A | 1463 | 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>Вы играете в новую компьютерную игру, в которой необходимо сражаться с монстрами. В очередном подземелье вы встретили трех монстров; у одного из них $$$a$$$ очков здоровья, у второго $$$b$$$ очков здоровья, а у третьего — $$$c$$$.</p><p>Для убийства монстров у вас есть пушка, которая наносит $$$1$$$ единицу урона выбранному монстру. При этом каждый $$$7$$$-й (т. е. выстрелы с номерами $$$7$$$, $$$14$$$, $$$21$$$ и т. д.) выстрел пушки <span class="tex-font-style-it">усиленный</span> и наносит $$$1$$$ урона <span class="tex-font-style-bf">всем</span> монстрам, а не только одному из них. Если текущее здоровье монстра равно $$$0$$$, он не может быть целью обычного выстрела и не получает урона от <span class="tex-font-style-it">усиленного</span> выстрела.</p><p>Вы хотите красиво пройти подземелье, а именно, убить всех монстров одним и тем же <span class="tex-font-style-it">усиленным</span> выстрелом (т. е. после очередного <span class="tex-font-style-it">усиленного</span> выстрела очки здоровья каждого из монстров должны <span class="tex-font-style-bf">впервые</span> стать равными $$$0$$$). Каждый выстрел должен попадать в монстра, т. е. вы не можете стрелять мимо цели.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одного целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из единственной строки, которая содержит три целых числа $$$a$$$, $$$b$$$ и $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$) — количество очков здоровья у каждого из монстров.</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>. Каждую букву можно выводить в любом регистре (например, <span class="tex-font-style-tt">YES</span>, <span class="tex-font-style-tt">Yes</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">yEs</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
3 2 4
1 1 1
10 1 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере вы можете действовать следующим образом: $$$1$$$-й выстрел в первого монстра, $$$2$$$-й выстрел во второго монстра, $$$3$$$-й выстрел в третьего монстра, $$$4$$$-й выстрел в первого монстра, $$$5$$$-й выстрел в третьего монстра, $$$6$$$-й выстрел в третьего монстра и $$$7$$$-й <span class="tex-font-style-it">усиленный</span> выстрел убьет всех монстров.</p><p>Во втором примере вы не можете убить монстров <span class="tex-font-style-it">усиленным</span> выстрелом, т. к. суммарное количество очков здоровья монстров равно $$$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="8e827c2335a2274cba41cff52821efda"/>
<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="caa689873c78fe2f6ee4f067504e7942b088601e"/>
<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='8e827c2335a2274cba41cff52821efda'> </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%2F1463%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='8e827c2335a2274cba41cff52821efda'/>
<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/1463">Educational Codeforces Round 100 (рейтинговый для Див. 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='8e827c2335a2274cba41cff52821efda'/>
<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/1463/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='8e827c2335a2274cba41cff52821efda'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="836001"/>
<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='8e827c2335a2274cba41cff52821efda'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="836001"/>
<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/85618" title="Educational Codeforces Round 100 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12640:12641" 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/85707" title="Разбор Educational Codeforces Round 100" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12653:12654" 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/1463">Задачи</a></li>
<li><a
href="/contest/1463/submit">Отослать</a></li>
<li><a
href="/contest/1463/my">Мои посылки</a></li>
<li><a
href="/contest/1463/status">Статус</a></li>
<li><a
href="/contest/1463/hacks">Взломы</a></li>
<li><a
href="/contest/1463/standings">Положение</a></li>
<li><a
href="/contest/1463/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_130b76b267fe473eb939db498822a879d9d66c03">
<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>Вы играете в новую компьютерную игру, в которой необходимо сражаться с монстрами. В очередном подземелье вы встретили трех монстров; у одного из них $$$a$$$ очков здоровья, у второго $$$b$$$ очков здоровья, а у третьего — $$$c$$$.</p><p>Для убийства монстров у вас есть пушка, которая наносит $$$1$$$ единицу урона выбранному монстру. При этом каждый $$$7$$$-й (т. е. выстрелы с номерами $$$7$$$, $$$14$$$, $$$21$$$ и т. д.) выстрел пушки <span class="tex-font-style-it">усиленный</span> и наносит $$$1$$$ урона <span class="tex-font-style-bf">всем</span> монстрам, а не только одному из них. Если текущее здоровье монстра равно $$$0$$$, он не может быть целью обычного выстрела и не получает урона от <span class="tex-font-style-it">усиленного</span> выстрела.</p><p>Вы хотите красиво пройти подземелье, а именно, убить всех монстров одним и тем же <span class="tex-font-style-it">усиленным</span> выстрелом (т. е. после очередного <span class="tex-font-style-it">усиленного</span> выстрела очки здоровья каждого из монстров должны <span class="tex-font-style-bf">впервые</span> стать равными $$$0$$$). Каждый выстрел должен попадать в монстра, т. е. вы не можете стрелять мимо цели.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одного целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из единственной строки, которая содержит три целых числа $$$a$$$, $$$b$$$ и $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$) — количество очков здоровья у каждого из монстров.</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>. Каждую букву можно выводить в любом регистре (например, <span class="tex-font-style-tt">YES</span>, <span class="tex-font-style-tt">Yes</span>, <span class="tex-font-style-tt">yes</span>, <span class="tex-font-style-tt">yEs</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
3 2 4
1 1 1
10 1 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере вы можете действовать следующим образом: $$$1$$$-й выстрел в первого монстра, $$$2$$$-й выстрел во второго монстра, $$$3$$$-й выстрел в третьего монстра, $$$4$$$-й выстрел в первого монстра, $$$5$$$-й выстрел в третьего монстра, $$$6$$$-й выстрел в третьего монстра и $$$7$$$-й <span class="tex-font-style-it">усиленный</span> выстрел убьет всех монстров.</p><p>Во втором примере вы не можете убить монстров <span class="tex-font-style-it">усиленным</span> выстрелом, т. к. суммарное количество очков здоровья монстров равно $$$3$$$, и вы убьете их за первые 3 выстрела.</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:18: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:'8124b633ddcb9d5b',t:'MTY5NjY2NjY4OC44MjMwMDA='};_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", "\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\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1100"] | ||
1463B | 1463 | 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]$$$ такой, что $$$1 \le a_i \le 10^9$$$. Пусть $$$S$$$ – сумма всех элементов массива $$$a$$$.</p><p>Назовем массив $$$b$$$, состоящий из $$$n$$$ целых чисел <span class="tex-font-style-bf">красивым</span>, если:</p><ul> <li> $$$1 \le b_i \le 10^9$$$ для всех $$$i$$$ от $$$1$$$ до $$$n$$$; </li><li> для каждой пары соседних целых чисел из массива $$$(b_i, b_{i + 1})$$$, либо $$$b_i$$$ делит $$$b_{i + 1}$$$, либо $$$b_{i + 1}$$$ делит $$$b_i$$$ (или оба числа делятся друг на друга); </li><li> $$$2 \sum \limits_{i = 1}^{n} |a_i - b_i| \le S$$$. </li></ul><p>Ваша задача — найти красивый массив. Можно показать, что по крайней мере один красивый массив всегда существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из двух строк. Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 50$$$).</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите красивый массив $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) на отдельной строке. Можно показать, что существует по крайней мере один красивый массив. Если ответов несколько, выведите любой из них.</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
2
4 6
2
1 1000000000
6
3 4 8 1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 3 3 3 3
3 6
1 1000000000
4 4 8 1 3 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="b2029f2eb894c38b92a7191a0e9651a5"/>
<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="caa689873c78fe2f6ee4f067504e7942b088601e"/>
<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='b2029f2eb894c38b92a7191a0e9651a5'> </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%2F1463%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='b2029f2eb894c38b92a7191a0e9651a5'/>
<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/1463">Educational Codeforces Round 100 (рейтинговый для Див. 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='b2029f2eb894c38b92a7191a0e9651a5'/>
<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/1463/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='b2029f2eb894c38b92a7191a0e9651a5'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="836002"/>
<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='b2029f2eb894c38b92a7191a0e9651a5'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="836002"/>
<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/85618" title="Educational Codeforces Round 100 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12640:12641" 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/85707" title="Разбор Educational Codeforces Round 100" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12653:12654" 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/1463">Задачи</a></li>
<li><a
href="/contest/1463/submit">Отослать</a></li>
<li><a
href="/contest/1463/my">Мои посылки</a></li>
<li><a
href="/contest/1463/status">Статус</a></li>
<li><a
href="/contest/1463/hacks">Взломы</a></li>
<li><a
href="/contest/1463/standings">Положение</a></li>
<li><a
href="/contest/1463/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_a22512d4ac8617ee4052301c508bdd2136e19c10">
<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]$$$ такой, что $$$1 \le a_i \le 10^9$$$. Пусть $$$S$$$ – сумма всех элементов массива $$$a$$$.</p><p>Назовем массив $$$b$$$, состоящий из $$$n$$$ целых чисел <span class="tex-font-style-bf">красивым</span>, если:</p><ul> <li> $$$1 \le b_i \le 10^9$$$ для всех $$$i$$$ от $$$1$$$ до $$$n$$$; </li><li> для каждой пары соседних целых чисел из массива $$$(b_i, b_{i + 1})$$$, либо $$$b_i$$$ делит $$$b_{i + 1}$$$, либо $$$b_{i + 1}$$$ делит $$$b_i$$$ (или оба числа делятся друг на друга); </li><li> $$$2 \sum \limits_{i = 1}^{n} |a_i - b_i| \le S$$$. </li></ul><p>Ваша задача — найти красивый массив. Можно показать, что по крайней мере один красивый массив всегда существует.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из двух строк. Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 50$$$).</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите красивый массив $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$) на отдельной строке. Можно показать, что существует по крайней мере один красивый массив. Если ответов несколько, выведите любой из них.</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
2
4 6
2
1 1000000000
6
3 4 8 1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 3 3 3 3
3 6
1 1000000000
4 4 8 1 3 3
</pre></div></div></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:18: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:'8124b63cdfe43a89',t:'MTY5NjY2NjY5MC4xODQwMDA='};_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", "\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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\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", "*1400"] | ||
1463C | 1463 | 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>У вас есть робот, который двигается по числовой прямой. В момент времени $$$0$$$ он находится в точке $$$0$$$.</p><p>Вы посылаете роботу $$$n$$$ команд: в $$$t_i$$$-ю секунды вы указываете робот пойти в точку $$$x_i$$$. Когда робот получает команду, он сразу же начинает движение в сторону точки $$$x_i$$$ со скоростью $$$1$$$ в секунду и останавливается, когда достигает этой точки. Однако, когда робот двигается, он <span class="tex-font-style-bf">игнорирует</span> все другие команды, которые он получает.</p><p>Например, предположим, что роботу приходят три команды: в секунду $$$1$$$ ехать в точку $$$5$$$, в секунду $$$3$$$ ехать в точку $$$0$$$ и в секунду $$$6$$$ ехать в точку $$$4$$$. Тогда робот будет стоять в $$$0$$$ до секунды $$$1$$$, затем начнет ехать к $$$5$$$, игнорируя вторую команду, достигнет $$$5$$$ в момент времени $$$6$$$ и сразу же начнет ехать к $$$4$$$, чтобы выполнить третью команду. В момент времени $$$7$$$ он доедет до $$$4$$$ и остановится там.</p><p>Команда $$$i$$$ считается выполненной успешно, если существует такой момент времени в отрезке $$$[t_i, t_{i + 1}]$$$ (то есть после того, как команда послана, и перед тем, как послана следующая, обе границы включительно; считаем $$$t_{n + 1} = +\infty$$$), что робот находится в позиции $$$x_i$$$. Посчитайте количество успешных команд. Обратите внимание, что проигнорированная команда все равно может быть успешной.</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$$$) — количество команд.</p><p>Затем $$$n$$$ строк описывают команды. В $$$i$$$-й из них записаны два целых числа $$$t_i$$$ и $$$x_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le x_i \le 10^9$$$) — время и точка назначения $$$i$$$-й команды.</p><p>Команды упорядочены по времени, то есть, $$$t_i < t_{i + 1}$$$ для всех возможных $$$i$$$.</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>
8
3
1 5
3 0
6 4
3
1 5
2 4
10 -5
5
2 -5
3 1
4 1
5 1
6 1
4
3 3
5 -3
9 2
12 0
8
1 1
2 -6
7 2
8 3
12 -9
14 2
18 -1
23 9
5
1 -4
4 -7
6 -1
7 -3
8 -7
2
1 2
2 -2
6
3 10
5 5
8 0
12 -4
14 -7
19 -5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
0
2
1
1
0
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Движение робота в первом наборе входных данных описано в условии задачи. Только последняя команда успешна.</p><p>Во втором наборе входных данных вторая команда успешна: робот проходит через точку назначения $$$4$$$ в момент времени $$$5$$$. К тому же, последняя команда тоже в конце концов станет успешной.</p><p>В третьем наборе входных данных ни одна команда не успешна, и робот остановится в $$$-5$$$ в секунду $$$7$$$.</p><p>Вот $$$0$$$-индексированные последовательности позиций робота в каждую секунду для каждого набора входных данных из примера. Все отрезанные позиции совпадают с последней: </p><ol> <li> $$$[0, 0, 1, 2, 3, 4, 5, 4, 4, \dots]$$$ </li><li> $$$[0, 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -5, \dots]$$$ </li><li> $$$[0, 0, 0, -1, -2, -3, -4, -5, -5, \dots]$$$ </li><li> $$$[0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, \dots]$$$ </li><li> $$$[0, 0, 1, 0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -7, -8, -9, -9, -9, -9, -8, -7, -6, -5, -4, -3, -2, -1, -1, \dots]$$$ </li><li> $$$[0, 0, -1, -2, -3, -4, -4, -3, -2, -1, -1, \dots]$$$ </li><li> $$$[0, 0, 1, 2, 2, \dots]$$$ </li><li> $$$[0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -7, \dots]$$$ </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="4f08a0884a168e0a6737cb5b87f3ce4a"/>
<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="caa689873c78fe2f6ee4f067504e7942b088601e"/>
<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='4f08a0884a168e0a6737cb5b87f3ce4a'> </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%2F1463%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='4f08a0884a168e0a6737cb5b87f3ce4a'/>
<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/1463">Educational Codeforces Round 100 (рейтинговый для Див. 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='4f08a0884a168e0a6737cb5b87f3ce4a'/>
<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/1463/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="Сложность">
*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='4f08a0884a168e0a6737cb5b87f3ce4a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="836003"/>
<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='4f08a0884a168e0a6737cb5b87f3ce4a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="836003"/>
<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/85618" title="Educational Codeforces Round 100 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12640:12641" 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/85707" title="Разбор Educational Codeforces Round 100" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12653:12654" 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/1463">Задачи</a></li>
<li><a
href="/contest/1463/submit">Отослать</a></li>
<li><a
href="/contest/1463/my">Мои посылки</a></li>
<li><a
href="/contest/1463/status">Статус</a></li>
<li><a
href="/contest/1463/hacks">Взломы</a></li>
<li><a
href="/contest/1463/standings">Положение</a></li>
<li><a
href="/contest/1463/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_ce9b335ed4afc54ec9d16ebaad4452a12d6c6900">
<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>У вас есть робот, который двигается по числовой прямой. В момент времени $$$0$$$ он находится в точке $$$0$$$.</p><p>Вы посылаете роботу $$$n$$$ команд: в $$$t_i$$$-ю секунды вы указываете робот пойти в точку $$$x_i$$$. Когда робот получает команду, он сразу же начинает движение в сторону точки $$$x_i$$$ со скоростью $$$1$$$ в секунду и останавливается, когда достигает этой точки. Однако, когда робот двигается, он <span class="tex-font-style-bf">игнорирует</span> все другие команды, которые он получает.</p><p>Например, предположим, что роботу приходят три команды: в секунду $$$1$$$ ехать в точку $$$5$$$, в секунду $$$3$$$ ехать в точку $$$0$$$ и в секунду $$$6$$$ ехать в точку $$$4$$$. Тогда робот будет стоять в $$$0$$$ до секунды $$$1$$$, затем начнет ехать к $$$5$$$, игнорируя вторую команду, достигнет $$$5$$$ в момент времени $$$6$$$ и сразу же начнет ехать к $$$4$$$, чтобы выполнить третью команду. В момент времени $$$7$$$ он доедет до $$$4$$$ и остановится там.</p><p>Команда $$$i$$$ считается выполненной успешно, если существует такой момент времени в отрезке $$$[t_i, t_{i + 1}]$$$ (то есть после того, как команда послана, и перед тем, как послана следующая, обе границы включительно; считаем $$$t_{n + 1} = +\infty$$$), что робот находится в позиции $$$x_i$$$. Посчитайте количество успешных команд. Обратите внимание, что проигнорированная команда все равно может быть успешной.</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$$$) — количество команд.</p><p>Затем $$$n$$$ строк описывают команды. В $$$i$$$-й из них записаны два целых числа $$$t_i$$$ и $$$x_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le x_i \le 10^9$$$) — время и точка назначения $$$i$$$-й команды.</p><p>Команды упорядочены по времени, то есть, $$$t_i < t_{i + 1}$$$ для всех возможных $$$i$$$.</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>
8
3
1 5
3 0
6 4
3
1 5
2 4
10 -5
5
2 -5
3 1
4 1
5 1
6 1
4
3 3
5 -3
9 2
12 0
8
1 1
2 -6
7 2
8 3
12 -9
14 2
18 -1
23 9
5
1 -4
4 -7
6 -1
7 -3
8 -7
2
1 2
2 -2
6
3 10
5 5
8 0
12 -4
14 -7
19 -5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
0
2
1
1
0
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Движение робота в первом наборе входных данных описано в условии задачи. Только последняя команда успешна.</p><p>Во втором наборе входных данных вторая команда успешна: робот проходит через точку назначения $$$4$$$ в момент времени $$$5$$$. К тому же, последняя команда тоже в конце концов станет успешной.</p><p>В третьем наборе входных данных ни одна команда не успешна, и робот остановится в $$$-5$$$ в секунду $$$7$$$.</p><p>Вот $$$0$$$-индексированные последовательности позиций робота в каждую секунду для каждого набора входных данных из примера. Все отрезанные позиции совпадают с последней: </p><ol> <li> $$$[0, 0, 1, 2, 3, 4, 5, 4, 4, \dots]$$$ </li><li> $$$[0, 0, 1, 2, 3, 4, 5, 5, 5, 5, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -5, \dots]$$$ </li><li> $$$[0, 0, 0, -1, -2, -3, -4, -5, -5, \dots]$$$ </li><li> $$$[0, 0, 0, 0, 1, 2, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, \dots]$$$ </li><li> $$$[0, 0, 1, 0, -1, -2, -3, -4, -5, -6, -6, -6, -6, -7, -8, -9, -9, -9, -9, -8, -7, -6, -5, -4, -3, -2, -1, -1, \dots]$$$ </li><li> $$$[0, 0, -1, -2, -3, -4, -4, -3, -2, -1, -1, \dots]$$$ </li><li> $$$[0, 0, 1, 2, 2, \dots]$$$ </li><li> $$$[0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -7, \dots]$$$ </li></ol></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:18: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:'8124b64579339d8a',t:'MTY5NjY2NjY5MS42ODMwMDA='};_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", "*1800"] | ||
1463D | 1463 | 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>У вас есть $$$2n$$$ целых чисел $$$1, 2, \dots, 2n$$$. Вы распределяете все $$$2n$$$ чисел на $$$n$$$ пар. После этого вы выбираете $$$x$$$ пар и из каждой из них берете минимум, а из каждой из оставшихся $$$n - x$$$ пар — максимум.</p><p>Ваша цель — получить в результате выбора элементов множество $$$\{b_1, b_2, \dots, b_n\}$$$.</p><p>Сколько существует различных $$$x$$$-в ($$$0 \le x \le n$$$) таких, что возможно получить множество $$$b$$$, если для каждого $$$x$$$ вы можете выбирать, как распределять числа и из каких $$$x$$$ пар выбирать минимумы?</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 2 \cdot 10^5$$$).</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_1 < b_2 < \dots < b_n \le 2n$$$) — множество, которое вы хотите получить.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите единственное число — количество различных $$$x$$$-в, таких, что возможно получить множество $$$b$$$.</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
1
5
1 4 5 9 10
2
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
3
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, $$$x = 1$$$ является единственным вариантом: у вас есть одна пара $$$(1, 2)$$$ и вы выбираете минимум в ней.</p><p>Во втором наборе, есть три возможных $$$x$$$-а. Если $$$x = 1$$$, то вы можете сформировать следующие пары: $$$(1, 6)$$$, $$$(2, 4)$$$, $$$(3, 5)$$$, $$$(7, 9)$$$, $$$(8, 10)$$$. Вы можете взять минимум из $$$(1, 6)$$$ (равный $$$1$$$) и максимумы из остальных пар, чтобы получить множество $$$b$$$.</p><p>Если $$$x = 2$$$, вы можете сформировать пары $$$(1, 2)$$$, $$$(3, 4)$$$, $$$(5, 6)$$$, $$$(7, 9)$$$, $$$(8, 10)$$$ и взять минимумы из $$$(1, 2)$$$, $$$(5, 6)$$$ и максимумы из остальных пар.</p><p>Если $$$x = 3$$$, вы можете сформировать пары $$$(1, 3)$$$, $$$(4, 6)$$$, $$$(5, 7)$$$, $$$(2, 9)$$$, $$$(8, 10)$$$ и взять минимумы из $$$(1, 3)$$$, $$$(4, 6)$$$, $$$(5, 7)$$$.</p><p>В третьем наборе, $$$x = 0$$$ является единственным вариантом: вы можете сформировать пары $$$(1, 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="2356329dd13a245a8749153acb82ee00"/>
<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="caa689873c78fe2f6ee4f067504e7942b088601e"/>
<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='2356329dd13a245a8749153acb82ee00'> </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%2F1463%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='2356329dd13a245a8749153acb82ee00'/>
<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/1463">Educational Codeforces Round 100 (рейтинговый для Див. 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='2356329dd13a245a8749153acb82ee00'/>
<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/1463/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='2356329dd13a245a8749153acb82ee00'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="836004"/>
<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='2356329dd13a245a8749153acb82ee00'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="836004"/>
<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/85618" title="Educational Codeforces Round 100 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12640:12641" 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/85707" title="Разбор Educational Codeforces Round 100" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12653:12654" 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/1463">Задачи</a></li>
<li><a
href="/contest/1463/submit">Отослать</a></li>
<li><a
href="/contest/1463/my">Мои посылки</a></li>
<li><a
href="/contest/1463/status">Статус</a></li>
<li><a
href="/contest/1463/hacks">Взломы</a></li>
<li><a
href="/contest/1463/standings">Положение</a></li>
<li><a
href="/contest/1463/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_5d3ce1f112e789979590053906e2d43c6916590a">
<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>У вас есть $$$2n$$$ целых чисел $$$1, 2, \dots, 2n$$$. Вы распределяете все $$$2n$$$ чисел на $$$n$$$ пар. После этого вы выбираете $$$x$$$ пар и из каждой из них берете минимум, а из каждой из оставшихся $$$n - x$$$ пар — максимум.</p><p>Ваша цель — получить в результате выбора элементов множество $$$\{b_1, b_2, \dots, b_n\}$$$.</p><p>Сколько существует различных $$$x$$$-в ($$$0 \le x \le n$$$) таких, что возможно получить множество $$$b$$$, если для каждого $$$x$$$ вы можете выбирать, как распределять числа и из каких $$$x$$$ пар выбирать минимумы?</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 2 \cdot 10^5$$$).</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_1 < b_2 < \dots < b_n \le 2n$$$) — множество, которое вы хотите получить.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите единственное число — количество различных $$$x$$$-в, таких, что возможно получить множество $$$b$$$.</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
1
5
1 4 5 9 10
2
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
3
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, $$$x = 1$$$ является единственным вариантом: у вас есть одна пара $$$(1, 2)$$$ и вы выбираете минимум в ней.</p><p>Во втором наборе, есть три возможных $$$x$$$-а. Если $$$x = 1$$$, то вы можете сформировать следующие пары: $$$(1, 6)$$$, $$$(2, 4)$$$, $$$(3, 5)$$$, $$$(7, 9)$$$, $$$(8, 10)$$$. Вы можете взять минимум из $$$(1, 6)$$$ (равный $$$1$$$) и максимумы из остальных пар, чтобы получить множество $$$b$$$.</p><p>Если $$$x = 2$$$, вы можете сформировать пары $$$(1, 2)$$$, $$$(3, 4)$$$, $$$(5, 6)$$$, $$$(7, 9)$$$, $$$(8, 10)$$$ и взять минимумы из $$$(1, 2)$$$, $$$(5, 6)$$$ и максимумы из остальных пар.</p><p>Если $$$x = 3$$$, вы можете сформировать пары $$$(1, 3)$$$, $$$(4, 6)$$$, $$$(5, 7)$$$, $$$(2, 9)$$$, $$$(8, 10)$$$ и взять минимумы из $$$(1, 3)$$$, $$$(4, 6)$$$, $$$(5, 7)$$$.</p><p>В третьем наборе, $$$x = 0$$$ является единственным вариантом: вы можете сформировать пары $$$(1, 3)$$$, $$$(2, 4)$$$ и взять максимумы из обеих пар.</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:18: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:'8124b64ebe139d87',t:'MTY5NjY2NjY5My4xMTkwMDA='};_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", "\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", "*1900"] | ||
1463E | 1463 | 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>Иван — учитель по программированию. В течение учебного года он планирует прочитать $$$n$$$ лекций на $$$n$$$ различных тем. Каждая тема должна быть использована ровно в одной лекции. Иван хочет выбрать, какую тему он будет объяснять во время $$$1$$$-й, $$$2$$$-й, ..., $$$n$$$-й лекции — формально он хочет выбрать некоторую перестановку целых чисел от $$$1$$$ до $$$n$$$ (назовем эту перестановку $$$q$$$). $$$q_i$$$ — это номер темы, которую Иван объяснит во время $$$i$$$-й лекции.</p><p>Для каждой темы (за исключением <span class="tex-font-style-bf">ровно одной</span>) существует обязательная предшествующая тема (для $$$i$$$-й темы предшествующая тема — $$$p_i$$$). Иван не может читать лекцию по теме, не прочитав лекцию по ее предшествующей теме. Существует по крайней мере один допустимый порядок тем в соответствии с этими предварительными ограничениями.</p><p>Правильный порядок тем может помочь студентам лучше понять лекции. У Ивана есть $$$k$$$ специальных пар тем $$$(x_i, y_i)$$$ таких, что он знает, что студенты лучше поймут $$$y_i$$$-ю тему, если лекция по ней будет проводиться <span class="tex-font-style-bf">сразу</span> после лекции по $$$x_i$$$-й теме. Иван хочет удовлетворить ограничениям на каждую такую пару, то есть для каждого $$$i \in [1, k]$$$ должно существовать некоторое $$$j \in [1, n - 1]$$$ такое, что $$$q_j = x_i$$$ и $$$q_{j + 1} = y_i$$$.</p><p>Теперь Иван хочет знать, существует ли порядок тем, удовлетворяющий всем этим ограничениям, и если хотя бы один из них существует, найти любой из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$1 \le k \le n - 1$$$) — количество тем и количество специальных пар тем соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ ($$$0 \le p_i \le n$$$), где $$$p_i$$$ — обязательная предшествующая тема для темы $$$i$$$ (или $$$p_i = 0$$$, если у $$$i$$$-й темы нет предшествующей темы). Ровно одно из этих целых чисел равно $$$0$$$. Существует по крайней мере один порядок тем, такой что для каждой темы $$$i$$$ тема $$$p_i$$$ идет до $$$i$$$-й темы. </p><p>Затем следует $$$k$$$ строк, $$$i$$$-я строка содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$) — темы из специальной пары $$$i$$$. Все значения $$$x_i$$$ попарно различны; аналогично, все значения $$$y_i$$$ попарно различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует порядка тем, удовлетворяющих всем ограничениям, выведите $$$0$$$.</p><p>В противном случае выведите $$$n$$$ попарно различных целых чисел $$$q_1$$$, $$$q_2$$$, ..., $$$q_n$$$ ($$$1 \le q_i \le n$$$) — порядок тем, удовлетворяющих всем ограничениям. Если ответов несколько, выведите любой из них.</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
2 3 0 5 3
1 5
5 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 2 1 5 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 2
2 3 0 5 3
1 5
5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1
2 3 0 5 3
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 5 2 1 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="3487ce0787ef33fc43da2817a0001373"/>
<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="caa689873c78fe2f6ee4f067504e7942b088601e"/>
<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='3487ce0787ef33fc43da2817a0001373'> </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%2F1463%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='3487ce0787ef33fc43da2817a0001373'/>
<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/1463">Educational Codeforces Round 100 (рейтинговый для Див. 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='3487ce0787ef33fc43da2817a0001373'/>
<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/1463/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="Сложность">
*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='3487ce0787ef33fc43da2817a0001373'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="836005"/>
<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='3487ce0787ef33fc43da2817a0001373'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="836005"/>
<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/85618" title="Educational Codeforces Round 100 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12640:12641" 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/85707" title="Разбор Educational Codeforces Round 100" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12653:12654" 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/1463">Задачи</a></li>
<li><a
href="/contest/1463/submit">Отослать</a></li>
<li><a
href="/contest/1463/my">Мои посылки</a></li>
<li><a
href="/contest/1463/status">Статус</a></li>
<li><a
href="/contest/1463/hacks">Взломы</a></li>
<li><a
href="/contest/1463/standings">Положение</a></li>
<li><a
href="/contest/1463/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_ca36dbe49da3e7bb4f955405bc5b532c800b4d26">
<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>Иван — учитель по программированию. В течение учебного года он планирует прочитать $$$n$$$ лекций на $$$n$$$ различных тем. Каждая тема должна быть использована ровно в одной лекции. Иван хочет выбрать, какую тему он будет объяснять во время $$$1$$$-й, $$$2$$$-й, ..., $$$n$$$-й лекции — формально он хочет выбрать некоторую перестановку целых чисел от $$$1$$$ до $$$n$$$ (назовем эту перестановку $$$q$$$). $$$q_i$$$ — это номер темы, которую Иван объяснит во время $$$i$$$-й лекции.</p><p>Для каждой темы (за исключением <span class="tex-font-style-bf">ровно одной</span>) существует обязательная предшествующая тема (для $$$i$$$-й темы предшествующая тема — $$$p_i$$$). Иван не может читать лекцию по теме, не прочитав лекцию по ее предшествующей теме. Существует по крайней мере один допустимый порядок тем в соответствии с этими предварительными ограничениями.</p><p>Правильный порядок тем может помочь студентам лучше понять лекции. У Ивана есть $$$k$$$ специальных пар тем $$$(x_i, y_i)$$$ таких, что он знает, что студенты лучше поймут $$$y_i$$$-ю тему, если лекция по ней будет проводиться <span class="tex-font-style-bf">сразу</span> после лекции по $$$x_i$$$-й теме. Иван хочет удовлетворить ограничениям на каждую такую пару, то есть для каждого $$$i \in [1, k]$$$ должно существовать некоторое $$$j \in [1, n - 1]$$$ такое, что $$$q_j = x_i$$$ и $$$q_{j + 1} = y_i$$$.</p><p>Теперь Иван хочет знать, существует ли порядок тем, удовлетворяющий всем этим ограничениям, и если хотя бы один из них существует, найти любой из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$1 \le k \le n - 1$$$) — количество тем и количество специальных пар тем соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ ($$$0 \le p_i \le n$$$), где $$$p_i$$$ — обязательная предшествующая тема для темы $$$i$$$ (или $$$p_i = 0$$$, если у $$$i$$$-й темы нет предшествующей темы). Ровно одно из этих целых чисел равно $$$0$$$. Существует по крайней мере один порядок тем, такой что для каждой темы $$$i$$$ тема $$$p_i$$$ идет до $$$i$$$-й темы. </p><p>Затем следует $$$k$$$ строк, $$$i$$$-я строка содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$) — темы из специальной пары $$$i$$$. Все значения $$$x_i$$$ попарно различны; аналогично, все значения $$$y_i$$$ попарно различны.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует порядка тем, удовлетворяющих всем ограничениям, выведите $$$0$$$.</p><p>В противном случае выведите $$$n$$$ попарно различных целых чисел $$$q_1$$$, $$$q_2$$$, ..., $$$q_n$$$ ($$$1 \le q_i \le n$$$) — порядок тем, удовлетворяющих всем ограничениям. Если ответов несколько, выведите любой из них.</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
2 3 0 5 3
1 5
5 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 2 1 5 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 2
2 3 0 5 3
1 5
5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1
2 3 0 5 3
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 4
2 3 0 5 3
2 1
3 5
5 2
1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 5 2 1 4
</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:18: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:'8124b657aba34d8c',t:'MTY5NjY2NjY5NC43MDIwMDA='};_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", "\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\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", "\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043d\u043c", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2400"] | ||
1463F | 1463 | F | ru | F. Максимальное правильное множество | <div class="problem-statement"><div class="header"><div class="title">F. Максимальное правильное множество</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>Назовем множество положительных целых чисел $$$S$$$ <span class="tex-font-style-bf">правильным</span>, если выполняются следующие два условия: </p><ul> <li> $$$S \subseteq \{1, 2, \dots, n\}$$$; </li><li> если $$$a \in S$$$ и $$$b \in S$$$, то $$$|a-b| \neq x$$$ и $$$|a-b| \neq y$$$. </li></ul><p>Для заданных значений $$$n$$$, $$$x$$$ и $$$y$$$ вам необходимо найти размер максимального <span class="tex-font-style-bf">правильного</span> множества.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка входных данных содержит три целых числа $$$n$$$, $$$x$$$ и $$$y$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le x, y \le 22$$$).</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>
10 2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
21 4 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
9
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1337 7 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
672
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
455678451 22 17
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
221997195
</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="a27132f460948d15fd3f84a77a0af252"/>
<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="caa689873c78fe2f6ee4f067504e7942b088601e"/>
<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='a27132f460948d15fd3f84a77a0af252'> </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%2F1463%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='a27132f460948d15fd3f84a77a0af252'/>
<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/1463">Educational Codeforces Round 100 (рейтинговый для Див. 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='a27132f460948d15fd3f84a77a0af252'/>
<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/1463/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="Сложность">
*3100
</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='a27132f460948d15fd3f84a77a0af252'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="836006"/>
<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='a27132f460948d15fd3f84a77a0af252'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="836006"/>
<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/85618" title="Educational Codeforces Round 100 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12640:12641" 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/85707" title="Разбор Educational Codeforces Round 100" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12653:12654" 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/1463">Задачи</a></li>
<li><a
href="/contest/1463/submit">Отослать</a></li>
<li><a
href="/contest/1463/my">Мои посылки</a></li>
<li><a
href="/contest/1463/status">Статус</a></li>
<li><a
href="/contest/1463/hacks">Взломы</a></li>
<li><a
href="/contest/1463/standings">Положение</a></li>
<li><a
href="/contest/1463/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_f93d9a5e9ed52d72ba31a4f26b91cc4ada3b8d72">
<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>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>Назовем множество положительных целых чисел $$$S$$$ <span class="tex-font-style-bf">правильным</span>, если выполняются следующие два условия: </p><ul> <li> $$$S \subseteq \{1, 2, \dots, n\}$$$; </li><li> если $$$a \in S$$$ и $$$b \in S$$$, то $$$|a-b| \neq x$$$ и $$$|a-b| \neq y$$$. </li></ul><p>Для заданных значений $$$n$$$, $$$x$$$ и $$$y$$$ вам необходимо найти размер максимального <span class="tex-font-style-bf">правильного</span> множества.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Единственная строка входных данных содержит три целых числа $$$n$$$, $$$x$$$ и $$$y$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le x, y \le 22$$$).</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>
10 2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
21 4 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
9
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1337 7 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
672
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
455678451 22 17
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
221997195
</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:18: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:'8124b6618c4b1640',t:'MTY5NjY2NjY5Ni4wMjYwMDA='};_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", "\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", "\u0434\u043f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*3100"] | ||
1464A | 1464 | 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 \times n$$$. Строки и столбцы доски пронумерованы от $$$1$$$ до $$$n$$$. Клетка $$$(x, y)$$$ лежит на пересечении столбца номер $$$x$$$ и строки номер $$$y$$$. </p><p>Ладья это шахматная фигура, которая за один ход может переместиться на любое количество клеток по вертикали, либо по горизонтали. На доске размещены $$$m$$$ ладей ($$$m < n$$$), которые не бьют друг друга. То есть, нет пары ладей, стоящих на одной вертикали или горизонтали.</p><p>За один ход можно сделать ход одной из ладей. То есть, переместить ее на любое количество клеток по вертикали или горизонтали. При этом, после хода ладья снова не должна оказаться под боем других ладей. Какое минимальное количество ходов нужно сделать, чтобы разместить все ладьи на главной диагонали?</p><p>Главной диагональю называются клетки $$$(i, i)$$$, где $$$1 \le i \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано целое число $$$t$$$ — количество тестовых случаев ($$$1 \leq t \leq 10^3$$$). Далее дано описание $$$t$$$ тестовых случаев.</p><p>В первой строке даны два целых числа $$$n$$$ и $$$m$$$ — размер поля и количество ладей ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m < n$$$). Следующие $$$m$$$ строк содержат пары целых чисел $$$x_i$$$ и $$$y_i$$$ — позиции ладей, $$$i$$$-я ладья исходно стоит в клетке $$$(x_i, y_i)$$$ ($$$1 \leq x_i, y_i \leq n$$$). Гарантируется, что в исходной расстановке ладьи не бьют друг друга.</p><p>Сумма $$$n$$$ по всем тестовым случаям не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из $$$t$$$ тестовых случаев в новой строке выведите наименьшее количество ходов, которые требуются, чтобы поставить все ладьи на главную диагональ.</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
3 1
2 3
3 2
2 1
1 2
5 3
2 3
3 1
1 2
5 4
4 5
5 1
2 2
3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
3
4
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможные ходы для первых трех тестовых случаев:</p><ol> <li> $$$(2, 3) \to (2, 2)$$$ </li><li> $$$(2, 1) \to (2, 3)$$$, $$$(1, 2) \to (1, 1)$$$, $$$(2, 3) \to (2, 2)$$$ </li><li> $$$(2, 3) \to (2, 4)$$$, $$$(2, 4) \to (4, 4)$$$, $$$(3, 1) \to (3, 3)$$$, $$$(1, 2) \to (1, 1)$$$ </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="3f10e82e06b4ff2429ad96c5851b7e39"/>
<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="3c9dc94db75d508298c615d1b3169900cb351547"/>
<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='3f10e82e06b4ff2429ad96c5851b7e39'> </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%2F1464%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='3f10e82e06b4ff2429ad96c5851b7e39'/>
<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/1464">Codeforces Round 692 (Div. 1, основан на Отборочном раунде 3 Технокубка 2021)</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='3f10e82e06b4ff2429ad96c5851b7e39'/>
<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/1464/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='3f10e82e06b4ff2429ad96c5851b7e39'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="839210"/>
<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='3f10e82e06b4ff2429ad96c5851b7e39'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="839210"/>
<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="12660:12661" 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="12671:12672" 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/1464">Задачи</a></li>
<li><a
href="/contest/1464/submit">Отослать</a></li>
<li><a
href="/contest/1464/my">Мои посылки</a></li>
<li><a
href="/contest/1464/status">Статус</a></li>
<li><a
href="/contest/1464/hacks">Взломы</a></li>
<li><a
href="/contest/1464/room/1">Комната</a></li>
<li><a
href="/contest/1464/standings">Положение</a></li>
<li><a
href="/contest/1464/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_1f830f0dc17303f908ae29add143d05e00a386ea">
<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 \times n$$$. Строки и столбцы доски пронумерованы от $$$1$$$ до $$$n$$$. Клетка $$$(x, y)$$$ лежит на пересечении столбца номер $$$x$$$ и строки номер $$$y$$$. </p><p>Ладья это шахматная фигура, которая за один ход может переместиться на любое количество клеток по вертикали, либо по горизонтали. На доске размещены $$$m$$$ ладей ($$$m < n$$$), которые не бьют друг друга. То есть, нет пары ладей, стоящих на одной вертикали или горизонтали.</p><p>За один ход можно сделать ход одной из ладей. То есть, переместить ее на любое количество клеток по вертикали или горизонтали. При этом, после хода ладья снова не должна оказаться под боем других ладей. Какое минимальное количество ходов нужно сделать, чтобы разместить все ладьи на главной диагонали?</p><p>Главной диагональю называются клетки $$$(i, i)$$$, где $$$1 \le i \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано целое число $$$t$$$ — количество тестовых случаев ($$$1 \leq t \leq 10^3$$$). Далее дано описание $$$t$$$ тестовых случаев.</p><p>В первой строке даны два целых числа $$$n$$$ и $$$m$$$ — размер поля и количество ладей ($$$2 \leq n \leq 10^5$$$, $$$1 \leq m < n$$$). Следующие $$$m$$$ строк содержат пары целых чисел $$$x_i$$$ и $$$y_i$$$ — позиции ладей, $$$i$$$-я ладья исходно стоит в клетке $$$(x_i, y_i)$$$ ($$$1 \leq x_i, y_i \leq n$$$). Гарантируется, что в исходной расстановке ладьи не бьют друг друга.</p><p>Сумма $$$n$$$ по всем тестовым случаям не превышает $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из $$$t$$$ тестовых случаев в новой строке выведите наименьшее количество ходов, которые требуются, чтобы поставить все ладьи на главную диагональ.</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
3 1
2 3
3 2
2 1
1 2
5 3
2 3
3 1
1 2
5 4
4 5
5 1
2 2
3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
3
4
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможные ходы для первых трех тестовых случаев:</p><ol> <li> $$$(2, 3) \to (2, 2)$$$ </li><li> $$$(2, 1) \to (2, 3)$$$, $$$(1, 2) \to (1, 1)$$$, $$$(2, 3) \to (2, 2)$$$ </li><li> $$$(2, 3) \to (2, 4)$$$, $$$(2, 4) \to (4, 4)$$$, $$$(3, 1) \to (3, 3)$$$, $$$(1, 2) \to (1, 1)$$$ </li></ol></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:18: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:'8124b669ddd72de6',t:'MTY5NjY2NjY5Ny41MzcwMDA='};_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", "\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\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"] | ["\u0433\u0440\u0430\u0444\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\u043d\u043c", "*1700"] | ||
1464B | 1464 | 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-tt">01</span> в рэп ХХОСа хейтеры напишут $$$x$$$ гневных комментариев, а за каждое вхождение <span class="tex-font-style-bf">подпоследовательности</span> <span class="tex-font-style-tt">10</span> будет написано $$$y$$$ гневных комментариев. Вы должны заменить каждый знак вопроса на <span class="tex-font-style-tt">0</span> либо <span class="tex-font-style-tt">1</span>, чтобы минимизировать число гневных комментариев, которые получит ХХОС.</p><p>Подпоследовательностью строки $$$a$$$ называется строка $$$b$$$, которая может получиться в результате удаления нескольких символов из строки $$$a$$$. Два вхождения подпоследовательности считаются разными, если различаются множества позиций оставленных символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записан рэп ХХОСа — строка $$$s$$$ ($$$1 \le |s| \leq 10^5$$$). Во второй строке даны два целых числа $$$x$$$ и $$$y$$$ — количество гневных комментариев, которые ХХОС получит за каждую подпоследовательность <span class="tex-font-style-tt">01</span> и <span class="tex-font-style-tt">10</span>, соответственно ($$$0 \leq x, y \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>
0?1
2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
?????
13 37
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
?10?
239 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
28
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
01101001
5 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
96
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере одним из оптимальных вариантов замены является <span class="tex-font-style-tt">001</span>. Тогда в строке будет $$$2$$$ подпоследовательности <span class="tex-font-style-tt">01</span> и $$$0$$$ подпоследовательностей <span class="tex-font-style-tt">10</span>. Суммарное количество гневных комментариев равно $$$2 \cdot 2 + 0 \cdot 3 = 4$$$.</p><p>Во втором примере одним из оптимальных вариантов замены является <span class="tex-font-style-tt">11111</span>. Тогда в строке будет $$$0$$$ подпоследовательностей <span class="tex-font-style-tt">01</span> и $$$0$$$ подпоследовательностей <span class="tex-font-style-tt">10</span>. Суммарное количество гневных комментариев равно $$$0 \cdot 13 + 0 \cdot 37 = 0$$$.</p><p>В третьем примере одним из оптимальных вариантов замены является <span class="tex-font-style-tt">1100</span>. Тогда в строке будет $$$0$$$ подпоследовательностей <span class="tex-font-style-tt">01</span> и $$$4$$$ подпоследовательности <span class="tex-font-style-tt">10</span>. Суммарное количество гневных комментариев равно $$$0 \cdot 239 + 4 \cdot 7 = 28$$$.</p><p>В четвёртом примере одним из оптимальных вариантов замены является <span class="tex-font-style-tt">01101001</span>. Тогда в строке будет $$$8$$$ подпоследовательностей <span class="tex-font-style-tt">01</span> и $$$8$$$ подпоследовательностей <span class="tex-font-style-tt">10</span>. Суммарное количество гневных комментариев равно $$$8 \cdot 5 + 8 \cdot 7 = 96$$$.</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="6053558a670f2c446b09613a1809eed2"/>
<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="3c9dc94db75d508298c615d1b3169900cb351547"/>
<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='6053558a670f2c446b09613a1809eed2'> </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%2F1464%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='6053558a670f2c446b09613a1809eed2'/>
<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/1464">Codeforces Round 692 (Div. 1, основан на Отборочном раунде 3 Технокубка 2021)</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='6053558a670f2c446b09613a1809eed2'/>
<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/1464/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="Сложность">
*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='6053558a670f2c446b09613a1809eed2'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="839211"/>
<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='6053558a670f2c446b09613a1809eed2'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="839211"/>
<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="12660:12661" 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="12671:12672" 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/1464">Задачи</a></li>
<li><a
href="/contest/1464/submit">Отослать</a></li>
<li><a
href="/contest/1464/my">Мои посылки</a></li>
<li><a
href="/contest/1464/status">Статус</a></li>
<li><a
href="/contest/1464/hacks">Взломы</a></li>
<li><a
href="/contest/1464/room/1">Комната</a></li>
<li><a
href="/contest/1464/standings">Положение</a></li>
<li><a
href="/contest/1464/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_b8942c5a2033eddb7a252bcd6d2ec007de73bd0b">
<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-tt">01</span> в рэп ХХОСа хейтеры напишут $$$x$$$ гневных комментариев, а за каждое вхождение <span class="tex-font-style-bf">подпоследовательности</span> <span class="tex-font-style-tt">10</span> будет написано $$$y$$$ гневных комментариев. Вы должны заменить каждый знак вопроса на <span class="tex-font-style-tt">0</span> либо <span class="tex-font-style-tt">1</span>, чтобы минимизировать число гневных комментариев, которые получит ХХОС.</p><p>Подпоследовательностью строки $$$a$$$ называется строка $$$b$$$, которая может получиться в результате удаления нескольких символов из строки $$$a$$$. Два вхождения подпоследовательности считаются разными, если различаются множества позиций оставленных символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записан рэп ХХОСа — строка $$$s$$$ ($$$1 \le |s| \leq 10^5$$$). Во второй строке даны два целых числа $$$x$$$ и $$$y$$$ — количество гневных комментариев, которые ХХОС получит за каждую подпоследовательность <span class="tex-font-style-tt">01</span> и <span class="tex-font-style-tt">10</span>, соответственно ($$$0 \leq x, y \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>
0?1
2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
?????
13 37
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
?10?
239 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
28
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
01101001
5 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
96
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере одним из оптимальных вариантов замены является <span class="tex-font-style-tt">001</span>. Тогда в строке будет $$$2$$$ подпоследовательности <span class="tex-font-style-tt">01</span> и $$$0$$$ подпоследовательностей <span class="tex-font-style-tt">10</span>. Суммарное количество гневных комментариев равно $$$2 \cdot 2 + 0 \cdot 3 = 4$$$.</p><p>Во втором примере одним из оптимальных вариантов замены является <span class="tex-font-style-tt">11111</span>. Тогда в строке будет $$$0$$$ подпоследовательностей <span class="tex-font-style-tt">01</span> и $$$0$$$ подпоследовательностей <span class="tex-font-style-tt">10</span>. Суммарное количество гневных комментариев равно $$$0 \cdot 13 + 0 \cdot 37 = 0$$$.</p><p>В третьем примере одним из оптимальных вариантов замены является <span class="tex-font-style-tt">1100</span>. Тогда в строке будет $$$0$$$ подпоследовательностей <span class="tex-font-style-tt">01</span> и $$$4$$$ подпоследовательности <span class="tex-font-style-tt">10</span>. Суммарное количество гневных комментариев равно $$$0 \cdot 239 + 4 \cdot 7 = 28$$$.</p><p>В четвёртом примере одним из оптимальных вариантов замены является <span class="tex-font-style-tt">01101001</span>. Тогда в строке будет $$$8$$$ подпоследовательностей <span class="tex-font-style-tt">01</span> и $$$8$$$ подпоследовательностей <span class="tex-font-style-tt">10</span>. Суммарное количество гневных комментариев равно $$$8 \cdot 5 + 8 \cdot 7 = 96$$$.</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:18: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:'8124b6733b854971',t:'MTY5NjY2NjY5OC44OTIwMDA='};_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\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", "\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.", "\u0422\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\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\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "*2100"] | ||
1464C | 1464 | 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>Ваш друг прислал вам строку $$$S$$$, состоящую из $$$n$$$ строчных английских букв. Оказывается, это число, записанное в <span class="tex-font-style-it">ромской</span> системе счисления. Знания о ромских числах давно утрачены, но сохранился алгоритм перевода ромских чисел в привычные нам. Пронумеруем символы $$$S$$$ от $$$1$$$ до $$$n$$$ слева направо. Значение числа $$$S$$$ обозначим как $$$f(S)$$$, оно определяется следующим образом: </p><ul> <li> Если $$$|S| > 1$$$, то выбирается произвольное значение $$$m$$$ ($$$1 \le m < |S|$$$) и считается, что $$$f(S) = -f(S[1, m]) + f(S[m + 1, |S|])$$$, где $$$S[l, r]$$$ — это подстрока $$$S$$$ с $$$l$$$-й позиции до $$$r$$$-й включительно. </li><li> Иначе $$$S = c$$$, где $$$c$$$ — какая-то буква. В таком случае $$$f(S) = 2^{pos(c)}$$$, где $$$pos(c)$$$ — это позиция буквы $$$c$$$ в английском алфавите ($$$pos($$$<span class="tex-font-style-tt">a</span>$$$) = 0$$$, $$$pos($$$<span class="tex-font-style-tt">z</span>$$$) = 25$$$). </li></ul><p>Обратите внимание, что $$$m$$$ выбирается независимо на каждом шаге.</p><p>Друг уверен, что правильно выбирая $$$m$$$ на каждом шаге, можно получить $$$f(S) = T$$$. Прав ли он?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны числа $$$n$$$ и $$$T$$$ ($$$2 \leq n \leq 10^5$$$, $$$-10^{15} \leq T \leq 10^{15}$$$).</p><p>Во второй строке дана строка $$$S$$$ длины $$$n$$$, состоящая из строчных английских букв.</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><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 -1
ba
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 -7
abc
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 -475391
qohshra
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере нельзя получить $$$-7$$$. Но можно получить, например, $$$1$$$ следующим образом: </p><ol> <li> Сперва выбираем $$$m = 1$$$, тогда $$$f($$$<span class="tex-font-style-tt">abc</span>$$$) = -f($$$<span class="tex-font-style-tt">a</span>$$$) + f($$$<span class="tex-font-style-tt">bc</span>$$$)$$$ </li><li> $$$f($$$<span class="tex-font-style-tt">a</span>$$$) = 2^0 = 1$$$ </li><li> $$$f($$$<span class="tex-font-style-tt">bc</span>$$$) = -f($$$<span class="tex-font-style-tt">b</span>$$$) + f($$$<span class="tex-font-style-tt">c</span>$$$) = -2^1 + 2^2 = 2$$$ </li><li> Итого $$$f($$$<span class="tex-font-style-tt">abc</span>$$$) = -1 + 2 = 1$$$ </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="db3ccecb14a31a0f442bd74edfaa19dc"/>
<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="3c9dc94db75d508298c615d1b3169900cb351547"/>
<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='db3ccecb14a31a0f442bd74edfaa19dc'> </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%2F1464%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='db3ccecb14a31a0f442bd74edfaa19dc'/>
<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/1464">Codeforces Round 692 (Div. 1, основан на Отборочном раунде 3 Технокубка 2021)</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='db3ccecb14a31a0f442bd74edfaa19dc'/>
<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/1464/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='db3ccecb14a31a0f442bd74edfaa19dc'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="839212"/>
<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='db3ccecb14a31a0f442bd74edfaa19dc'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="839212"/>
<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="12660:12661" 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="12671:12672" 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/1464">Задачи</a></li>
<li><a
href="/contest/1464/submit">Отослать</a></li>
<li><a
href="/contest/1464/my">Мои посылки</a></li>
<li><a
href="/contest/1464/status">Статус</a></li>
<li><a
href="/contest/1464/hacks">Взломы</a></li>
<li><a
href="/contest/1464/room/1">Комната</a></li>
<li><a
href="/contest/1464/standings">Положение</a></li>
<li><a
href="/contest/1464/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_71e63c506f9bd96c94c652b80f7b4ab5147cb90b">
<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>Ваш друг прислал вам строку $$$S$$$, состоящую из $$$n$$$ строчных английских букв. Оказывается, это число, записанное в <span class="tex-font-style-it">ромской</span> системе счисления. Знания о ромских числах давно утрачены, но сохранился алгоритм перевода ромских чисел в привычные нам. Пронумеруем символы $$$S$$$ от $$$1$$$ до $$$n$$$ слева направо. Значение числа $$$S$$$ обозначим как $$$f(S)$$$, оно определяется следующим образом: </p><ul> <li> Если $$$|S| > 1$$$, то выбирается произвольное значение $$$m$$$ ($$$1 \le m < |S|$$$) и считается, что $$$f(S) = -f(S[1, m]) + f(S[m + 1, |S|])$$$, где $$$S[l, r]$$$ — это подстрока $$$S$$$ с $$$l$$$-й позиции до $$$r$$$-й включительно. </li><li> Иначе $$$S = c$$$, где $$$c$$$ — какая-то буква. В таком случае $$$f(S) = 2^{pos(c)}$$$, где $$$pos(c)$$$ — это позиция буквы $$$c$$$ в английском алфавите ($$$pos($$$<span class="tex-font-style-tt">a</span>$$$) = 0$$$, $$$pos($$$<span class="tex-font-style-tt">z</span>$$$) = 25$$$). </li></ul><p>Обратите внимание, что $$$m$$$ выбирается независимо на каждом шаге.</p><p>Друг уверен, что правильно выбирая $$$m$$$ на каждом шаге, можно получить $$$f(S) = T$$$. Прав ли он?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны числа $$$n$$$ и $$$T$$$ ($$$2 \leq n \leq 10^5$$$, $$$-10^{15} \leq T \leq 10^{15}$$$).</p><p>Во второй строке дана строка $$$S$$$ длины $$$n$$$, состоящая из строчных английских букв.</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><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 -1
ba
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 -7
abc
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
7 -475391
qohshra
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере нельзя получить $$$-7$$$. Но можно получить, например, $$$1$$$ следующим образом: </p><ol> <li> Сперва выбираем $$$m = 1$$$, тогда $$$f($$$<span class="tex-font-style-tt">abc</span>$$$) = -f($$$<span class="tex-font-style-tt">a</span>$$$) + f($$$<span class="tex-font-style-tt">bc</span>$$$)$$$ </li><li> $$$f($$$<span class="tex-font-style-tt">a</span>$$$) = 2^0 = 1$$$ </li><li> $$$f($$$<span class="tex-font-style-tt">bc</span>$$$) = -f($$$<span class="tex-font-style-tt">b</span>$$$) + f($$$<span class="tex-font-style-tt">c</span>$$$) = -2^1 + 2^2 = 2$$$ </li><li> Итого $$$f($$$<span class="tex-font-style-tt">abc</span>$$$) = -1 + 2 = 1$$$ </li></ol></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:18: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:'8124b67b9da79db0',t:'MTY5NjY2NjcwMC4yMzkwMDA='};_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", "\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", "\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2300"] | ||
1464D | 1464 | 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>Легенда гласит, что в Ханойском храме хранится перестановка чисел от $$$1$$$ до $$$n$$$. Перед храмом в линию лежат $$$n$$$ разноцветных камней. Жрецы могут проводить следующую операцию над камнями: выбрать позицию $$$i$$$ ($$$1 \le i \le n$$$) и циклически сдвинуть камни на позициях $$$i$$$, $$$p[i]$$$, $$$p[p[i]]$$$, .... То есть, камень с позиции $$$i$$$ перейдет на позицию $$$p[i]$$$, камень с позиции $$$p[i]$$$ перейдет на позицию $$$p[p[i]]$$$, и т.д., на позицию $$$i$$$ перейдет камень с позиции $$$j$$$, такой что $$$p[j] = i$$$.</p><p>Каждый день жрецы обязаны получать новую расстановку камней, используя произвольное количество этих операций. Когда все возможные расстановки будут получены, наступит конец света. Вам стало интересно, что если бы перед самым началом можно было бы поменять местами некоторые элементы перестановки? Сколько дней бы просуществовал мир? </p><p>Вы хотите за минимальное количество обменов двух элементов, получить перестановку, которая позволит миру просуществовать как можно дольше.</p><p>Две расстановки камней, считаются различными, если существует позиция $$$i$$$ такая, что цвета камней на этой позиции в расстановках различаются.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано целое число $$$t$$$ — количество тестовых случаев ($$$1 \leq t \leq 10^3$$$). Далее дано описание тестовых случаев.</p><p>В первой строке дано целое число $$$n$$$ — длина перестановки ($$$3 \leq n \leq 10^6$$$). Во второй строке находится $$$n$$$ целых чисел $$$p_1, \dots, p_n$$$ — перестановка ($$$1 \le p_i \le n$$$). Гарантируется, что $$$p$$$ является перестановкой.</p><p>Сумма $$$n$$$ по всем тестовым случаям не превышает $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из $$$t$$$ тестовых случаев в новой строке выведите два целых числа: наибольшее возможное количество дней, которые может просуществовать мир, по модулю $$$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
3
2 3 1
3
2 1 3
3
1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 0
3 1
3 2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
4
2 3 4 1
4
2 3 1 4
4
2 1 4 3
4
2 1 3 4
4
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4 0
4 1
4 0
4 1
4 2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обозначим цвета камней буквами. Пояснения для первых двух тестовых случаев первого примера: </p><ol> <li> Используя перестановку $$$[2, 3, 1]$$$, из <span class="tex-font-style-tt">ABC</span> можно дополнительно получить расстановки <span class="tex-font-style-tt">CAB</span> и <span class="tex-font-style-tt">BCA</span>. Что уже является максимально возможным результатом. </li><li> Используя перестановку $$$[2, 1, 3]$$$, из <span class="tex-font-style-tt">ABC</span> можно получить только <span class="tex-font-style-tt">BAC</span>. Как мы видели в предыдущем примере, две расстановки не являются максимально возможным количеством для $$$n = 3$$$. Для получения оптимальной перестановки, например, можно поменять местами $$$1$$$ и $$$3$$$, чтобы получить перестановку $$$[2, 3, 1]$$$. </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="63bccb5f16b78129915d63fc25a511e9"/>
<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="3c9dc94db75d508298c615d1b3169900cb351547"/>
<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='63bccb5f16b78129915d63fc25a511e9'> </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%2F1464%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='63bccb5f16b78129915d63fc25a511e9'/>
<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/1464">Codeforces Round 692 (Div. 1, основан на Отборочном раунде 3 Технокубка 2021)</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='63bccb5f16b78129915d63fc25a511e9'/>
<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/1464/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="Сложность">
*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='63bccb5f16b78129915d63fc25a511e9'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="839213"/>
<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='63bccb5f16b78129915d63fc25a511e9'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="839213"/>
<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="12660:12661" 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="12671:12672" 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/1464">Задачи</a></li>
<li><a
href="/contest/1464/submit">Отослать</a></li>
<li><a
href="/contest/1464/my">Мои посылки</a></li>
<li><a
href="/contest/1464/status">Статус</a></li>
<li><a
href="/contest/1464/hacks">Взломы</a></li>
<li><a
href="/contest/1464/room/1">Комната</a></li>
<li><a
href="/contest/1464/standings">Положение</a></li>
<li><a
href="/contest/1464/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_74071336798380ee4e904e3bfdef16ec7812b978">
<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>Легенда гласит, что в Ханойском храме хранится перестановка чисел от $$$1$$$ до $$$n$$$. Перед храмом в линию лежат $$$n$$$ разноцветных камней. Жрецы могут проводить следующую операцию над камнями: выбрать позицию $$$i$$$ ($$$1 \le i \le n$$$) и циклически сдвинуть камни на позициях $$$i$$$, $$$p[i]$$$, $$$p[p[i]]$$$, .... То есть, камень с позиции $$$i$$$ перейдет на позицию $$$p[i]$$$, камень с позиции $$$p[i]$$$ перейдет на позицию $$$p[p[i]]$$$, и т.д., на позицию $$$i$$$ перейдет камень с позиции $$$j$$$, такой что $$$p[j] = i$$$.</p><p>Каждый день жрецы обязаны получать новую расстановку камней, используя произвольное количество этих операций. Когда все возможные расстановки будут получены, наступит конец света. Вам стало интересно, что если бы перед самым началом можно было бы поменять местами некоторые элементы перестановки? Сколько дней бы просуществовал мир? </p><p>Вы хотите за минимальное количество обменов двух элементов, получить перестановку, которая позволит миру просуществовать как можно дольше.</p><p>Две расстановки камней, считаются различными, если существует позиция $$$i$$$ такая, что цвета камней на этой позиции в расстановках различаются.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано целое число $$$t$$$ — количество тестовых случаев ($$$1 \leq t \leq 10^3$$$). Далее дано описание тестовых случаев.</p><p>В первой строке дано целое число $$$n$$$ — длина перестановки ($$$3 \leq n \leq 10^6$$$). Во второй строке находится $$$n$$$ целых чисел $$$p_1, \dots, p_n$$$ — перестановка ($$$1 \le p_i \le n$$$). Гарантируется, что $$$p$$$ является перестановкой.</p><p>Сумма $$$n$$$ по всем тестовым случаям не превышает $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого из $$$t$$$ тестовых случаев в новой строке выведите два целых числа: наибольшее возможное количество дней, которые может просуществовать мир, по модулю $$$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
3
2 3 1
3
2 1 3
3
1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 0
3 1
3 2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
4
2 3 4 1
4
2 3 1 4
4
2 1 4 3
4
2 1 3 4
4
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4 0
4 1
4 0
4 1
4 2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Обозначим цвета камней буквами. Пояснения для первых двух тестовых случаев первого примера: </p><ol> <li> Используя перестановку $$$[2, 3, 1]$$$, из <span class="tex-font-style-tt">ABC</span> можно дополнительно получить расстановки <span class="tex-font-style-tt">CAB</span> и <span class="tex-font-style-tt">BCA</span>. Что уже является максимально возможным результатом. </li><li> Используя перестановку $$$[2, 1, 3]$$$, из <span class="tex-font-style-tt">ABC</span> можно получить только <span class="tex-font-style-tt">BAC</span>. Как мы видели в предыдущем примере, две расстановки не являются максимально возможным количеством для $$$n = 3$$$. Для получения оптимальной перестановки, например, можно поменять местами $$$1$$$ и $$$3$$$, чтобы получить перестановку $$$[2, 3, 1]$$$. </li></ol></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:18: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:'8124b68429ce160a',t:'MTY5NjY2NjcwMS41NzcwMDA='};_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", "*3000"] | ||
1464E | 1464 | 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$$$ вершинами: </p><ol> <li> Целое число $$$v$$$ выбирается случайно и равновероятно из $$$[1, n + 1]$$$. </li><li> Если $$$v \leq n$$$, в $$$v$$$-ю вершину графа добавляется фишка, а процесс переходит к шагу 1. </li><li> Если $$$v = n + 1$$$, Алиса и Боб играют в описанную выше игру на данном графе с текущим расположением фишек, определяется победитель этой игры. После чего, процесс завершается. </li></ol><p>Найдите вероятность победы Алисы. Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ — взаимно простые целые числа, $$$Q \not\equiv 0 \pmod{998\,244\,353}$$$. Выведите значение $$$P \cdot Q^{-1} \bmod 998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два целых числа $$$n$$$ и $$$m$$$ — количество вершин и ребер в графе ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq 10^5$$$).</p><p>Затем следует $$$m$$$ строк, в $$$i$$$-й из которых содержатся два целых числа $$$u_i$$$ и $$$v_i$$$ — начало и конец $$$i$$$-го ребра ($$$1 \leq u_i, v_i \leq n$$$). Гарантируется, что граф является ациклическим.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите вероятность победы Алисы по модулю $$$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>
1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 1
1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
332748118
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5
1 4
5 2
4 3
1 5
5 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
931694730
</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="bab0da4a32713acca9fe1f356914a45d"/>
<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="3c9dc94db75d508298c615d1b3169900cb351547"/>
<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='bab0da4a32713acca9fe1f356914a45d'> </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%2F1464%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='bab0da4a32713acca9fe1f356914a45d'/>
<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/1464">Codeforces Round 692 (Div. 1, основан на Отборочном раунде 3 Технокубка 2021)</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='bab0da4a32713acca9fe1f356914a45d'/>
<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/1464/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='bab0da4a32713acca9fe1f356914a45d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="839214"/>
<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='bab0da4a32713acca9fe1f356914a45d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="839214"/>
<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="12660:12661" 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="12671:12672" 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/1464">Задачи</a></li>
<li><a
href="/contest/1464/submit">Отослать</a></li>
<li><a
href="/contest/1464/my">Мои посылки</a></li>
<li><a
href="/contest/1464/status">Статус</a></li>
<li><a
href="/contest/1464/hacks">Взломы</a></li>
<li><a
href="/contest/1464/room/1">Комната</a></li>
<li><a
href="/contest/1464/standings">Положение</a></li>
<li><a
href="/contest/1464/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_5294704e35b9abb6e9f57c28363ce51316a2ff37">
<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$$$ вершинами: </p><ol> <li> Целое число $$$v$$$ выбирается случайно и равновероятно из $$$[1, n + 1]$$$. </li><li> Если $$$v \leq n$$$, в $$$v$$$-ю вершину графа добавляется фишка, а процесс переходит к шагу 1. </li><li> Если $$$v = n + 1$$$, Алиса и Боб играют в описанную выше игру на данном графе с текущим расположением фишек, определяется победитель этой игры. После чего, процесс завершается. </li></ol><p>Найдите вероятность победы Алисы. Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ — взаимно простые целые числа, $$$Q \not\equiv 0 \pmod{998\,244\,353}$$$. Выведите значение $$$P \cdot Q^{-1} \bmod 998\,244\,353$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке даны два целых числа $$$n$$$ и $$$m$$$ — количество вершин и ребер в графе ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq 10^5$$$).</p><p>Затем следует $$$m$$$ строк, в $$$i$$$-й из которых содержатся два целых числа $$$u_i$$$ и $$$v_i$$$ — начало и конец $$$i$$$-го ребра ($$$1 \leq u_i, v_i \leq n$$$). Гарантируется, что граф является ациклическим.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите вероятность победы Алисы по модулю $$$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>
1 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 1
1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
332748118
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5
1 4
5 2
4 3
1 5
5 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
931694730
</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:18: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:'8124b68c8aa975a3',t:'MTY5NjY2NjcwMi45MDUwMDA='};_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", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\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\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u0438\u0435 \u043c\u0430\u0442\u0440\u0438\u0446, \u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044c, \u043f\u0440\u0430\u0432\u0438\u043b\u043e \u041a\u0440\u0430\u043c\u0435\u0440\u0430, \u0441\u0438\u0441\u0442\u0435\u043c\u044b \u043b\u0438\u043d\u0435\u0439\u043d\u044b\u0445 \u0443\u0440\u0430\u0432\u043d\u0435\u043d\u0438\u0439", "\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"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u0438\u0433\u0440\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043c\u0430\u0442\u0440\u0438\u0446\u044b", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*2700"] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.