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
|
---|---|---|---|---|---|---|---|---|---|---|
1353F | 1353 | 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.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>Вы играете в одну популярную sandbox-игру с трехмерным миром. Карта мира может быть представлена в виде матрицы размера $$$n \times m$$$, где высота клетки $$$(i, j)$$$ равна $$$a_{i, j}$$$.</p><p>Сейчас вы находитесь в клетке $$$(1, 1)$$$ и хотите попасть в клетку $$$(n, m)$$$. Вы можете перемещаться только вниз (из клетки $$$(i, j)$$$ в клетку $$$(i + 1, j)$$$) или вправо (из клетки $$$(i, j)$$$ в клетку $$$(i, j + 1)$$$). Также есть дополнительное <span class="tex-font-style-bf">ограничение</span>: если высота текущей клетки равна $$$x$$$, то вы можете переместиться только в клетку с высотой $$$x+1$$$.</p><p><span class="tex-font-style-bf">Перед первым перемещением</span> вы можете выполнить несколько операций. В течение одной операции вы можете уменьшить высоту <span class="tex-font-style-bf">любой</span> клетки на единицу. То есть вы выбираете какую-то клетку $$$(i, j)$$$ и присваиваете $$$a_{i, j} := a_{i, j} - 1$$$. Заметьте, что вы <span class="tex-font-style-bf">можете</span> делать высоты <span class="tex-font-style-bf">меньшими или равными нулю</span>. Также заметьте, что вы <span class="tex-font-style-bf">можете</span> уменьшать высоту клетки $$$(1, 1)$$$.</p><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> количество операций, которое необходимо выполнить, чтобы получить хотя бы один подходящий путь из клетки $$$(1, 1)$$$ в клетку $$$(n, m)$$$. Гарантируется, что ответ существует.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — Количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 100$$$) — количество строк и количество столбцов в карте мира. Следующие $$$n$$$ строк содержат по $$$m$$$ целых чисел каждая, где $$$j$$$-е число в $$$i$$$-й строке равно $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 10^{15}$$$) — высоте клетки $$$(i, j)$$$.</p><p>Гарантируется, что сумма $$$n$$$ (также как сумма $$$m$$$) по всем наборам тестовых данных не превосходит $$$100$$$ ($$$\sum n \le 100; \sum m \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ — <span class="tex-font-style-bf">минимальное</span> количество операций, которое необходимо выполнить, чтобы получить хотя бы один подходящий путь из клетки $$$(1, 1)$$$ в клетку $$$(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 4
1 2 3 4
5 6 7 8
9 10 11 12
5 5
2 5 4 8 3
9 10 11 5 1
12 8 4 2 5
2 2 5 4 1
6 8 2 4 2
2 2
100 10
10 1
1 2
123456789876543 987654321234567
1 1
42
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
9
49
111
864197531358023
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="7fd2e3b0f741ae3484b0250ec2e7b16a"/>
<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="134b039cb4ec8c6d4592abffb422fda7ed92ea33"/>
<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='7fd2e3b0f741ae3484b0250ec2e7b16a'> </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%2F1353%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='7fd2e3b0f741ae3484b0250ec2e7b16a'/>
<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/1353">Codeforces Round 642 (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='7fd2e3b0f741ae3484b0250ec2e7b16a'/>
<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/1353/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='7fd2e3b0f741ae3484b0250ec2e7b16a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="620792"/>
<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='7fd2e3b0f741ae3484b0250ec2e7b16a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="620792"/>
<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/77309" title="Codeforces Round #642 (Div. 3)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10943" resourceName="Codeforces Round #642 (Div. 3)"
resourceManual="true" src="//codeforces.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/77373" title="Codeforces Round #642 (Div. 3) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10944" resourceName="Codeforces Round #642 (Div. 3) 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/1353">Задачи</a></li>
<li><a
href="/contest/1353/submit">Отослать</a></li>
<li><a
href="/contest/1353/my">Мои посылки</a></li>
<li><a
href="/contest/1353/status">Статус</a></li>
<li><a
href="/contest/1353/hacks">Взломы</a></li>
<li><a
href="/contest/1353/standings">Положение</a></li>
<li><a
href="/contest/1353/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_a9654a74f73d11d44e968084837b3f18c9028c86">
<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.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>Вы играете в одну популярную sandbox-игру с трехмерным миром. Карта мира может быть представлена в виде матрицы размера $$$n \times m$$$, где высота клетки $$$(i, j)$$$ равна $$$a_{i, j}$$$.</p><p>Сейчас вы находитесь в клетке $$$(1, 1)$$$ и хотите попасть в клетку $$$(n, m)$$$. Вы можете перемещаться только вниз (из клетки $$$(i, j)$$$ в клетку $$$(i + 1, j)$$$) или вправо (из клетки $$$(i, j)$$$ в клетку $$$(i, j + 1)$$$). Также есть дополнительное <span class="tex-font-style-bf">ограничение</span>: если высота текущей клетки равна $$$x$$$, то вы можете переместиться только в клетку с высотой $$$x+1$$$.</p><p><span class="tex-font-style-bf">Перед первым перемещением</span> вы можете выполнить несколько операций. В течение одной операции вы можете уменьшить высоту <span class="tex-font-style-bf">любой</span> клетки на единицу. То есть вы выбираете какую-то клетку $$$(i, j)$$$ и присваиваете $$$a_{i, j} := a_{i, j} - 1$$$. Заметьте, что вы <span class="tex-font-style-bf">можете</span> делать высоты <span class="tex-font-style-bf">меньшими или равными нулю</span>. Также заметьте, что вы <span class="tex-font-style-bf">можете</span> уменьшать высоту клетки $$$(1, 1)$$$.</p><p>Ваша задача — найти <span class="tex-font-style-bf">минимальное</span> количество операций, которое необходимо выполнить, чтобы получить хотя бы один подходящий путь из клетки $$$(1, 1)$$$ в клетку $$$(n, m)$$$. Гарантируется, что ответ существует.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов тестовых данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — Количество наборов тестовых данных. Затем следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка набора тестовых данных содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 100$$$) — количество строк и количество столбцов в карте мира. Следующие $$$n$$$ строк содержат по $$$m$$$ целых чисел каждая, где $$$j$$$-е число в $$$i$$$-й строке равно $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 10^{15}$$$) — высоте клетки $$$(i, j)$$$.</p><p>Гарантируется, что сумма $$$n$$$ (также как сумма $$$m$$$) по всем наборам тестовых данных не превосходит $$$100$$$ ($$$\sum n \le 100; \sum m \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите ответ — <span class="tex-font-style-bf">минимальное</span> количество операций, которое необходимо выполнить, чтобы получить хотя бы один подходящий путь из клетки $$$(1, 1)$$$ в клетку $$$(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 4
1 2 3 4
5 6 7 8
9 10 11 12
5 5
2 5 4 8 3
9 10 11 5 1
12 8 4 2 5
2 2 5 4 1
6 8 2 4 2
2 2
100 10
10 1
1 2
123456789876543 987654321234567
1 1
42
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
9
49
111
864197531358023
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:03: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:'8124a0e7d9ba161c',t:'MTY5NjY2NTgxNi40MzAwMDA='};_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", "*2200"] | ||
1354A | 1354 | 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$$$ минут, чтобы отдохнуть.</p><p><span class="tex-font-style-bf">Поликарп может проснуться только от звука будильника.</span> Он только заснул, а его первый будильник прозвонит ровно через $$$b$$$ минут.</p><p>Каждый раз когда Поликарп просыпается, он решает, заводить ли будильник еще раз или нет. Если он проспал меньше $$$a$$$ минут суммарно, то он заводит будильник так, чтобы тот прозвонил ровно через $$$c$$$ минут, и тратит $$$d$$$ минут, чтобы снова заснуть. Иначе же он встает с кровати, начиная новый день.</p><p>Если будильник звонит, пока Поликарп все еще засыпает, то он снова его заводит на $$$c$$$ минут и опять тратит $$$d$$$ минут, чтобы заснуть.</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 1000$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора входных данных записаны четыре целых числа $$$a, b, c, d$$$ ($$$1 \le a, b, c, d \le 10^9$$$) — время, которое необходимо Поликарпу, чтобы выспаться, время до первого звонка будильника, время до каждого последующего звонка будильника и время, необходимое Поликарпу, чтобы заснуть.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно целое число. Если Поликарп никогда не встанет с кровати, то выведите <span class="tex-font-style-tt">-1</span>. Иначе выведите время, которое Поликарп потратит до того, как встать с кровати.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
10 3 6 4
11 3 6 4
5 9 4 10
6 5 2 3
1 1 1 1
3947465 47342 338129 123123
234123843 13 361451236 361451000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
27
27
9
-1
1
6471793
358578060125049
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Поликарп просыпается через $$$3$$$ минуты. Он отдохнул только $$$3$$$ минуты из необходимых $$$10$$$. Поэтому он снова заводит будильник, чтобы тот прозвенел через $$$6$$$ минут, и тратит $$$4$$$ минуты, чтобы уснуть. То есть он отдыхает в течение еще $$$2$$$ минут, что суммируется в $$$3+2=5$$$ минут сна. Он повторяет эту процедуру еще три раза, и получается $$$11$$$ минут сна. Наконец, он встает с кровати. Он потратил $$$3$$$ минуты до первого будильника, в потом заново завел будильник четыре раза. Ответ равен $$$3+4 \cdot 6 = 27$$$.</p><p>Второй набор входных данных похож на первый, но Поликарпу надо $$$11$$$ минут, чтобы выспаться, вместо $$$10$$$. Однако, это ничего не меняет, потому что Поликарп получает $$$11$$$ минут сна при таких настройках будильника так и так.</p><p>В третьем наборе входных данных Поликарп просыпается достаточно отдохнувшим уже после первого будильника. Поэтому ответ равен $$$b=9$$$.</p><p>В четвертом наборе входных данных Поликарп просыпается через $$$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="d4fab95bb2bc8c0f76e4ef04b5c57e9a"/>
<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="44f62d4b558bd2705c65f1533d7b7f4199a9561f"/>
<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='d4fab95bb2bc8c0f76e4ef04b5c57e9a'> </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%2F1354%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='d4fab95bb2bc8c0f76e4ef04b5c57e9a'/>
<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/1354">Educational Codeforces Round 87 (рейтинговый для Див. 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='d4fab95bb2bc8c0f76e4ef04b5c57e9a'/>
<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/1354/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="Сложность">
*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='d4fab95bb2bc8c0f76e4ef04b5c57e9a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="623444"/>
<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='d4fab95bb2bc8c0f76e4ef04b5c57e9a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="623444"/>
<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/77454" title="Educational Codeforces Round 87 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10899:10900" 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/77593" title="77593" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10923:10924" 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/1354">Задачи</a></li>
<li><a
href="/contest/1354/submit">Отослать</a></li>
<li><a
href="/contest/1354/my">Мои посылки</a></li>
<li><a
href="/contest/1354/status">Статус</a></li>
<li><a
href="/contest/1354/hacks">Взломы</a></li>
<li><a
href="/contest/1354/standings">Положение</a></li>
<li><a
href="/contest/1354/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_cf233c98ce76dfa50f343872ba724ed19d37ac90">
<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$$$ минут, чтобы отдохнуть.</p><p><span class="tex-font-style-bf">Поликарп может проснуться только от звука будильника.</span> Он только заснул, а его первый будильник прозвонит ровно через $$$b$$$ минут.</p><p>Каждый раз когда Поликарп просыпается, он решает, заводить ли будильник еще раз или нет. Если он проспал меньше $$$a$$$ минут суммарно, то он заводит будильник так, чтобы тот прозвонил ровно через $$$c$$$ минут, и тратит $$$d$$$ минут, чтобы снова заснуть. Иначе же он встает с кровати, начиная новый день.</p><p>Если будильник звонит, пока Поликарп все еще засыпает, то он снова его заводит на $$$c$$$ минут и опять тратит $$$d$$$ минут, чтобы заснуть.</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 1000$$$) — количество наборов входных данных.</p><p>В единственной строке каждого набора входных данных записаны четыре целых числа $$$a, b, c, d$$$ ($$$1 \le a, b, c, d \le 10^9$$$) — время, которое необходимо Поликарпу, чтобы выспаться, время до первого звонка будильника, время до каждого последующего звонка будильника и время, необходимое Поликарпу, чтобы заснуть.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно целое число. Если Поликарп никогда не встанет с кровати, то выведите <span class="tex-font-style-tt">-1</span>. Иначе выведите время, которое Поликарп потратит до того, как встать с кровати.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
10 3 6 4
11 3 6 4
5 9 4 10
6 5 2 3
1 1 1 1
3947465 47342 338129 123123
234123843 13 361451236 361451000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
27
27
9
-1
1
6471793
358578060125049
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Поликарп просыпается через $$$3$$$ минуты. Он отдохнул только $$$3$$$ минуты из необходимых $$$10$$$. Поэтому он снова заводит будильник, чтобы тот прозвенел через $$$6$$$ минут, и тратит $$$4$$$ минуты, чтобы уснуть. То есть он отдыхает в течение еще $$$2$$$ минут, что суммируется в $$$3+2=5$$$ минут сна. Он повторяет эту процедуру еще три раза, и получается $$$11$$$ минут сна. Наконец, он встает с кровати. Он потратил $$$3$$$ минуты до первого будильника, в потом заново завел будильник четыре раза. Ответ равен $$$3+4 \cdot 6 = 27$$$.</p><p>Второй набор входных данных похож на первый, но Поликарпу надо $$$11$$$ минут, чтобы выспаться, вместо $$$10$$$. Однако, это ничего не меняет, потому что Поликарп получает $$$11$$$ минут сна при таких настройках будильника так и так.</p><p>В третьем наборе входных данных Поликарп просыпается достаточно отдохнувшим уже после первого будильника. Поэтому ответ равен $$$b=9$$$.</p><p>В четвертом наборе входных данных Поликарп просыпается через $$$5$$$ минут. К сожалению, дальше он не может отдохнуть ни минуты, заводя будильник все снова и снова бесконечно :(</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:03: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:'8124a0f05f2b165a',t:'MTY5NjY2NTgxNy44NzAwMDA='};_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", "*900"] | ||
1354B | 1354 | 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$$$, каждый символ которой — <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> или <span class="tex-font-style-tt">3</span>. Вы должны выбрать кратчайшую непрерывную подстроку $$$s$$$, в которой каждый из трех символов встречается хотя бы один раз.</p><p>Непрерывная подстрока $$$s$$$ — строка, которую можно получить из $$$s$$$ удалением какого-то количества (возможно, ни одного) символов из начала строки $$$s$$$ и какого-то количества (возможно, ни одного) символов из конца строки $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 20000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки $$$s$$$ ($$$1 \le |s| \le 200000$$$). Гарантируется, что каждый символ $$$s$$$ — <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> или <span class="tex-font-style-tt">3</span>.</p><p>Сумма длин всех строк не превосходит $$$200000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно число — длину кратчайшей подстроки $$$s$$$, содержащей символы всех трех типов. Если такой подстроки нет, выведите $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
123
12222133333332
112233
332211
12121212
333333
31121
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
3
4
4
0
0
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим пример из условия:</p><p>В первом наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">123</span>.</p><p>Во втором наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">213</span>.</p><p>В третьем наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">1223</span>.</p><p>В четвертом наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">3221</span>.</p><p>В пятом наборе входных данных в $$$s$$$ нету символа <span class="tex-font-style-tt">3</span>.</p><p>В шестом наборе входных данных в $$$s$$$ нету символа <span class="tex-font-style-tt">1</span>.</p><p>В седьмом наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">3112</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="f9e0883ce7ecfa74edc7c18bbf7ce2cb"/>
<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="44f62d4b558bd2705c65f1533d7b7f4199a9561f"/>
<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='f9e0883ce7ecfa74edc7c18bbf7ce2cb'> </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%2F1354%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='f9e0883ce7ecfa74edc7c18bbf7ce2cb'/>
<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/1354">Educational Codeforces Round 87 (рейтинговый для Див. 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='f9e0883ce7ecfa74edc7c18bbf7ce2cb'/>
<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/1354/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="Сложность">
*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='f9e0883ce7ecfa74edc7c18bbf7ce2cb'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="623445"/>
<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='f9e0883ce7ecfa74edc7c18bbf7ce2cb'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="623445"/>
<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/77454" title="Educational Codeforces Round 87 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10899:10900" 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/77593" title="77593" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10923:10924" 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/1354">Задачи</a></li>
<li><a
href="/contest/1354/submit">Отослать</a></li>
<li><a
href="/contest/1354/my">Мои посылки</a></li>
<li><a
href="/contest/1354/status">Статус</a></li>
<li><a
href="/contest/1354/hacks">Взломы</a></li>
<li><a
href="/contest/1354/standings">Положение</a></li>
<li><a
href="/contest/1354/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_b7d22d87185f1511cc124217e795b2f1a5e32ede">
<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$$$, каждый символ которой — <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> или <span class="tex-font-style-tt">3</span>. Вы должны выбрать кратчайшую непрерывную подстроку $$$s$$$, в которой каждый из трех символов встречается хотя бы один раз.</p><p>Непрерывная подстрока $$$s$$$ — строка, которую можно получить из $$$s$$$ удалением какого-то количества (возможно, ни одного) символов из начала строки $$$s$$$ и какого-то количества (возможно, ни одного) символов из конца строки $$$s$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 20000$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных состоит из одной строки $$$s$$$ ($$$1 \le |s| \le 200000$$$). Гарантируется, что каждый символ $$$s$$$ — <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> или <span class="tex-font-style-tt">3</span>.</p><p>Сумма длин всех строк не превосходит $$$200000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно число — длину кратчайшей подстроки $$$s$$$, содержащей символы всех трех типов. Если такой подстроки нет, выведите $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
123
12222133333332
112233
332211
12121212
333333
31121
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
3
4
4
0
0
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим пример из условия:</p><p>В первом наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">123</span>.</p><p>Во втором наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">213</span>.</p><p>В третьем наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">1223</span>.</p><p>В четвертом наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">3221</span>.</p><p>В пятом наборе входных данных в $$$s$$$ нету символа <span class="tex-font-style-tt">3</span>.</p><p>В шестом наборе входных данных в $$$s$$$ нету символа <span class="tex-font-style-tt">1</span>.</p><p>В седьмом наборе входных данных можно использовать подстроку <span class="tex-font-style-tt">3112</span>.</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:03: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:'8124a0f97c74149c',t:'MTY5NjY2NTgxOS4yNTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1200"] | ||
1354C1 | 1354 | C1 | ru | C1. Просто вписываем многоугольник | <div class="problem-statement"><div class="header"><div class="title">C1. Просто вписываем многоугольник</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">Условие этой задачи почти полностью совпадает с условием задачи C2. Единственное отличие в следующем: в задаче C1 $$$n$$$ всегда четно, а в задаче C2 $$$n$$$ всегда нечетно.</span></p><p>Вам задан правильный многоугольник из $$$2 \cdot n$$$ вершин (то есть он выпуклый и имеет равные стороны и углы) и все его стороны имеют длину $$$1$$$. Назовем этот многоугольник $$$2n$$$-угольником.</p><p>Ваша задача — найти квадрат минимального размера, такой что в него можно вписать $$$2n$$$-угольник. $$$2n$$$-угольник можно вписать в квадрат, если $$$2n$$$-угольник можно разместить таким образом, что каждая точка, лежащая внутри или на границе $$$2n$$$-угольника также будет лежать внутри или на границе квадрата.</p><p>Вы можете вращать $$$2n$$$-угольник и/или квадрат.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$T$$$ ($$$1 \le T \le 200$$$) — количество наборов входных данных.</p><p>В следующих $$$T$$$ строках заданы описания наборов — по одной строке на набор. В каждой строке задано единственное <span class="tex-font-style-bf">четное</span> целое число $$$n$$$ ($$$2 \le n \le 200$$$). Не забывайте, что вам нужно вписать $$$2n$$$-угольник, а не $$$n$$$-угольник.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ действительных чисел — по одному на набор входных данных. Для каждого набора, выведите минимальную длину стороны квадрата, в который можно вписать $$$2n$$$-угольник. Ваш ответ будет считаться правильным, если его абсолютная или относительная погрешность не превосходит $$$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>
3
2
4
200
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1.000000000
2.414213562
127.321336469
</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="043ac30911a8532caac078943c65a369"/>
<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="44f62d4b558bd2705c65f1533d7b7f4199a9561f"/>
<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='043ac30911a8532caac078943c65a369'> </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%2F1354%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='043ac30911a8532caac078943c65a369'/>
<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/1354">Educational Codeforces Round 87 (рейтинговый для Див. 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='043ac30911a8532caac078943c65a369'/>
<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/1354/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='043ac30911a8532caac078943c65a369'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="623456"/>
<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='043ac30911a8532caac078943c65a369'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="623456"/>
<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/77454" title="Educational Codeforces Round 87 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10899:10900" 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/77593" title="77593" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10923:10924" 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/1354">Задачи</a></li>
<li><a
href="/contest/1354/submit">Отослать</a></li>
<li><a
href="/contest/1354/my">Мои посылки</a></li>
<li><a
href="/contest/1354/status">Статус</a></li>
<li><a
href="/contest/1354/hacks">Взломы</a></li>
<li><a
href="/contest/1354/standings">Положение</a></li>
<li><a
href="/contest/1354/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_37f74bb1f9a63fb68ced4d0706cc4d1a6b503d28">
<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. Просто вписываем многоугольник</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">Условие этой задачи почти полностью совпадает с условием задачи C2. Единственное отличие в следующем: в задаче C1 $$$n$$$ всегда четно, а в задаче C2 $$$n$$$ всегда нечетно.</span></p><p>Вам задан правильный многоугольник из $$$2 \cdot n$$$ вершин (то есть он выпуклый и имеет равные стороны и углы) и все его стороны имеют длину $$$1$$$. Назовем этот многоугольник $$$2n$$$-угольником.</p><p>Ваша задача — найти квадрат минимального размера, такой что в него можно вписать $$$2n$$$-угольник. $$$2n$$$-угольник можно вписать в квадрат, если $$$2n$$$-угольник можно разместить таким образом, что каждая точка, лежащая внутри или на границе $$$2n$$$-угольника также будет лежать внутри или на границе квадрата.</p><p>Вы можете вращать $$$2n$$$-угольник и/или квадрат.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$T$$$ ($$$1 \le T \le 200$$$) — количество наборов входных данных.</p><p>В следующих $$$T$$$ строках заданы описания наборов — по одной строке на набор. В каждой строке задано единственное <span class="tex-font-style-bf">четное</span> целое число $$$n$$$ ($$$2 \le n \le 200$$$). Не забывайте, что вам нужно вписать $$$2n$$$-угольник, а не $$$n$$$-угольник.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ действительных чисел — по одному на набор входных данных. Для каждого набора, выведите минимальную длину стороны квадрата, в который можно вписать $$$2n$$$-угольник. Ваш ответ будет считаться правильным, если его абсолютная или относительная погрешность не превосходит $$$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>
3
2
4
200
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1.000000000
2.414213562
127.321336469
</pre></div></div></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:03: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:'8124a1021c1f16f0',t:'MTY5NjY2NTgyMC42ODUwMDA='};_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", "\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\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "*1400"] | ||
1354C2 | 1354 | C2 | ru | C2. Не так просто вписываем многоугольник | <div class="problem-statement"><div class="header"><div class="title">C2. Не так просто вписываем многоугольник</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">Условие этой задачи почти полностью совпадает с условием задачи C1. Единственное отличие в следующем: в задаче C1 $$$n$$$ всегда четно, а в задаче C2 $$$n$$$ всегда нечетно.</span></p><p>Вам задан правильный многоугольник из $$$2 \cdot n$$$ вершин (то есть он выпуклый и имеет равные стороны и углы) и все его стороны имеют длину $$$1$$$. Назовем этот многоугольник $$$2n$$$-угольником.</p><p>Ваша задача — найти квадрат минимального размера, такой что в него можно вписать $$$2n$$$-угольник. $$$2n$$$-угольник можно вписать в квадрат, если $$$2n$$$-угольник можно разместить таким образом, что каждая точка, лежащая внутри или на границе $$$2n$$$-угольника также будет лежать внутри или на границе квадрата.</p><p>Вы можете вращать $$$2n$$$-угольник и/или квадрат.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$T$$$ ($$$1 \le T \le 200$$$) — количество наборов входных данных.</p><p>В следующих $$$T$$$ строках заданы описания наборов — по одной строке на набор. В каждой строке задано единственное <span class="tex-font-style-bf">нечетное</span> целое число $$$n$$$ ($$$3 \le n \le 199$$$). Не забывайте, что вам нужно вписать $$$2n$$$-угольник, а не $$$n$$$-угольник.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ действительных чисел — по одному на набор входных данных. Для каждого набора, выведите минимальную длину стороны квадрата, в который можно вписать $$$2n$$$-угольник. Ваш ответ будет считаться правильным, если его абсолютная или относительная погрешность не превосходит $$$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>
3
3
5
199
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1.931851653
3.196226611
126.687663595
</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="68d2bebcae24112850054003f7af94b1"/>
<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="44f62d4b558bd2705c65f1533d7b7f4199a9561f"/>
<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='68d2bebcae24112850054003f7af94b1'> </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%2F1354%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='68d2bebcae24112850054003f7af94b1'/>
<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/1354">Educational Codeforces Round 87 (рейтинговый для Див. 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='68d2bebcae24112850054003f7af94b1'/>
<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/1354/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='68d2bebcae24112850054003f7af94b1'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="623446"/>
<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='68d2bebcae24112850054003f7af94b1'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="623446"/>
<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/77454" title="Educational Codeforces Round 87 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10899:10900" 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/77593" title="77593" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10923:10924" 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/1354">Задачи</a></li>
<li><a
href="/contest/1354/submit">Отослать</a></li>
<li><a
href="/contest/1354/my">Мои посылки</a></li>
<li><a
href="/contest/1354/status">Статус</a></li>
<li><a
href="/contest/1354/hacks">Взломы</a></li>
<li><a
href="/contest/1354/standings">Положение</a></li>
<li><a
href="/contest/1354/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_1c0e17428c07bc8278873d1696a7507d9636fa56">
<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. Не так просто вписываем многоугольник</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">Условие этой задачи почти полностью совпадает с условием задачи C1. Единственное отличие в следующем: в задаче C1 $$$n$$$ всегда четно, а в задаче C2 $$$n$$$ всегда нечетно.</span></p><p>Вам задан правильный многоугольник из $$$2 \cdot n$$$ вершин (то есть он выпуклый и имеет равные стороны и углы) и все его стороны имеют длину $$$1$$$. Назовем этот многоугольник $$$2n$$$-угольником.</p><p>Ваша задача — найти квадрат минимального размера, такой что в него можно вписать $$$2n$$$-угольник. $$$2n$$$-угольник можно вписать в квадрат, если $$$2n$$$-угольник можно разместить таким образом, что каждая точка, лежащая внутри или на границе $$$2n$$$-угольника также будет лежать внутри или на границе квадрата.</p><p>Вы можете вращать $$$2n$$$-угольник и/или квадрат.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано целое число $$$T$$$ ($$$1 \le T \le 200$$$) — количество наборов входных данных.</p><p>В следующих $$$T$$$ строках заданы описания наборов — по одной строке на набор. В каждой строке задано единственное <span class="tex-font-style-bf">нечетное</span> целое число $$$n$$$ ($$$3 \le n \le 199$$$). Не забывайте, что вам нужно вписать $$$2n$$$-угольник, а не $$$n$$$-угольник.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ действительных чисел — по одному на набор входных данных. Для каждого набора, выведите минимальную длину стороны квадрата, в который можно вписать $$$2n$$$-угольник. Ваш ответ будет считаться правильным, если его абсолютная или относительная погрешность не превосходит $$$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>
3
3
5
199
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1.931851653
3.196226611
126.687663595
</pre></div></div></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:03:42</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a10afc3b0056',t:'MTY5NjY2NTgyMi4xMTgwMDA='};_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", "\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\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2000"] | ||
1354D | 1354 | 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>28 мегабайт</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><ul> <li> добавить элемент $$$k$$$ в мультимножество; </li><li> найти $$$k$$$-ю порядковую статистику в мультимножестве и удалить ее. </li></ul><p>Напомним, что $$$k$$$-я порядковая статистика в мультимножестве — это элемент, который будет на позиции $$$k$$$, если выписать все его элементы в порядке неубывания. Например, если в мультимножестве содержатся числа $$$1$$$, $$$4$$$, $$$2$$$, $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$ и $$$k = 3$$$, то необходимо найти $$$3$$$-й элемент в списке $$$[1, 1, 2, 4, 4, 5, 7]$$$, и он равен $$$2$$$. Если в мультимножестве несколько копий удаляемого элемента, удаляется только одна из них.</p><p>После всех запросов выведите <span class="tex-font-style-bf">любое</span> число, принадлежащее мультимножеству, или сообщите, что оно пустое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два числа $$$n$$$ и $$$q$$$ ($$$1 \le n, q \le 10^6$$$) — количество элементов в мультимножестве и количество запросов, соответственно.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_1 \le a_2 \le \dots \le a_n \le n$$$) — элементы мультимножества.</p><p>В третьей строке заданы $$$q$$$ целых чисел $$$k_1$$$, $$$k_2$$$, ..., $$$k_q$$$, каждое из которых описывает очередной запрос следующим образом: </p><ul> <li> если $$$1 \le k_i \le n$$$, то $$$i$$$-й запрос — «добавить $$$k_i$$$ в мультимножество»; </li><li> если $$$k_i < 0$$$, то $$$i$$$-й запрос — «удалить $$$|k_i|$$$-ю порядковую статистику». Гарантируется, что в таком случае $$$|k_i|$$$ не превосходит размера множества. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если после всех запросов мультимножество оказалось пустым, выведите $$$0$$$.</p><p>Иначе выведите любое число, принадлежащее мультимножеству.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5 5
1 2 3 4 5
-1 -1 -1 -1 -1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 4
1 2 3 4 5
-5 -1 -3 -1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 2
1 1 1 2 3 4
5 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере последовательно удаляются все элементы мультимножества.</p><p>Во втором примере последовательно удалятся элементы $$$5$$$, $$$1$$$, $$$4$$$, $$$2$$$.</p><p>В третьем примере $$$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="b8ec1b99d4b18505a3468a97416fbef6"/>
<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="44f62d4b558bd2705c65f1533d7b7f4199a9561f"/>
<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='b8ec1b99d4b18505a3468a97416fbef6'> </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%2F1354%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='b8ec1b99d4b18505a3468a97416fbef6'/>
<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/1354">Educational Codeforces Round 87 (рейтинговый для Див. 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='b8ec1b99d4b18505a3468a97416fbef6'/>
<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/1354/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="Сложность">
*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='b8ec1b99d4b18505a3468a97416fbef6'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="623447"/>
<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='b8ec1b99d4b18505a3468a97416fbef6'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="623447"/>
<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/77454" title="Educational Codeforces Round 87 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10899:10900" 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/77593" title="77593" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10923:10924" 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/1354">Задачи</a></li>
<li><a
href="/contest/1354/submit">Отослать</a></li>
<li><a
href="/contest/1354/my">Мои посылки</a></li>
<li><a
href="/contest/1354/status">Статус</a></li>
<li><a
href="/contest/1354/hacks">Взломы</a></li>
<li><a
href="/contest/1354/standings">Положение</a></li>
<li><a
href="/contest/1354/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_138b5a900641f5338762a5dd46a5a72ecf5ec908">
<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>28 мегабайт</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><ul> <li> добавить элемент $$$k$$$ в мультимножество; </li><li> найти $$$k$$$-ю порядковую статистику в мультимножестве и удалить ее. </li></ul><p>Напомним, что $$$k$$$-я порядковая статистика в мультимножестве — это элемент, который будет на позиции $$$k$$$, если выписать все его элементы в порядке неубывания. Например, если в мультимножестве содержатся числа $$$1$$$, $$$4$$$, $$$2$$$, $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$ и $$$k = 3$$$, то необходимо найти $$$3$$$-й элемент в списке $$$[1, 1, 2, 4, 4, 5, 7]$$$, и он равен $$$2$$$. Если в мультимножестве несколько копий удаляемого элемента, удаляется только одна из них.</p><p>После всех запросов выведите <span class="tex-font-style-bf">любое</span> число, принадлежащее мультимножеству, или сообщите, что оно пустое.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два числа $$$n$$$ и $$$q$$$ ($$$1 \le n, q \le 10^6$$$) — количество элементов в мультимножестве и количество запросов, соответственно.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_1 \le a_2 \le \dots \le a_n \le n$$$) — элементы мультимножества.</p><p>В третьей строке заданы $$$q$$$ целых чисел $$$k_1$$$, $$$k_2$$$, ..., $$$k_q$$$, каждое из которых описывает очередной запрос следующим образом: </p><ul> <li> если $$$1 \le k_i \le n$$$, то $$$i$$$-й запрос — «добавить $$$k_i$$$ в мультимножество»; </li><li> если $$$k_i < 0$$$, то $$$i$$$-й запрос — «удалить $$$|k_i|$$$-ю порядковую статистику». Гарантируется, что в таком случае $$$|k_i|$$$ не превосходит размера множества. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если после всех запросов мультимножество оказалось пустым, выведите $$$0$$$.</p><p>Иначе выведите любое число, принадлежащее мультимножеству.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5 5
1 2 3 4 5
-1 -1 -1 -1 -1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 4
1 2 3 4 5
-5 -1 -3 -1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 2
1 1 1 2 3 4
5 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере последовательно удаляются все элементы мультимножества.</p><p>Во втором примере последовательно удалятся элементы $$$5$$$, $$$1$$$, $$$4$$$, $$$2$$$.</p><p>В третьем примере $$$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:03: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:'8124a113ebc43a8f',t:'MTY5NjY2NTgyMy40NTAwMDA='};_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", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1900"] | ||
1354E | 1354 | 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$$$ вершин и $$$m$$$ ребер. Также вам задано три числа $$$n_1$$$, $$$n_2$$$ и $$$n_3$$$.</p><p>Определите, можно ли расставить в вершины графа цифры <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> и <span class="tex-font-style-tt">3</span> так, чтобы выполнялись следующие условия: </p><ol> <li> В каждой вершине должно стоять ровно одно из чисел <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span>, <span class="tex-font-style-tt">3</span>; </li><li> Суммарно количество чисел <span class="tex-font-style-tt">1</span> во всех вершинах должно равняться $$$n_1$$$; </li><li> Суммарно количество чисел <span class="tex-font-style-tt">2</span> во всех вершинах должно равняться $$$n_2$$$; </li><li> Суммарно количество чисел <span class="tex-font-style-tt">3</span> во всех вершинах должно равняться $$$n_3$$$; </li><li> Для каждого ребра $$$(u, v)$$$ должно быть верно $$$|col_u - col_v| = 1$$$, где $$$col_x$$$ — цвет вершины с индексом $$$x$$$. </li></ol><p>Если существует несколько раскрасок, удовлетворяющим все описанным выше условиям, разрешено найти любую из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следуют два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — количество вершин в графе и количество ребер в графе.</p><p>Во второй строке следуют три целых числа $$$n_1$$$, $$$n_2$$$ и $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — необходимое количество цифр <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> и <span class="tex-font-style-tt">3</span>, соответственно. Гарантируется, что $$$n_1 + n_2 + n_3 = n$$$.</p><p>В следующих $$$m$$$ строках следует описание ребер: в $$$i$$$-й строке следуют два целых числа $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — номера вершин, которые соединяет $$$i$$$-е ребро. Гарантируется, что граф не содержит петель и кратных ребер.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если существует раскраска, удовлетворяющая всем описанным условиям, выведите в первую строку «<span class="tex-font-style-tt">YES</span>» (без кавычек). Во вторую строку выведите строку длины $$$n$$$, состоящую только из цифр <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> и <span class="tex-font-style-tt">3</span>, причем $$$i$$$-й символ этой строки должен быть равен цифре, которую нужно поставить в $$$i$$$-ю вершину.</p><p>Если подходящей раскраски не существует, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6 3
2 2 2
3 1
5 4
2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
112323
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
</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="b47d57853d5ed9fe36359f1d8796e394"/>
<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="44f62d4b558bd2705c65f1533d7b7f4199a9561f"/>
<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='b47d57853d5ed9fe36359f1d8796e394'> </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%2F1354%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='b47d57853d5ed9fe36359f1d8796e394'/>
<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/1354">Educational Codeforces Round 87 (рейтинговый для Див. 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='b47d57853d5ed9fe36359f1d8796e394'/>
<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/1354/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="Сложность">
*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='b47d57853d5ed9fe36359f1d8796e394'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="623448"/>
<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='b47d57853d5ed9fe36359f1d8796e394'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="623448"/>
<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/77454" title="Educational Codeforces Round 87 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10899:10900" 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/77593" title="77593" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10923:10924" 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/1354">Задачи</a></li>
<li><a
href="/contest/1354/submit">Отослать</a></li>
<li><a
href="/contest/1354/my">Мои посылки</a></li>
<li><a
href="/contest/1354/status">Статус</a></li>
<li><a
href="/contest/1354/hacks">Взломы</a></li>
<li><a
href="/contest/1354/standings">Положение</a></li>
<li><a
href="/contest/1354/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_0b4d62dc0aca41eb9d7fdf4279c5f3d5d3514298">
<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$$$ вершин и $$$m$$$ ребер. Также вам задано три числа $$$n_1$$$, $$$n_2$$$ и $$$n_3$$$.</p><p>Определите, можно ли расставить в вершины графа цифры <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> и <span class="tex-font-style-tt">3</span> так, чтобы выполнялись следующие условия: </p><ol> <li> В каждой вершине должно стоять ровно одно из чисел <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span>, <span class="tex-font-style-tt">3</span>; </li><li> Суммарно количество чисел <span class="tex-font-style-tt">1</span> во всех вершинах должно равняться $$$n_1$$$; </li><li> Суммарно количество чисел <span class="tex-font-style-tt">2</span> во всех вершинах должно равняться $$$n_2$$$; </li><li> Суммарно количество чисел <span class="tex-font-style-tt">3</span> во всех вершинах должно равняться $$$n_3$$$; </li><li> Для каждого ребра $$$(u, v)$$$ должно быть верно $$$|col_u - col_v| = 1$$$, где $$$col_x$$$ — цвет вершины с индексом $$$x$$$. </li></ol><p>Если существует несколько раскрасок, удовлетворяющим все описанным выше условиям, разрешено найти любую из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следуют два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 5000$$$; $$$0 \le m \le 10^5$$$) — количество вершин в графе и количество ребер в графе.</p><p>Во второй строке следуют три целых числа $$$n_1$$$, $$$n_2$$$ и $$$n_3$$$ ($$$0 \le n_1, n_2, n_3 \le n$$$) — необходимое количество цифр <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> и <span class="tex-font-style-tt">3</span>, соответственно. Гарантируется, что $$$n_1 + n_2 + n_3 = n$$$.</p><p>В следующих $$$m$$$ строках следует описание ребер: в $$$i$$$-й строке следуют два целых числа $$$u_i$$$, $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — номера вершин, которые соединяет $$$i$$$-е ребро. Гарантируется, что граф не содержит петель и кратных ребер.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если существует раскраска, удовлетворяющая всем описанным условиям, выведите в первую строку «<span class="tex-font-style-tt">YES</span>» (без кавычек). Во вторую строку выведите строку длины $$$n$$$, состоящую только из цифр <span class="tex-font-style-tt">1</span>, <span class="tex-font-style-tt">2</span> и <span class="tex-font-style-tt">3</span>, причем $$$i$$$-й символ этой строки должен быть равен цифре, которую нужно поставить в $$$i$$$-ю вершину.</p><p>Если подходящей раскраски не существует, выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6 3
2 2 2
3 1
5 4
2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
112323
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 9
0 2 3
1 2
1 3
1 5
2 3
2 4
2 5
3 4
3 5
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
</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:03: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:'8124a11c38a19d8d',t:'MTY5NjY2NTgyNC43NzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2100"] | ||
1354F | 1354 | F | ru | F. Призыв существ | <div class="problem-statement"><div class="header"><div class="title">F. Призыв существ</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>6 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в компьютерную игру. В этой игре игроки призывают армии магических существ и сражаются с армиями существ других игроков.</p><p>Поликарп может призвать $$$n$$$ разных существ, $$$i$$$-е существо изначально имеет силу $$$a_i$$$; кроме того, когда Поликарп призывает его, оно увеличивает на $$$b_i$$$ силу всех ранее призванных существ (исключая себя). Поликарп может призывать существ в любом порядке.</p><p>Однако под контролем Поликарпа может находиться не более $$$k$$$ существ одновременно. Поэтому, помимо призыва существ, он может уничтожать ранее призванных существ. Каждое существо может быть призвано (а, значит, и уничтожено) не более одного раза.</p><p>Цель Поликарпа — собрать максимально сильную армию существ. Он хочет, чтобы после всех его действий суммарная сила всех призванных (но не уничтоженных) им существ была максимально возможной.</p><p>Помогите Поликарпу составить оптимальную последовательность действий, чтобы собрать максимально сильную армию!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$T$$$ ($$$1 \le T \le 75$$$) — количество наборов тестовых данных.</p><p>Каждый набор тестовых данных начинается строкой, содержащей два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 75$$$) — количество существ, доступных для призыва, и максимальное количество существ, которые могут одновременно быть под контролем Поликарпа, соответственно.</p><p>Затем следуют $$$n$$$ строк, $$$i$$$-я из которых содержит $$$2$$$ целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — параметры $$$i$$$-го существа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите оптимальную последовательность действий в следующем формате:</p><p>Сначала выведите $$$m$$$ — количество действий, которые должен совершить Поликарп ($$$0 \le m \le 2n$$$). После этого выведите $$$m$$$ целых чисел $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, где $$$o_i$$$ описывает $$$i$$$-е действие следующим образом: если $$$i$$$-е действие — это «призвать существо $$$x$$$», то $$$o_i = x$$$, а если $$$i$$$-е действие — это «уничтожить существо $$$x$$$», то $$$o_i = -x$$$. Каждое существо может быть призвано не более одного раза и не может быть уничтожено, если оно еще не призвано (или уже уничтожено). После каждого действия под контролем Поликарпа должно быть не более $$$k$$$ существ.</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
5 2
5 3
7 0
5 0
4 0
10 0
2 1
10 100
50 10
5 5
1 5
2 4
3 3
4 2
5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
2 1 -1 5
1
2
5
5 4 3 2 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим пример из условия.</p><p>В первом наборе тестовых данных можно сначала вызвать существо $$$2$$$ с силой $$$7$$$, затем призвать существо $$$1$$$, которое увеличит силу предыдущего существа на $$$3$$$, после этого уничтожить существо $$$1$$$ и поставить существо $$$5$$$. В итоге у Поликарпа будут два существа с силой $$$10$$$.</p><p>Во втором наборе тестовых данных у Поликарпа не может быть более одного существа под контролем, поэтому достаточно выбрать самое сильное существо и призвать его.</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="33c1ba12555a9aecb9934fb2195ae42d"/>
<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="44f62d4b558bd2705c65f1533d7b7f4199a9561f"/>
<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='33c1ba12555a9aecb9934fb2195ae42d'> </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%2F1354%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='33c1ba12555a9aecb9934fb2195ae42d'/>
<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/1354">Educational Codeforces Round 87 (рейтинговый для Див. 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='33c1ba12555a9aecb9934fb2195ae42d'/>
<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/1354/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Паросочетания, теорема Кёнига, вершинные и реберные покрытия в двудольных графах">
паросочетания
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Потоки в графах">
потоки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='33c1ba12555a9aecb9934fb2195ae42d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="623449"/>
<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='33c1ba12555a9aecb9934fb2195ae42d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="623449"/>
<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/77454" title="Educational Codeforces Round 87 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10899:10900" 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/77593" title="77593" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10923:10924" 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/1354">Задачи</a></li>
<li><a
href="/contest/1354/submit">Отослать</a></li>
<li><a
href="/contest/1354/my">Мои посылки</a></li>
<li><a
href="/contest/1354/status">Статус</a></li>
<li><a
href="/contest/1354/hacks">Взломы</a></li>
<li><a
href="/contest/1354/standings">Положение</a></li>
<li><a
href="/contest/1354/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_8cc09c6c1c72585357b7c1aa45ef07efe0727452">
<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>6 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в компьютерную игру. В этой игре игроки призывают армии магических существ и сражаются с армиями существ других игроков.</p><p>Поликарп может призвать $$$n$$$ разных существ, $$$i$$$-е существо изначально имеет силу $$$a_i$$$; кроме того, когда Поликарп призывает его, оно увеличивает на $$$b_i$$$ силу всех ранее призванных существ (исключая себя). Поликарп может призывать существ в любом порядке.</p><p>Однако под контролем Поликарпа может находиться не более $$$k$$$ существ одновременно. Поэтому, помимо призыва существ, он может уничтожать ранее призванных существ. Каждое существо может быть призвано (а, значит, и уничтожено) не более одного раза.</p><p>Цель Поликарпа — собрать максимально сильную армию существ. Он хочет, чтобы после всех его действий суммарная сила всех призванных (но не уничтоженных) им существ была максимально возможной.</p><p>Помогите Поликарпу составить оптимальную последовательность действий, чтобы собрать максимально сильную армию!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$T$$$ ($$$1 \le T \le 75$$$) — количество наборов тестовых данных.</p><p>Каждый набор тестовых данных начинается строкой, содержащей два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 75$$$) — количество существ, доступных для призыва, и максимальное количество существ, которые могут одновременно быть под контролем Поликарпа, соответственно.</p><p>Затем следуют $$$n$$$ строк, $$$i$$$-я из которых содержит $$$2$$$ целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i \le 10^5$$$, $$$0 \le b_i \le 10^5$$$) — параметры $$$i$$$-го существа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите оптимальную последовательность действий в следующем формате:</p><p>Сначала выведите $$$m$$$ — количество действий, которые должен совершить Поликарп ($$$0 \le m \le 2n$$$). После этого выведите $$$m$$$ целых чисел $$$o_1$$$, $$$o_2$$$, ..., $$$o_m$$$, где $$$o_i$$$ описывает $$$i$$$-е действие следующим образом: если $$$i$$$-е действие — это «призвать существо $$$x$$$», то $$$o_i = x$$$, а если $$$i$$$-е действие — это «уничтожить существо $$$x$$$», то $$$o_i = -x$$$. Каждое существо может быть призвано не более одного раза и не может быть уничтожено, если оно еще не призвано (или уже уничтожено). После каждого действия под контролем Поликарпа должно быть не более $$$k$$$ существ.</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
5 2
5 3
7 0
5 0
4 0
10 0
2 1
10 100
50 10
5 5
1 5
2 4
3 3
4 2
5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
2 1 -1 5
1
2
5
5 4 3 2 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим пример из условия.</p><p>В первом наборе тестовых данных можно сначала вызвать существо $$$2$$$ с силой $$$7$$$, затем призвать существо $$$1$$$, которое увеличит силу предыдущего существа на $$$3$$$, после этого уничтожить существо $$$1$$$ и поставить существо $$$5$$$. В итоге у Поликарпа будут два существа с силой $$$10$$$.</p><p>Во втором наборе тестовых данных у Поликарпа не может быть более одного существа под контролем, поэтому достаточно выбрать самое сильное существо и призвать его.</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:03: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:'8124a12488910004',t:'MTY5NjY2NTgyNi4wNjUwMDA='};_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", "\u041f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f, \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u041a\u0451\u043d\u0438\u0433\u0430, \u0432\u0435\u0440\u0448\u0438\u043d\u043d\u044b\u0435 \u0438 \u0440\u0435\u0431\u0435\u0440\u043d\u044b\u0435 \u043f\u043e\u043a\u0440\u044b\u0442\u0438\u044f \u0432 \u0434\u0432\u0443\u0434\u043e\u043b\u044c\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\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", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u043f\u043e\u0442\u043e\u043a\u0438", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2500"] | ||
1354G | 1354 | 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><span class="tex-font-style-it">Это интерактивная задача. Не забывайте при выводе запросов сбрасывать буфер с помощью <span class="tex-font-style-tt">cout.flush()</span> или <span class="tex-font-style-tt">fflush(stdout)</span> в <span class="tex-font-style-tt">C++</span> и аналогичных функций в других языках программирования.</span></p><p>На столе стоят $$$n$$$ коробок с подарками, пронумерованные от $$$1$$$ по $$$n$$$ слева направо. Известно, что ровно в $$$k$$$ из них лежат ценные подарки — в остальных просто камешки на удачу. Выглядят все коробки одинаково и отличить их можно только по весу. Все <span class="tex-font-style-it">коробки с камнями весят одинаково и строго больше</span>, чем коробки с ценными подарками. Массы коробок с подарками же могут как совпадать, так и различаться между собой.</p><p>Вы можете сделать не более $$$50$$$ запросов (без учета вывода ответа). Каждым запросом вы можете сравнить массы двух непересекающихся подмножеств коробок $$$a_1, a_2, \dots, a_{k_a}$$$ и $$$b_1, b_2, \dots, b_{k_b}$$$ на чашечных весах. В ответ вы получите один из четырех вариантов:</p><ul> <li> <span class="tex-font-style-tt">FIRST</span>, если подмножество $$$a_1, a_2, \dots, a_{k_a}$$$ <span class="tex-font-style-bf">тяжелее</span>; </li><li> <span class="tex-font-style-tt">SECOND</span>, если подмножество $$$b_1, b_2, \dots, b_{k_b}$$$ <span class="tex-font-style-bf">тяжелее</span>; </li><li> <span class="tex-font-style-tt">EQUAL</span>, если массы подмножеств совпадают; </li><li> <span class="tex-font-style-tt">WASTED</span>, если запрос некорректен или превышено количество запросов. </li></ul><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 500$$$) — количество наборов входных данных.</p><p>В начале каждого набора вам выдаются два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 1000$$$, $$$1 \le k \le \frac{n}{2}$$$) — количество коробок в ряду и количество с ценными подарками среди них.</p><p>Гарантируется, что порядок коробок в каждом наборе фиксирован и сумма $$$n$$$ по всем наборам не превосходит $$$1000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальный номер коробки, содержащей ценный подарок, в следующем формате: «<span class="tex-font-style-tt">! $$$x$$$</span>», где $$$x$$$ ($$$1 \le x \le n$$$) — искомый номер.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Выводите каждый запрос в три строки. В первой строке выводите размеры подмножеств в следующем формате: «<span class="tex-font-style-tt">? $$$k_a$$$ $$$k_b$$$</span>», где $$$k_a$$$ и $$$k_b$$$ ($$$1 \le k_a, k_b \le n$$$; $$$k_a + k_b \le n$$$) — их соответствующие размеры.</p><p>Во второй строке выведите $$$k_a$$$ целых чисел $$$a_1, a_2, \dots, a_{k_a}$$$ ($$$1 \le a_i \le n$$$; $$$a_i \neq a_j$$$ при $$$i \neq j$$$) — номера коробок в первом подмножестве.</p><p>В третьей строке выведите $$$k_b$$$ целых чисел $$$b_1, b_2, \dots, b_{k_b}$$$ ($$$1 \le b_i \le n$$$; $$$b_i \neq b_j$$$ при $$$i \neq j$$$) — номера коробок во втором подмножестве.</p><p>Подмножества не должны пересекаться, то есть $$$a_i \neq b_j$$$ для всех $$$i$$$ и $$$j$$$.</p><p>В ответ будет получен один из четырех вариантов, описанных выше. В случае получения <span class="tex-font-style-tt">WASTED</span> завершите работу программы во избежание получения вердиктов тестирования, отличных от <span class="tex-font-style-tt">Wrong Answer</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
2 1
-
-
-
FIRST
-
5 2
-
-
-
FIRST
-
-
-
SECOND
-
-
-
EQUAL
-</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-
-
? 1 1
1
2
-
! 2
-
? 1 1
1
2
-
? 2 3
4 2
1 3 5
-
? 1 1
4
5
-
! 1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дополнительные разделители «–» в примере использованы только для наглядности самого примера. <span class="tex-font-style-bf">При отправке запросов и получении ответов не должно быть никаких лишних символов или переводов строк.</span></p><p><span class="tex-font-style-it">Взломы в данной задаче запрещены.</span></p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="1719e326fa1eb615adae9bc87b357fff"/>
<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="44f62d4b558bd2705c65f1533d7b7f4199a9561f"/>
<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='1719e326fa1eb615adae9bc87b357fff'> </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%2F1354%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='1719e326fa1eb615adae9bc87b357fff'/>
<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/1354">Educational Codeforces Round 87 (рейтинговый для Див. 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='1719e326fa1eb615adae9bc87b357fff'/>
<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/1354/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др.">
теория вероятностей
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1719e326fa1eb615adae9bc87b357fff'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="623450"/>
<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='1719e326fa1eb615adae9bc87b357fff'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="623450"/>
<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/77454" title="Educational Codeforces Round 87 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10899:10900" 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/77593" title="77593" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10923:10924" 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/1354">Задачи</a></li>
<li><a
href="/contest/1354/submit">Отослать</a></li>
<li><a
href="/contest/1354/my">Мои посылки</a></li>
<li><a
href="/contest/1354/status">Статус</a></li>
<li><a
href="/contest/1354/hacks">Взломы</a></li>
<li><a
href="/contest/1354/standings">Положение</a></li>
<li><a
href="/contest/1354/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_37314a73a8280fc4142d524291cc8dff18d5dd15">
<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><span class="tex-font-style-it">Это интерактивная задача. Не забывайте при выводе запросов сбрасывать буфер с помощью <span class="tex-font-style-tt">cout.flush()</span> или <span class="tex-font-style-tt">fflush(stdout)</span> в <span class="tex-font-style-tt">C++</span> и аналогичных функций в других языках программирования.</span></p><p>На столе стоят $$$n$$$ коробок с подарками, пронумерованные от $$$1$$$ по $$$n$$$ слева направо. Известно, что ровно в $$$k$$$ из них лежат ценные подарки — в остальных просто камешки на удачу. Выглядят все коробки одинаково и отличить их можно только по весу. Все <span class="tex-font-style-it">коробки с камнями весят одинаково и строго больше</span>, чем коробки с ценными подарками. Массы коробок с подарками же могут как совпадать, так и различаться между собой.</p><p>Вы можете сделать не более $$$50$$$ запросов (без учета вывода ответа). Каждым запросом вы можете сравнить массы двух непересекающихся подмножеств коробок $$$a_1, a_2, \dots, a_{k_a}$$$ и $$$b_1, b_2, \dots, b_{k_b}$$$ на чашечных весах. В ответ вы получите один из четырех вариантов:</p><ul> <li> <span class="tex-font-style-tt">FIRST</span>, если подмножество $$$a_1, a_2, \dots, a_{k_a}$$$ <span class="tex-font-style-bf">тяжелее</span>; </li><li> <span class="tex-font-style-tt">SECOND</span>, если подмножество $$$b_1, b_2, \dots, b_{k_b}$$$ <span class="tex-font-style-bf">тяжелее</span>; </li><li> <span class="tex-font-style-tt">EQUAL</span>, если массы подмножеств совпадают; </li><li> <span class="tex-font-style-tt">WASTED</span>, если запрос некорректен или превышено количество запросов. </li></ul><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 500$$$) — количество наборов входных данных.</p><p>В начале каждого набора вам выдаются два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 1000$$$, $$$1 \le k \le \frac{n}{2}$$$) — количество коробок в ряду и количество с ценными подарками среди них.</p><p>Гарантируется, что порядок коробок в каждом наборе фиксирован и сумма $$$n$$$ по всем наборам не превосходит $$$1000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальный номер коробки, содержащей ценный подарок, в следующем формате: «<span class="tex-font-style-tt">! $$$x$$$</span>», где $$$x$$$ ($$$1 \le x \le n$$$) — искомый номер.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Выводите каждый запрос в три строки. В первой строке выводите размеры подмножеств в следующем формате: «<span class="tex-font-style-tt">? $$$k_a$$$ $$$k_b$$$</span>», где $$$k_a$$$ и $$$k_b$$$ ($$$1 \le k_a, k_b \le n$$$; $$$k_a + k_b \le n$$$) — их соответствующие размеры.</p><p>Во второй строке выведите $$$k_a$$$ целых чисел $$$a_1, a_2, \dots, a_{k_a}$$$ ($$$1 \le a_i \le n$$$; $$$a_i \neq a_j$$$ при $$$i \neq j$$$) — номера коробок в первом подмножестве.</p><p>В третьей строке выведите $$$k_b$$$ целых чисел $$$b_1, b_2, \dots, b_{k_b}$$$ ($$$1 \le b_i \le n$$$; $$$b_i \neq b_j$$$ при $$$i \neq j$$$) — номера коробок во втором подмножестве.</p><p>Подмножества не должны пересекаться, то есть $$$a_i \neq b_j$$$ для всех $$$i$$$ и $$$j$$$.</p><p>В ответ будет получен один из четырех вариантов, описанных выше. В случае получения <span class="tex-font-style-tt">WASTED</span> завершите работу программы во избежание получения вердиктов тестирования, отличных от <span class="tex-font-style-tt">Wrong Answer</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
2 1
-
-
-
FIRST
-
5 2
-
-
-
FIRST
-
-
-
SECOND
-
-
-
EQUAL
-</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-
-
? 1 1
1
2
-
! 2
-
? 1 1
1
2
-
? 2 3
4 2
1 3 5
-
? 1 1
4
5
-
! 1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дополнительные разделители «–» в примере использованы только для наглядности самого примера. <span class="tex-font-style-bf">При отправке запросов и получении ответов не должно быть никаких лишних символов или переводов строк.</span></p><p><span class="tex-font-style-it">Взломы в данной задаче запрещены.</span></p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=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:03: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:'8124a12c88289db4',t:'MTY5NjY2NTgyNy4zNjcwMDA='};_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\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\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\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*2600"] | ||
1355A | 1355 | A | ru | A. Последовательность с цифрами | <div class="problem-statement"><div class="header"><div class="title">A. Последовательность с цифрами</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Определим рекуррентную последовательность следующим образом: $$$$$$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$$$$$</p><p>Здесь $$$minDigit(x)$$$ и $$$maxDigit(x)$$$ — минимальная и максимальная цифры в десятичной записи числа $$$x$$$ без ведущих нулей соответственно. Для примеров обратитесь к примечаниям.</p><p>Ваша задача — по заданным $$$a_{1}$$$ и $$$K$$$ вычислить $$$a_{K}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано единственное число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество независимых наборов входных данных.</p><p>Каждый набор входных данных состоит из двух целых чисел $$$a_{1}$$$ и $$$K$$$ ($$$1 \le a_{1} \le 10^{18}$$$, $$$1 \le K \le 10^{16}$$$), записанных через пробел на отдельной строке.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно число $$$a_{K}$$$ на отдельной строке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
8
1 4
487 1
487 2
487 3
487 4
487 5
487 6
487 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
42
487
519
528
544
564
588
628
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>$$$a_{1} = 487$$$ </p><p> $$$a_{2} = a_{1} + minDigit(a_{1}) \cdot maxDigit(a_{1}) = 487 + \min (4, 8, 7) \cdot \max (4, 8, 7) = 487 + 4 \cdot 8 = 519$$$ </p><p> $$$a_{3} = a_{2} + minDigit(a_{2}) \cdot maxDigit(a_{2}) = 519 + \min (5, 1, 9) \cdot \max (5, 1, 9) = 519 + 1 \cdot 9 = 528$$$ </p><p> $$$a_{4} = a_{3} + minDigit(a_{3}) \cdot maxDigit(a_{3}) = 528 + \min (5, 2, 8) \cdot \max (5, 2, 8) = 528 + 2 \cdot 8 = 544$$$ </p><p> $$$a_{5} = a_{4} + minDigit(a_{4}) \cdot maxDigit(a_{4}) = 544 + \min (5, 4, 4) \cdot \max (5, 4, 4) = 544 + 4 \cdot 5 = 564$$$ </p><p> $$$a_{6} = a_{5} + minDigit(a_{5}) \cdot maxDigit(a_{5}) = 564 + \min (5, 6, 4) \cdot \max (5, 6, 4) = 564 + 4 \cdot 6 = 588$$$ </p><p> $$$a_{7} = a_{6} + minDigit(a_{6}) \cdot maxDigit(a_{6}) = 588 + \min (5, 8, 8) \cdot \max (5, 8, 8) = 588 + 5 \cdot 8 = 628$$$</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="a77475e8cf01b1576d1ae3c3f71704e1"/>
<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="592b9a15cba9650ad702e706e005bb936c66df5a"/>
<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='a77475e8cf01b1576d1ae3c3f71704e1'> </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%2F1355%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='a77475e8cf01b1576d1ae3c3f71704e1'/>
<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/1355">Codeforces Round 643 (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='a77475e8cf01b1576d1ae3c3f71704e1'/>
<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/1355/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a77475e8cf01b1576d1ae3c3f71704e1'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="621791"/>
<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='a77475e8cf01b1576d1ae3c3f71704e1'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="621791"/>
<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/77323" title="Codeforces Round #643 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10887" resourceName="Codeforces Round #643 (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/77491" title="Codeforces Round #643 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10893" resourceName="Codeforces Round #643 (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/1355">Задачи</a></li>
<li><a
href="/contest/1355/submit">Отослать</a></li>
<li><a
href="/contest/1355/my">Мои посылки</a></li>
<li><a
href="/contest/1355/status">Статус</a></li>
<li><a
href="/contest/1355/hacks">Взломы</a></li>
<li><a
href="/contest/1355/room/1">Комната</a></li>
<li><a
href="/contest/1355/standings">Положение</a></li>
<li><a
href="/contest/1355/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_183d230306029b469acdf6c5a44690450304b324">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Последовательность с цифрами</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Определим рекуррентную последовательность следующим образом: $$$$$$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$$$$$</p><p>Здесь $$$minDigit(x)$$$ и $$$maxDigit(x)$$$ — минимальная и максимальная цифры в десятичной записи числа $$$x$$$ без ведущих нулей соответственно. Для примеров обратитесь к примечаниям.</p><p>Ваша задача — по заданным $$$a_{1}$$$ и $$$K$$$ вычислить $$$a_{K}$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано единственное число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество независимых наборов входных данных.</p><p>Каждый набор входных данных состоит из двух целых чисел $$$a_{1}$$$ и $$$K$$$ ($$$1 \le a_{1} \le 10^{18}$$$, $$$1 \le K \le 10^{16}$$$), записанных через пробел на отдельной строке.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно число $$$a_{K}$$$ на отдельной строке.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
8
1 4
487 1
487 2
487 3
487 4
487 5
487 6
487 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
42
487
519
528
544
564
588
628
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>$$$a_{1} = 487$$$ </p><p> $$$a_{2} = a_{1} + minDigit(a_{1}) \cdot maxDigit(a_{1}) = 487 + \min (4, 8, 7) \cdot \max (4, 8, 7) = 487 + 4 \cdot 8 = 519$$$ </p><p> $$$a_{3} = a_{2} + minDigit(a_{2}) \cdot maxDigit(a_{2}) = 519 + \min (5, 1, 9) \cdot \max (5, 1, 9) = 519 + 1 \cdot 9 = 528$$$ </p><p> $$$a_{4} = a_{3} + minDigit(a_{3}) \cdot maxDigit(a_{3}) = 528 + \min (5, 2, 8) \cdot \max (5, 2, 8) = 528 + 2 \cdot 8 = 544$$$ </p><p> $$$a_{5} = a_{4} + minDigit(a_{4}) \cdot maxDigit(a_{4}) = 544 + \min (5, 4, 4) \cdot \max (5, 4, 4) = 544 + 4 \cdot 5 = 564$$$ </p><p> $$$a_{6} = a_{5} + minDigit(a_{5}) \cdot maxDigit(a_{5}) = 564 + \min (5, 6, 4) \cdot \max (5, 6, 4) = 564 + 4 \cdot 6 = 588$$$ </p><p> $$$a_{7} = a_{6} + minDigit(a_{6}) \cdot maxDigit(a_{6}) = 588 + \min (5, 8, 8) \cdot \max (5, 8, 8) = 588 + 5 \cdot 8 = 628$$$</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:03: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:'8124a134b9710022',t:'MTY5NjY2NTgyOC43MTQwMDA='};_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", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1200"] | ||
1355B | 1355 | 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>Многие юные следопыты неопытны, и отправлять их маленькими группами — не всегда хорошая идея. Даже сам Рассел недавно стал старшим следопытом и нечасто бывал в экспедициях. Каждый следопыт характеризуется своей неопытностью — целым положительным числом $$$e_i$$$. Рассел решил, что юный следопыт с неопытностью $$$e$$$ может идти лишь в группе, количество следопытов в которой не меньше $$$e$$$.</p><p>Теперь задача Рассела — определить, какое наибольшее число групп следопытов он сможет организовать. При этом может получиться, что некоторые следопыты не войдут в состав ни одной группы, это не страшно, ведь и в лагере для них найдется работа. Рассел очень переживает за успех экспедиции, и потому попросил вас помочь ему.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано число $$$T$$$ ($$$1 \leq T \leq 2 \cdot 10^5$$$) — количество независимых тестовых случаев. В следующих $$$2T$$$ строках следует описание тестовых случаев.</p><p>В первой строке описания каждого теста задано целое число юных следопытов $$$N$$$ ($$$1 \leq N \leq 2 \cdot 10^5$$$).</p><p>В следующей строке записаны $$$N$$$ целых чисел $$$e_1, e_2, \ldots, e_N$$$ ($$$1 \leq e_i \leq N$$$), где $$$e_i$$$ — неопытность $$$i$$$-го следопыта.</p><p>Гарантируется, что сумма $$$N$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ чисел, каждое на отдельной строке.</p><p>В $$$i$$$-й строке выведите наибольшее число групп, которое можно организовать в $$$i$$$-м тестовом случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
3
1 1 1
5
2 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно сформировать три группы, в каждой из которых будет один следопыт. Это возможно, так как неопытность всех трех следопытов равна $$$1$$$, что не меньше, чем размер их групп.</p><p>Во втором примере можно сформировать две группы. В первой группе окажутся следопыты с неопытностью $$$1$$$, $$$2$$$ и $$$3$$$, а во второй группе — два следопыта с неопытностью $$$2$$$.</p><p>Этот способ — не единственный возможный. Можно, например, сформировать одну группу из трех следопытов с неопытностью $$$2$$$, а также еще одну группу, в которой будет всего один следопыт с неопытностью $$$1$$$. При таком разбиении на группы следопыт с неопытностью $$$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="2495fc47ea1caa1fd2ab61f51f8b1eb6"/>
<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="592b9a15cba9650ad702e706e005bb936c66df5a"/>
<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='2495fc47ea1caa1fd2ab61f51f8b1eb6'> </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%2F1355%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='2495fc47ea1caa1fd2ab61f51f8b1eb6'/>
<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/1355">Codeforces Round 643 (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='2495fc47ea1caa1fd2ab61f51f8b1eb6'/>
<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/1355/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2495fc47ea1caa1fd2ab61f51f8b1eb6'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="621792"/>
<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='2495fc47ea1caa1fd2ab61f51f8b1eb6'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="621792"/>
<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/77323" title="Codeforces Round #643 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10887" resourceName="Codeforces Round #643 (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/77491" title="Codeforces Round #643 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10893" resourceName="Codeforces Round #643 (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/1355">Задачи</a></li>
<li><a
href="/contest/1355/submit">Отослать</a></li>
<li><a
href="/contest/1355/my">Мои посылки</a></li>
<li><a
href="/contest/1355/status">Статус</a></li>
<li><a
href="/contest/1355/hacks">Взломы</a></li>
<li><a
href="/contest/1355/room/1">Комната</a></li>
<li><a
href="/contest/1355/standings">Положение</a></li>
<li><a
href="/contest/1355/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_b6ea48403f0ce4a2b0ef32a6e36d6eae0fd8f064">
<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>Многие юные следопыты неопытны, и отправлять их маленькими группами — не всегда хорошая идея. Даже сам Рассел недавно стал старшим следопытом и нечасто бывал в экспедициях. Каждый следопыт характеризуется своей неопытностью — целым положительным числом $$$e_i$$$. Рассел решил, что юный следопыт с неопытностью $$$e$$$ может идти лишь в группе, количество следопытов в которой не меньше $$$e$$$.</p><p>Теперь задача Рассела — определить, какое наибольшее число групп следопытов он сможет организовать. При этом может получиться, что некоторые следопыты не войдут в состав ни одной группы, это не страшно, ведь и в лагере для них найдется работа. Рассел очень переживает за успех экспедиции, и потому попросил вас помочь ему.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано число $$$T$$$ ($$$1 \leq T \leq 2 \cdot 10^5$$$) — количество независимых тестовых случаев. В следующих $$$2T$$$ строках следует описание тестовых случаев.</p><p>В первой строке описания каждого теста задано целое число юных следопытов $$$N$$$ ($$$1 \leq N \leq 2 \cdot 10^5$$$).</p><p>В следующей строке записаны $$$N$$$ целых чисел $$$e_1, e_2, \ldots, e_N$$$ ($$$1 \leq e_i \leq N$$$), где $$$e_i$$$ — неопытность $$$i$$$-го следопыта.</p><p>Гарантируется, что сумма $$$N$$$ по всем тестовым случаям не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$T$$$ чисел, каждое на отдельной строке.</p><p>В $$$i$$$-й строке выведите наибольшее число групп, которое можно организовать в $$$i$$$-м тестовом случае.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
3
1 1 1
5
2 3 1 2 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно сформировать три группы, в каждой из которых будет один следопыт. Это возможно, так как неопытность всех трех следопытов равна $$$1$$$, что не меньше, чем размер их групп.</p><p>Во втором примере можно сформировать две группы. В первой группе окажутся следопыты с неопытностью $$$1$$$, $$$2$$$ и $$$3$$$, а во второй группе — два следопыта с неопытностью $$$2$$$.</p><p>Этот способ — не единственный возможный. Можно, например, сформировать одну группу из трех следопытов с неопытностью $$$2$$$, а также еще одну группу, в которой будет всего один следопыт с неопытностью $$$1$$$. При таком разбиении на группы следопыт с неопытностью $$$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:03: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:'8124a13d1e3f009d',t:'MTY5NjY2NTgzMC4xMTUwMDA='};_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", "*1200"] | ||
1355C | 1355 | 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$$$, $$$B$$$, $$$C$$$ и $$$D$$$, причем $$$A \leq B \leq C \leq D$$$. Также Юрий очень любит треугольники, поэтому в один день он задумался: сколько существует невырожденных треугольников с целочисленными длинами сторон $$$x$$$, $$$y$$$ и $$$z$$$ таких, что $$$A \leq x \leq B \leq y \leq C \leq z \leq D$$$?</p><p>Сейчас Юрий очень занят подготовкой задач для очередной олимпиады, поэтому он просит вас помочь посчитать количество интересующих его треугольников. </p><p>Треугольник называется невырожденным тогда и только тогда, когда его вершины не лежат на одной прямой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке через пробел записаны четыре целых числа $$$A$$$, $$$B$$$, $$$C$$$ и $$$D$$$ ($$$1 \leq A \leq B \leq C \leq D \leq 5 \cdot 10^5$$$) — любимые числа Юрия.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — количество невырожденных треугольников с целочисленными длинами сторон $$$x$$$, $$$y$$$ и $$$z$$$, для которых выполнено неравенство: $$$A \leq x \leq B \leq y \leq C \leq z \leq D$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 2 2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
500000 500000 500000 500000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно составить треугольники со следующими длинами сторон: $$$(1, 3, 3)$$$, $$$(2, 2, 3)$$$, $$$(2, 3, 3)$$$ и $$$(2, 3, 4)$$$.</p><p>Во втором примере можно составить треугольники: $$$(1, 2, 2)$$$, $$$(2, 2, 2)$$$ и $$$(2, 2, 3)$$$.</p><p>В третьем примере можно составить лишь один равносторонний треугольник. Длины всех сторон будут равны $$$5 \cdot 10^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="dd1f47265d018264880c315e16bb6d18"/>
<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="592b9a15cba9650ad702e706e005bb936c66df5a"/>
<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='dd1f47265d018264880c315e16bb6d18'> </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%2F1355%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='dd1f47265d018264880c315e16bb6d18'/>
<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/1355">Codeforces Round 643 (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='dd1f47265d018264880c315e16bb6d18'/>
<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/1355/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dd1f47265d018264880c315e16bb6d18'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="621793"/>
<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='dd1f47265d018264880c315e16bb6d18'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="621793"/>
<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/77323" title="Codeforces Round #643 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10887" resourceName="Codeforces Round #643 (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/77491" title="Codeforces Round #643 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10893" resourceName="Codeforces Round #643 (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/1355">Задачи</a></li>
<li><a
href="/contest/1355/submit">Отослать</a></li>
<li><a
href="/contest/1355/my">Мои посылки</a></li>
<li><a
href="/contest/1355/status">Статус</a></li>
<li><a
href="/contest/1355/hacks">Взломы</a></li>
<li><a
href="/contest/1355/room/1">Комната</a></li>
<li><a
href="/contest/1355/standings">Положение</a></li>
<li><a
href="/contest/1355/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_2f660e9d3127905dcac8cb4e879bba5e69da903a">
<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$$$, $$$B$$$, $$$C$$$ и $$$D$$$, причем $$$A \leq B \leq C \leq D$$$. Также Юрий очень любит треугольники, поэтому в один день он задумался: сколько существует невырожденных треугольников с целочисленными длинами сторон $$$x$$$, $$$y$$$ и $$$z$$$ таких, что $$$A \leq x \leq B \leq y \leq C \leq z \leq D$$$?</p><p>Сейчас Юрий очень занят подготовкой задач для очередной олимпиады, поэтому он просит вас помочь посчитать количество интересующих его треугольников. </p><p>Треугольник называется невырожденным тогда и только тогда, когда его вершины не лежат на одной прямой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке через пробел записаны четыре целых числа $$$A$$$, $$$B$$$, $$$C$$$ и $$$D$$$ ($$$1 \leq A \leq B \leq C \leq D \leq 5 \cdot 10^5$$$) — любимые числа Юрия.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — количество невырожденных треугольников с целочисленными длинами сторон $$$x$$$, $$$y$$$ и $$$z$$$, для которых выполнено неравенство: $$$A \leq x \leq B \leq y \leq C \leq z \leq D$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 2 2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
500000 500000 500000 500000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно составить треугольники со следующими длинами сторон: $$$(1, 3, 3)$$$, $$$(2, 2, 3)$$$, $$$(2, 3, 3)$$$ и $$$(2, 3, 4)$$$.</p><p>Во втором примере можно составить треугольники: $$$(1, 2, 2)$$$, $$$(2, 2, 2)$$$ и $$$(2, 2, 3)$$$.</p><p>В третьем примере можно составить лишь один равносторонний треугольник. Длины всех сторон будут равны $$$5 \cdot 10^5$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:03: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:'8124a145ebe613c6',t:'MTY5NjY2NTgzMS40MzAwMDA='};_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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1800"] | ||
1355D | 1355 | D | ru | D. Игра с массивом | <div class="problem-statement"><div class="header"><div class="title">D. Игра с массивом</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Петя и Вася, как всегда, заняты тем, что соревнуются между собой в новой интересной игре.</p><p>Сначала Петя должен придумать массив длины $$$N$$$, состоящий из целых положительных чисел, сумма которых равна $$$S$$$, а также целое число $$$K$$$ такое, что $$$0 \leq K \leq S$$$. Чтобы выиграть, Вася должен найти такой непустой подотрезок в массиве Пети, что сумма его элементов равна $$$K$$$ или $$$S - K$$$. В противном случае Васе придётся признать своё поражение.</p><p>Зная $$$N$$$ и $$$S$$$, определите, может ли Петя одержать победу при условии, что Вася будет играть наилучшим для себя способом. Если Петя может выиграть, подскажите, как ему следует сыграть.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке содержатся два целых числа $$$N$$$ и $$$S$$$ ($$$1 \leq N \leq S \leq 10^{6}$$$) — необходимая длина массива и сумма его элементов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если Петя может победить, то в первой строке следует вывести «<span class="tex-font-style-tt">YES</span>» (без кавычек), во второй строке нужно вывести необходимый массив, состоящий из $$$N$$$ натуральных чисел, сумма которых равна $$$S$$$, а в третьей строке вывести одно целое число $$$K$$$. Если подходящих ответов несколько, то можно вывести любой из них.</p><p>В противном случае в единственной строке выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
4
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
2 1 5
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="d5e44eb5a6af3e16b752a321cdd38e93"/>
<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="592b9a15cba9650ad702e706e005bb936c66df5a"/>
<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='d5e44eb5a6af3e16b752a321cdd38e93'> </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%2F1355%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='d5e44eb5a6af3e16b752a321cdd38e93'/>
<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/1355">Codeforces Round 643 (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='d5e44eb5a6af3e16b752a321cdd38e93'/>
<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/1355/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='d5e44eb5a6af3e16b752a321cdd38e93'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="621794"/>
<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='d5e44eb5a6af3e16b752a321cdd38e93'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="621794"/>
<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/77323" title="Codeforces Round #643 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10887" resourceName="Codeforces Round #643 (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/77491" title="Codeforces Round #643 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10893" resourceName="Codeforces Round #643 (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/1355">Задачи</a></li>
<li><a
href="/contest/1355/submit">Отослать</a></li>
<li><a
href="/contest/1355/my">Мои посылки</a></li>
<li><a
href="/contest/1355/status">Статус</a></li>
<li><a
href="/contest/1355/hacks">Взломы</a></li>
<li><a
href="/contest/1355/room/1">Комната</a></li>
<li><a
href="/contest/1355/standings">Положение</a></li>
<li><a
href="/contest/1355/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_4c844c6980d2bb06a1df7a942ad8e8bd8975fde0">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Игра с массивом</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Петя и Вася, как всегда, заняты тем, что соревнуются между собой в новой интересной игре.</p><p>Сначала Петя должен придумать массив длины $$$N$$$, состоящий из целых положительных чисел, сумма которых равна $$$S$$$, а также целое число $$$K$$$ такое, что $$$0 \leq K \leq S$$$. Чтобы выиграть, Вася должен найти такой непустой подотрезок в массиве Пети, что сумма его элементов равна $$$K$$$ или $$$S - K$$$. В противном случае Васе придётся признать своё поражение.</p><p>Зная $$$N$$$ и $$$S$$$, определите, может ли Петя одержать победу при условии, что Вася будет играть наилучшим для себя способом. Если Петя может выиграть, подскажите, как ему следует сыграть.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке содержатся два целых числа $$$N$$$ и $$$S$$$ ($$$1 \leq N \leq S \leq 10^{6}$$$) — необходимая длина массива и сумма его элементов.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если Петя может победить, то в первой строке следует вывести «<span class="tex-font-style-tt">YES</span>» (без кавычек), во второй строке нужно вывести необходимый массив, состоящий из $$$N$$$ натуральных чисел, сумма которых равна $$$S$$$, а в третьей строке вывести одно целое число $$$K$$$. Если подходящих ответов несколько, то можно вывести любой из них.</p><p>В противном случае в единственной строке выведите «<span class="tex-font-style-tt">NO</span>» (без кавычек).</p><p>Вы можете выводить каждую букву в любом регистре (строчную или заглавную).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
4
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
2 1 5
4</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:03: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:'8124a14e288116c7',t:'MTY5NjY2NTgzMi44MjAwMDA='};_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", "*1400"] | ||
1355E | 1355 | 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$$$ столбиков кирпичей, высота $$$i$$$-го столбика изначально равна $$$h_{i}$$$, высота измеряется количеством кирпичей. После реставрации все $$$N$$$ столбиков должны иметь одинаковую высоту.</p><p>Вам доступны следующие операции:</p><ul><li> положить кирпич на верх одного из столбиков, стоимость этой операции равна $$$A$$$;</li><li> убрать кирпич с верха одного из непустых столбиков, стоимость этой операции равна $$$R$$$;</li><li> переложить один кирпич с верха одного из непустых столбиков на верх другого столбика, стоимость этой операции равна $$$M$$$.</li></ul><p>Вы не можете создавать дополнительные столбики или игнорировать какие-то из существующих столбиков, даже если их высота стала равна $$$0$$$.</p><p>За какую минимальную суммарную стоимость возможно провести реставрацию, то есть сделать высоты всех столбиков равными?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны четыре целых числа $$$N$$$, $$$A$$$, $$$R$$$, $$$M$$$ ($$$1 \le N \le 10^{5}$$$, $$$0 \le A, R, M \le 10^{4}$$$) — количество столбиков кирпичей в стене, а также стоимости доступных операций.</p><p>Во второй строке записаны $$$N$$$ целых чисел $$$h_{i}$$$ ($$$0 \le h_{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>
3 1 100 100
1 3 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 100 1 100
1 3 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
9
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 100 100 1
1 3 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1 2 4
5 5 3 6 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1 2 2
5 5 3 6 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="3825b89dfb737073dbbb34980c254b36"/>
<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="592b9a15cba9650ad702e706e005bb936c66df5a"/>
<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='3825b89dfb737073dbbb34980c254b36'> </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%2F1355%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='3825b89dfb737073dbbb34980c254b36'/>
<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/1355">Codeforces Round 643 (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='3825b89dfb737073dbbb34980c254b36'/>
<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/1355/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='3825b89dfb737073dbbb34980c254b36'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="621795"/>
<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='3825b89dfb737073dbbb34980c254b36'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="621795"/>
<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/77323" title="Codeforces Round #643 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10887" resourceName="Codeforces Round #643 (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/77491" title="Codeforces Round #643 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10893" resourceName="Codeforces Round #643 (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/1355">Задачи</a></li>
<li><a
href="/contest/1355/submit">Отослать</a></li>
<li><a
href="/contest/1355/my">Мои посылки</a></li>
<li><a
href="/contest/1355/status">Статус</a></li>
<li><a
href="/contest/1355/hacks">Взломы</a></li>
<li><a
href="/contest/1355/room/1">Комната</a></li>
<li><a
href="/contest/1355/standings">Положение</a></li>
<li><a
href="/contest/1355/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_d29f5e8995416149d580e1b8b25313d963170447">
<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$$$ столбиков кирпичей, высота $$$i$$$-го столбика изначально равна $$$h_{i}$$$, высота измеряется количеством кирпичей. После реставрации все $$$N$$$ столбиков должны иметь одинаковую высоту.</p><p>Вам доступны следующие операции:</p><ul><li> положить кирпич на верх одного из столбиков, стоимость этой операции равна $$$A$$$;</li><li> убрать кирпич с верха одного из непустых столбиков, стоимость этой операции равна $$$R$$$;</li><li> переложить один кирпич с верха одного из непустых столбиков на верх другого столбика, стоимость этой операции равна $$$M$$$.</li></ul><p>Вы не можете создавать дополнительные столбики или игнорировать какие-то из существующих столбиков, даже если их высота стала равна $$$0$$$.</p><p>За какую минимальную суммарную стоимость возможно провести реставрацию, то есть сделать высоты всех столбиков равными?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны четыре целых числа $$$N$$$, $$$A$$$, $$$R$$$, $$$M$$$ ($$$1 \le N \le 10^{5}$$$, $$$0 \le A, R, M \le 10^{4}$$$) — количество столбиков кирпичей в стене, а также стоимости доступных операций.</p><p>Во второй строке записаны $$$N$$$ целых чисел $$$h_{i}$$$ ($$$0 \le h_{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>
3 1 100 100
1 3 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 100 1 100
1 3 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
9
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 100 100 1
1 3 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1 2 4
5 5 3 6 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 1 2 2
5 5 3 6 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:03: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:'8124a156db611498',t:'MTY5NjY2NTgzNC4xNjEwMDA='};_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", "\u0422\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\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", "\u0442\u0435\u0440\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "*2100"] | ||
1355F | 1355 | 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><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Загадано число $$$1 \le X \le 10^{9}$$$. Вам <span class="tex-font-style-bf">не нужно</span> угадывать это число. Вам нужно <span class="tex-font-style-bf">определить количество делителей</span> этого числа, и даже это вам <span class="tex-font-style-bf">не нужно делать точно</span>: ваш ответ будет считаться верным, если его абсолютная погрешность не превышает 7 <span class="tex-font-style-bf">или</span> его относительная погрешность не превышает $$$0.5$$$. Формально, пусть ваш ответ равен $$$ans$$$, а количество делителей $$$X$$$ равно $$$d$$$, тогда ваш ответ будет считаться правильным, если выполнено <span class="tex-font-style-bf">хотя бы одно</span> из следующих двух условий:</p><ul><li> $$$| ans - d | \le 7$$$;</li><li> $$$\frac{1}{2} \le \frac{ans}{d} \le 2$$$.</li></ul><p>Вы можете не более $$$22$$$ раз сделать запрос. Запрос состоит из одного целого числа $$$1 \le Q \le 10^{18}$$$. В ответ на запрос вы получите $$$gcd(X, Q)$$$ — наибольший общий делитель $$$X$$$ и $$$Q$$$.</p><p>Число $$$X$$$ зафиксировано до всех запросов. Иными словами, <span class="tex-font-style-bf">интерактор не является адаптивным</span>.</p><p>Назовём процесс отгадывания количества делителей числа $$$X$$$ <span class="tex-font-style-it">игрой</span>. В рамках одного теста вам нужно будет сыграть $$$T$$$ независимых игр, то есть отгадать количество делителей $$$T$$$ раз для $$$T$$$ независимых чисел $$$X$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>На первой строке записано одно целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество игр.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы сделать запрос, выведите строку вида «<span class="tex-font-style-tt">? Q</span>» ($$$1 \le Q \le 10^{18}$$$). После запроса считайте одно число — $$$gcd(X, Q)$$$. Вы можете сделать не более $$$22$$$ таких запросов в рамках одной игры.</p><p>Если вы считаете, что знаете количество делителей $$$X$$$ с достаточной точностью, выведите ваш ответ в формате «<span class="tex-font-style-tt">! ans</span>». $$$ans$$$ должно быть целым числом. Если это последняя игра, то вы должны завершить выполнение программы, иначе вы должны начать следующую игру. Обратите внимание, что интерактор не выводит ничего в ответ на вывод ответа.</p><p>После вывода запроса или ответа не забудьте вывести перевод строки и сбросить буфер вывода. Для сброса буфера вывода используйте:</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>Первая строка содержит одно целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество игр.</p><p>Каждая из следующих $$$T$$$ строк содержит одно целое число $$$X$$$($$$1 \le X \le 10^{9}$$$) — загаданное число.</p><p>Так, пример из условия имеет вид </p><pre class="verbatim"><br/>2<br/>998244353<br/>4194304<br/></pre></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1
1
1
1024
1048576
4194304
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 982306799268821872
? 230856864650023977
? 134690134760714371
! 5
? 1024
? 1048576
? 1073741824
! 42
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Почему ограничение на запросы именно 22? Возможно, автор задачи — фанат Тейлор Свифт.</p><p>Рассмотрим пример из условия.</p><p>В первой игре загадано число $$$X = 998\,244\,353$$$. Было бы сложно это угадать, правда? Это число является простым, то есть количество его делителей равно 2. Решение сделало запросы с несколькими случайными числами, и ответы на все запросы оказались равны 1 (удивительно, что ни один из трёх запросов не оказался кратным $$$998\,244\,353$$$). Логично предположить, что у загаданного числа не очень много делителей, поэтому решение ответило 5. Почему бы и не 5. Этот ответ будет засчитан, так как $$$| 5 - 2 | = 3 \le 7$$$.</p><p>Во второй игре загадано число $$$X = 4\,194\,304 = 2^{22}$$$, количество его делителей равно 23. Решение сделало запросы $$$1024 = 2^{10}$$$, $$$1\,048\,576 =2^{20}$$$, $$$1\,073\,741\,824 = 2^{30}$$$ и получило ответы $$$1024 = 2^{10}$$$, $$$1\,048\,576 =2^{20}$$$, $$$4\,194\,304 = 2^{22}$$$, соответственно. Затем решение окончательно запуталось и выдало ответ на Главный вопрос жизни, Вселенной и всего такого. Этот ответ будет засчитан, так как $$$\frac{1}{2} \le \frac{42}{23} \le 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="924c9601254352e84424c52d8f8b3e6a"/>
<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="592b9a15cba9650ad702e706e005bb936c66df5a"/>
<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='924c9601254352e84424c52d8f8b3e6a'> </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%2F1355%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='924c9601254352e84424c52d8f8b3e6a'/>
<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/1355">Codeforces Round 643 (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='924c9601254352e84424c52d8f8b3e6a'/>
<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/1355/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Теория чисел: функция Эйлера, НОД, делимость и др.">
теория чисел
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='924c9601254352e84424c52d8f8b3e6a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="621796"/>
<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='924c9601254352e84424c52d8f8b3e6a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="621796"/>
<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/77323" title="Codeforces Round #643 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10887" resourceName="Codeforces Round #643 (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/77491" title="Codeforces Round #643 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10893" resourceName="Codeforces Round #643 (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/1355">Задачи</a></li>
<li><a
href="/contest/1355/submit">Отослать</a></li>
<li><a
href="/contest/1355/my">Мои посылки</a></li>
<li><a
href="/contest/1355/status">Статус</a></li>
<li><a
href="/contest/1355/hacks">Взломы</a></li>
<li><a
href="/contest/1355/room/1">Комната</a></li>
<li><a
href="/contest/1355/standings">Положение</a></li>
<li><a
href="/contest/1355/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_15d1679cb93f09633f189fb4b5573bfe2370a039">
<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><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Загадано число $$$1 \le X \le 10^{9}$$$. Вам <span class="tex-font-style-bf">не нужно</span> угадывать это число. Вам нужно <span class="tex-font-style-bf">определить количество делителей</span> этого числа, и даже это вам <span class="tex-font-style-bf">не нужно делать точно</span>: ваш ответ будет считаться верным, если его абсолютная погрешность не превышает 7 <span class="tex-font-style-bf">или</span> его относительная погрешность не превышает $$$0.5$$$. Формально, пусть ваш ответ равен $$$ans$$$, а количество делителей $$$X$$$ равно $$$d$$$, тогда ваш ответ будет считаться правильным, если выполнено <span class="tex-font-style-bf">хотя бы одно</span> из следующих двух условий:</p><ul><li> $$$| ans - d | \le 7$$$;</li><li> $$$\frac{1}{2} \le \frac{ans}{d} \le 2$$$.</li></ul><p>Вы можете не более $$$22$$$ раз сделать запрос. Запрос состоит из одного целого числа $$$1 \le Q \le 10^{18}$$$. В ответ на запрос вы получите $$$gcd(X, Q)$$$ — наибольший общий делитель $$$X$$$ и $$$Q$$$.</p><p>Число $$$X$$$ зафиксировано до всех запросов. Иными словами, <span class="tex-font-style-bf">интерактор не является адаптивным</span>.</p><p>Назовём процесс отгадывания количества делителей числа $$$X$$$ <span class="tex-font-style-it">игрой</span>. В рамках одного теста вам нужно будет сыграть $$$T$$$ независимых игр, то есть отгадать количество делителей $$$T$$$ раз для $$$T$$$ независимых чисел $$$X$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>На первой строке записано одно целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество игр.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы сделать запрос, выведите строку вида «<span class="tex-font-style-tt">? Q</span>» ($$$1 \le Q \le 10^{18}$$$). После запроса считайте одно число — $$$gcd(X, Q)$$$. Вы можете сделать не более $$$22$$$ таких запросов в рамках одной игры.</p><p>Если вы считаете, что знаете количество делителей $$$X$$$ с достаточной точностью, выведите ваш ответ в формате «<span class="tex-font-style-tt">! ans</span>». $$$ans$$$ должно быть целым числом. Если это последняя игра, то вы должны завершить выполнение программы, иначе вы должны начать следующую игру. Обратите внимание, что интерактор не выводит ничего в ответ на вывод ответа.</p><p>После вывода запроса или ответа не забудьте вывести перевод строки и сбросить буфер вывода. Для сброса буфера вывода используйте:</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>Первая строка содержит одно целое число $$$T$$$ ($$$1 \le T \le 100$$$) — количество игр.</p><p>Каждая из следующих $$$T$$$ строк содержит одно целое число $$$X$$$($$$1 \le X \le 10^{9}$$$) — загаданное число.</p><p>Так, пример из условия имеет вид </p><pre class="verbatim"><br />2<br />998244353<br />4194304<br /></pre></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1
1
1
1024
1048576
4194304
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 982306799268821872
? 230856864650023977
? 134690134760714371
! 5
? 1024
? 1048576
? 1073741824
! 42
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Почему ограничение на запросы именно 22? Возможно, автор задачи — фанат Тейлор Свифт.</p><p>Рассмотрим пример из условия.</p><p>В первой игре загадано число $$$X = 998\,244\,353$$$. Было бы сложно это угадать, правда? Это число является простым, то есть количество его делителей равно 2. Решение сделало запросы с несколькими случайными числами, и ответы на все запросы оказались равны 1 (удивительно, что ни один из трёх запросов не оказался кратным $$$998\,244\,353$$$). Логично предположить, что у загаданного числа не очень много делителей, поэтому решение ответило 5. Почему бы и не 5. Этот ответ будет засчитан, так как $$$| 5 - 2 | = 3 \le 7$$$.</p><p>Во второй игре загадано число $$$X = 4\,194\,304 = 2^{22}$$$, количество его делителей равно 23. Решение сделало запросы $$$1024 = 2^{10}$$$, $$$1\,048\,576 =2^{20}$$$, $$$1\,073\,741\,824 = 2^{30}$$$ и получило ответы $$$1024 = 2^{10}$$$, $$$1\,048\,576 =2^{20}$$$, $$$4\,194\,304 = 2^{22}$$$, соответственно. Затем решение окончательно запуталось и выдало ответ на Главный вопрос жизни, Вселенной и всего такого. Этот ответ будет засчитан, так как $$$\frac{1}{2} \le \frac{42}{23} \le 2$$$.</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:03: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:'8124a15f2ece9d4c',t:'MTY5NjY2NTgzNS41NDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2600"] | ||
1358A | 1358 | A | ru | A. Освещение парка | <div class="problem-statement"><div class="header"><div class="title">A. Освещение парка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В связи с эпидемией коронавируса власти города обязали жителей соблюдать социальную дистанцию. Мэр города Семён Сергеевич хочет осветить парк Глухарники, чтобы люди даже ночью могли видеть друг друга и соблюдали дистанцию. </p><p>Парк представляет из себя прямоугольную таблицу состоящую из $$$n$$$ строк и $$$m$$$ столбцов, где клетки таблицы — площади, а границы между клетками — улицы. Также улицами являются внешние границы. Каждая улица имеет длину $$$1$$$. Например, у парка размера $$$n=m=2$$$ всего $$$12$$$ улиц.</p><p>Вам поручили разработать план освещения парка. Вы можете ставить фонари в серединах улиц. Фонарь освещает две площади, между которыми он стоит (или только одну площадь, если он стоит на границе парка).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/18aa1573b5d0c49e178a230e693800b5a0c2e6a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Пример парка размеров: $$$n=4$$$, $$$m=5$$$. Освещенные площади отмечены жёлтым цветом. Обратите внимание, что все улицы имеют длины $$$1$$$. Фонари ставятся в середины улиц. На картинке <span class="tex-font-style-bf">не все</span> площади освещены.</span> </center><p>Семён Сергеевич хочет потратить на освещение наименьшее возможное количество денег, но также хочет чтобы люди по всему парку держали социальную дистанцию. Поэтому он просит вас узнать, какое минимальное количество фонарей понадобится, чтобы осветить все площади.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных записывается одной строкой, содержащей два натуральных числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 10^4$$$) — размеры парка.</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>
5
1 1
1 3
2 2
3 3
5 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
2
5
8
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможное оптимальное расположение фонарей для $$$2$$$-го набора входных данных примера: <img class="tex-graphics" src="https://espresso.codeforces.com/9c98cd06c74ee783b366a57440a9ab57d0317193.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Возможное оптимальное расположение фонарей для $$$3$$$-го набора входных данных примера: <img class="tex-graphics" src="https://espresso.codeforces.com/ea550342416cdfaeadf987bfcfdab6d169d5f8ad.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="995fb868bdb49403de36a4af6ad4bbe3"/>
<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="8e1df481a86e7f7980d73e87046bbe9c10ffd3de"/>
<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='995fb868bdb49403de36a4af6ad4bbe3'> </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%2F1358%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='995fb868bdb49403de36a4af6ad4bbe3'/>
<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/1358">Codeforces Round 645 (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='995fb868bdb49403de36a4af6ad4bbe3'/>
<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/1358/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='995fb868bdb49403de36a4af6ad4bbe3'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="630275"/>
<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='995fb868bdb49403de36a4af6ad4bbe3'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="630275"/>
<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/77664" title="Codeforces Round #645 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10965:10966" 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/77869" title="Codeforces Round #645 (Div. 2) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11200:11201" 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/1358">Задачи</a></li>
<li><a
href="/contest/1358/submit">Отослать</a></li>
<li><a
href="/contest/1358/my">Мои посылки</a></li>
<li><a
href="/contest/1358/status">Статус</a></li>
<li><a
href="/contest/1358/hacks">Взломы</a></li>
<li><a
href="/contest/1358/room/1">Комната</a></li>
<li><a
href="/contest/1358/standings">Положение</a></li>
<li><a
href="/contest/1358/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_9b9780f7b391f99e1cf43f6938a72ba35ea40221">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Освещение парка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В связи с эпидемией коронавируса власти города обязали жителей соблюдать социальную дистанцию. Мэр города Семён Сергеевич хочет осветить парк Глухарники, чтобы люди даже ночью могли видеть друг друга и соблюдали дистанцию. </p><p>Парк представляет из себя прямоугольную таблицу состоящую из $$$n$$$ строк и $$$m$$$ столбцов, где клетки таблицы — площади, а границы между клетками — улицы. Также улицами являются внешние границы. Каждая улица имеет длину $$$1$$$. Например, у парка размера $$$n=m=2$$$ всего $$$12$$$ улиц.</p><p>Вам поручили разработать план освещения парка. Вы можете ставить фонари в серединах улиц. Фонарь освещает две площади, между которыми он стоит (или только одну площадь, если он стоит на границе парка).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/18aa1573b5d0c49e178a230e693800b5a0c2e6a8.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Пример парка размеров: $$$n=4$$$, $$$m=5$$$. Освещенные площади отмечены жёлтым цветом. Обратите внимание, что все улицы имеют длины $$$1$$$. Фонари ставятся в середины улиц. На картинке <span class="tex-font-style-bf">не все</span> площади освещены.</span> </center><p>Семён Сергеевич хочет потратить на освещение наименьшее возможное количество денег, но также хочет чтобы люди по всему парку держали социальную дистанцию. Поэтому он просит вас узнать, какое минимальное количество фонарей понадобится, чтобы осветить все площади.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных. Далее следуют $$$t$$$ наборов входных данных.</p><p>Каждый набор входных данных записывается одной строкой, содержащей два натуральных числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 10^4$$$) — размеры парка.</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>
5
1 1
1 3
2 2
3 3
5 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
2
5
8
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Возможное оптимальное расположение фонарей для $$$2$$$-го набора входных данных примера: <img class="tex-graphics" src="https://espresso.codeforces.com/9c98cd06c74ee783b366a57440a9ab57d0317193.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Возможное оптимальное расположение фонарей для $$$3$$$-го набора входных данных примера: <img class="tex-graphics" src="https://espresso.codeforces.com/ea550342416cdfaeadf987bfcfdab6d169d5f8ad.png" style="max-width: 100.0%;max-height: 100.0%;" /> </p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:03: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:'8124a167dc0375a3',t:'MTY5NjY2NTgzNi45MDIwMDA='};_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"] | ||
1358B | 1358 | 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$$$ других бабушек. Обратите внимание, что бабушки могут приходить во двор одновременно. Формально, бабушка $$$i$$$ готова прийти, если количество бабушек пришедших ранее или одновременно с ней больше или равно $$$a_i$$$.</p><p>Бабушки собираются во дворе так.</p><ul> <li> Изначально во дворе находится только Марья Ивановна (то есть количество бабушек во дворе равно $$$1$$$). Все остальные $$$n$$$ бабушек пока сидят по домам.</li><li> На очередном шаге Марья Ивановна выбирает подмножество бабушек, ни одна из которых ещё не вышла во двор. Каждой из них она обещает, что когда бабушка выйдет, во дворе будет не менее $$$a_i$$$ других бабушек (включая Марью Ивановну). Марья Ивановна может звонить сразу нескольким соседкам. В таком случае выбранные бабушки выйдут во двор <span class="tex-font-style-bf">одновременно</span>. </li><li> Вы не можете обманывать бабушек, то есть ситуация, когда $$$i$$$-я бабушка, после выхода во двор обнаружит, что сейчас во дворе строго меньше $$$a_i$$$ других бабушек (кроме неё самой, но включая Марью Ивановну), запрещена. Обратите внимание, что если несколько бабушек появились во дворе одновременно, то они каждая из них видит в том числе остальных в момент выхода. </li></ul><p>Ваша задача — найти, какое максимальное количество бабушек (включая себя) Марья Ивановна может собрать во дворе для проведения обряда «обкуривания от Короны-Вируса». Ведь чем больше людей в одном месте во время карантина, тем эффективнее обряд!</p><p>Рассмотрим пример: если $$$n=6$$$ и $$$a=[1,5,4,5,1,9]$$$, то:</p><ul> <li> на первом шаге Марья Ивановна может позвать бабушек с номерами $$$1$$$ и $$$5$$$, каждая из них будет видеть двух бабушек в момент выхода во двор (заметим, что $$$a_1=1 \le 2$$$ и $$$a_5=1 \le 2$$$); </li><li> на втором шаге Марья Ивановна может позвать бабушек с номерами $$$2$$$, $$$3$$$ и $$$4$$$, каждая из них будет видеть пять бабушек в момент выхода во двор (заметим, что $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ и $$$a_4=5 \le 5$$$); </li><li> бабушку номер $$$6$$$ позвать во двор не получится — следовательно, ответ на для такого примера равен $$$6$$$ (сама Марья Ивановна и еще $$$5$$$ суммарно вышедших бабушек). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют описания наборов входных данных.</p><p>Первая строка описания набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество бабушек (Марья Ивановна в это количество не входит). </p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$).</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число $$$k$$$ ($$$1 \le k \le 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
5
1 1 2 2 1
6
2 3 4 5 6 7
6
1 5 4 5 1 9
5
1 2 3 5 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
1
6
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера Марья Ивановна на первом шаге может позвать всех бабушек. Тогда каждая из них увидит пять бабушек, когда выйдет. Иными словами, ни одна не уйдёт домой. Поэтому во дворе будет Марья Ивановна и пять других бабушек.</p><p>Во втором наборе входных данных примера никто не сможет находиться во дворе, поэтому Марья Ивановна останется там одна.</p><p>Третий набор входных данных примера подробно разобран выше.</p><p>В четвёртом тестовом случае Марья Ивановна на первом шаге может позвать бабушек с номерами $$$1$$$, $$$2$$$ и $$$3$$$. Если на втором шаге Марья Ивановна позовёт только $$$4$$$-ю или только $$$5$$$-ю, то когда эта бабушка выходила бы во двор, то она бы увидела четверых бабушек, то есть Марья Ивановна по отдельности позвать $$$4$$$-ю и $$$5$$$-ю не может. Если она позовёт сразу обеих — $$$4$$$-ю и $$$5$$$-ю, то когда они будут выходить, то увидят по $$$4+1=5$$$ бабушек. Несмотря на то, что $$$4$$$-ю бабушку это устраивает, $$$5$$$-ю — этот вариант не устраивает. Следовательно, позвать одновременно $$$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="7446f6d1d732ba087eeb56f85c960470"/>
<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="8e1df481a86e7f7980d73e87046bbe9c10ffd3de"/>
<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='7446f6d1d732ba087eeb56f85c960470'> </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%2F1358%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='7446f6d1d732ba087eeb56f85c960470'/>
<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/1358">Codeforces Round 645 (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='7446f6d1d732ba087eeb56f85c960470'/>
<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/1358/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='7446f6d1d732ba087eeb56f85c960470'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="630276"/>
<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='7446f6d1d732ba087eeb56f85c960470'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="630276"/>
<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/77664" title="Codeforces Round #645 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10965:10966" 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/77869" title="Codeforces Round #645 (Div. 2) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11200:11201" 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/1358">Задачи</a></li>
<li><a
href="/contest/1358/submit">Отослать</a></li>
<li><a
href="/contest/1358/my">Мои посылки</a></li>
<li><a
href="/contest/1358/status">Статус</a></li>
<li><a
href="/contest/1358/hacks">Взломы</a></li>
<li><a
href="/contest/1358/room/1">Комната</a></li>
<li><a
href="/contest/1358/standings">Положение</a></li>
<li><a
href="/contest/1358/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_2f5a6c86a37651fb4ba8c48cb10ae9bcd7e306a0">
<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$$$ других бабушек. Обратите внимание, что бабушки могут приходить во двор одновременно. Формально, бабушка $$$i$$$ готова прийти, если количество бабушек пришедших ранее или одновременно с ней больше или равно $$$a_i$$$.</p><p>Бабушки собираются во дворе так.</p><ul> <li> Изначально во дворе находится только Марья Ивановна (то есть количество бабушек во дворе равно $$$1$$$). Все остальные $$$n$$$ бабушек пока сидят по домам.</li><li> На очередном шаге Марья Ивановна выбирает подмножество бабушек, ни одна из которых ещё не вышла во двор. Каждой из них она обещает, что когда бабушка выйдет, во дворе будет не менее $$$a_i$$$ других бабушек (включая Марью Ивановну). Марья Ивановна может звонить сразу нескольким соседкам. В таком случае выбранные бабушки выйдут во двор <span class="tex-font-style-bf">одновременно</span>. </li><li> Вы не можете обманывать бабушек, то есть ситуация, когда $$$i$$$-я бабушка, после выхода во двор обнаружит, что сейчас во дворе строго меньше $$$a_i$$$ других бабушек (кроме неё самой, но включая Марью Ивановну), запрещена. Обратите внимание, что если несколько бабушек появились во дворе одновременно, то они каждая из них видит в том числе остальных в момент выхода. </li></ul><p>Ваша задача — найти, какое максимальное количество бабушек (включая себя) Марья Ивановна может собрать во дворе для проведения обряда «обкуривания от Короны-Вируса». Ведь чем больше людей в одном месте во время карантина, тем эффективнее обряд!</p><p>Рассмотрим пример: если $$$n=6$$$ и $$$a=[1,5,4,5,1,9]$$$, то:</p><ul> <li> на первом шаге Марья Ивановна может позвать бабушек с номерами $$$1$$$ и $$$5$$$, каждая из них будет видеть двух бабушек в момент выхода во двор (заметим, что $$$a_1=1 \le 2$$$ и $$$a_5=1 \le 2$$$); </li><li> на втором шаге Марья Ивановна может позвать бабушек с номерами $$$2$$$, $$$3$$$ и $$$4$$$, каждая из них будет видеть пять бабушек в момент выхода во двор (заметим, что $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ и $$$a_4=5 \le 5$$$); </li><li> бабушку номер $$$6$$$ позвать во двор не получится — следовательно, ответ на для такого примера равен $$$6$$$ (сама Марья Ивановна и еще $$$5$$$ суммарно вышедших бабушек). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных в тесте. Далее следуют описания наборов входных данных.</p><p>Первая строка описания набора содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество бабушек (Марья Ивановна в это количество не входит). </p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$).</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число $$$k$$$ ($$$1 \le k \le 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
5
1 1 2 2 1
6
2 3 4 5 6 7
6
1 5 4 5 1 9
5
1 2 3 5 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
1
6
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных примера Марья Ивановна на первом шаге может позвать всех бабушек. Тогда каждая из них увидит пять бабушек, когда выйдет. Иными словами, ни одна не уйдёт домой. Поэтому во дворе будет Марья Ивановна и пять других бабушек.</p><p>Во втором наборе входных данных примера никто не сможет находиться во дворе, поэтому Марья Ивановна останется там одна.</p><p>Третий набор входных данных примера подробно разобран выше.</p><p>В четвёртом тестовом случае Марья Ивановна на первом шаге может позвать бабушек с номерами $$$1$$$, $$$2$$$ и $$$3$$$. Если на втором шаге Марья Ивановна позовёт только $$$4$$$-ю или только $$$5$$$-ю, то когда эта бабушка выходила бы во двор, то она бы увидела четверых бабушек, то есть Марья Ивановна по отдельности позвать $$$4$$$-ю и $$$5$$$-ю не может. Если она позовёт сразу обеих — $$$4$$$-ю и $$$5$$$-ю, то когда они будут выходить, то увидят по $$$4+1=5$$$ бабушек. Несмотря на то, что $$$4$$$-ю бабушку это устраивает, $$$5$$$-ю — этот вариант не устраивает. Следовательно, позвать одновременно $$$4$$$-ю и $$$5$$$-ю Марья Ивановна тоже не может. То есть во дворе будет только Марья Ивановна и три бабушки из первого шага.</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:03: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:'8124a1707d555aa6',t:'MTY5NjY2NTgzOC44MDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1000"] | ||
1358C | 1358 | C | ru | C. Обновление Celex | <div class="problem-statement"><div class="header"><div class="title">C. Обновление Celex</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айкромофта появилось больше свободного времени для реализации новых функций в «<span class="tex-font-style-tt">Celex-2021</span>». Разработчики сделали новую функцию <span class="tex-font-style-tt">GAZ-GIZ</span>, которая от левого верхнего угла бесконечно заполняет бесконечную вправо и вниз таблицу следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ab3c49666e913d52a14ebf7f09d741f3f712bacb.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Клетка с координатами $$$(x, y)$$$ находится на пересечение $$$x$$$-й строки и $$$y$$$-го столбца. Левая верхняя клетка $$$(1,1)$$$ содержит число $$$1$$$.</p><p>Разработчики функции <span class="tex-font-style-tt">SUM</span> тоже не спят. От скуки они сговорились с разработчиками функции <span class="tex-font-style-tt">RAND</span>, поэтому они добавили возможность посчитать сумму на произвольном пути от одной клетки до другой, передвигаясь вниз или вправо. Формально, из клетки $$$(x,y)$$$ за один шаг можно переместиться в клетку $$$(x+1, y)$$$ или $$$(x, y+1)$$$.</p><p>После очередного обновления Dinwows, Левиан решил изучать «<span class="tex-font-style-tt">Celex-2021</span>» (ведь он хочет стать бухгалтером!). После заполнения таблицы функцией <span class="tex-font-style-tt">GAZ-GIZ</span> он попросил вас посчитать количество возможных различных сумм на пути от заданной клетки $$$(x_1, y_1)$$$ до другой заданной клетки $$$(x_2, y_2$$$), если за один ход вы можете ходить только на одну ячейку вниз или вправо.</p><p>Формально, рассмотрим все пути из клетки $$$(x_1, y_1)$$$ в клетку $$$(x_2, y_2)$$$ такие, что каждая следующая клетка в пути располагается либо справа, либо снизу от предыдущей. Посчитайте количество различных сумм значений элементов для всех таких путей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 57179$$$) — количество наборов входных данных.</p><p>Каждая из следующих $$$t$$$ строк содержит четыре целых положительных числа $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1 \le x_2 \le 10^9$$$, $$$1 \le y_1 \le y_2 \le 10^9$$$) — координаты стартовой и конечной клеток. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных в отдельной строке выведите ответ — количество возможных различных сумм на пути от одной клетки до другой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 1 2 2
1 2 2 4
179 1 179 100000
5 7 5 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
1
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть две возможных суммы: $$$1+2+5=8$$$ и $$$1+3+5=9$$$. <img class="tex-graphics" src="https://espresso.codeforces.com/f80a32136dea106987ece7d1135079a5c040c792.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="83311c3352f8a45e5874506719e5c097"/>
<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="8e1df481a86e7f7980d73e87046bbe9c10ffd3de"/>
<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='83311c3352f8a45e5874506719e5c097'> </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%2F1358%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='83311c3352f8a45e5874506719e5c097'/>
<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/1358">Codeforces Round 645 (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='83311c3352f8a45e5874506719e5c097'/>
<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/1358/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="Сложность">
*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='83311c3352f8a45e5874506719e5c097'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="630277"/>
<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='83311c3352f8a45e5874506719e5c097'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="630277"/>
<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/77664" title="Codeforces Round #645 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10965:10966" 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/77869" title="Codeforces Round #645 (Div. 2) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11200:11201" 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/1358">Задачи</a></li>
<li><a
href="/contest/1358/submit">Отослать</a></li>
<li><a
href="/contest/1358/my">Мои посылки</a></li>
<li><a
href="/contest/1358/status">Статус</a></li>
<li><a
href="/contest/1358/hacks">Взломы</a></li>
<li><a
href="/contest/1358/room/1">Комната</a></li>
<li><a
href="/contest/1358/standings">Положение</a></li>
<li><a
href="/contest/1358/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_4f05e1085e9d93cd8a6b640b9c79fa108d7e0015">
<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. Обновление Celex</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айкромофта появилось больше свободного времени для реализации новых функций в «<span class="tex-font-style-tt">Celex-2021</span>». Разработчики сделали новую функцию <span class="tex-font-style-tt">GAZ-GIZ</span>, которая от левого верхнего угла бесконечно заполняет бесконечную вправо и вниз таблицу следующим образом:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/ab3c49666e913d52a14ebf7f09d741f3f712bacb.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Клетка с координатами $$$(x, y)$$$ находится на пересечение $$$x$$$-й строки и $$$y$$$-го столбца. Левая верхняя клетка $$$(1,1)$$$ содержит число $$$1$$$.</p><p>Разработчики функции <span class="tex-font-style-tt">SUM</span> тоже не спят. От скуки они сговорились с разработчиками функции <span class="tex-font-style-tt">RAND</span>, поэтому они добавили возможность посчитать сумму на произвольном пути от одной клетки до другой, передвигаясь вниз или вправо. Формально, из клетки $$$(x,y)$$$ за один шаг можно переместиться в клетку $$$(x+1, y)$$$ или $$$(x, y+1)$$$.</p><p>После очередного обновления Dinwows, Левиан решил изучать «<span class="tex-font-style-tt">Celex-2021</span>» (ведь он хочет стать бухгалтером!). После заполнения таблицы функцией <span class="tex-font-style-tt">GAZ-GIZ</span> он попросил вас посчитать количество возможных различных сумм на пути от заданной клетки $$$(x_1, y_1)$$$ до другой заданной клетки $$$(x_2, y_2$$$), если за один ход вы можете ходить только на одну ячейку вниз или вправо.</p><p>Формально, рассмотрим все пути из клетки $$$(x_1, y_1)$$$ в клетку $$$(x_2, y_2)$$$ такие, что каждая следующая клетка в пути располагается либо справа, либо снизу от предыдущей. Посчитайте количество различных сумм значений элементов для всех таких путей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 57179$$$) — количество наборов входных данных.</p><p>Каждая из следующих $$$t$$$ строк содержит четыре целых положительных числа $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \le x_1 \le x_2 \le 10^9$$$, $$$1 \le y_1 \le y_2 \le 10^9$$$) — координаты стартовой и конечной клеток. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных в отдельной строке выведите ответ — количество возможных различных сумм на пути от одной клетки до другой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 1 2 2
1 2 2 4
179 1 179 100000
5 7 5 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
1
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных есть две возможных суммы: $$$1+2+5=8$$$ и $$$1+3+5=9$$$. <img class="tex-graphics" src="https://espresso.codeforces.com/f80a32136dea106987ece7d1135079a5c040c792.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=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:04: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:'8124a17c3b469db4',t:'MTY5NjY2NTg0MC4yODcwMDA='};_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", "*1600"] | ||
1358D | 1358 | D | ru | D. Лучший отпуск | <div class="problem-statement"><div class="header"><div class="title">D. Лучший отпуск</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы давно влюблены в Коронавирус-тян, но до сих пор не знали, где она живёт. И буквально сейчас выяснили, что она живёт в далёком местечке под названием Ньаху. </p><p>Вы немедленно решили взять отпуск на своей скучной работы и навестить Коронавирус-тян. Ваш отпуск длится ровно $$$x$$$ дней, и ровно столько дней вы проведёте в гостях у подруги. В гостях вы проведёте ровно $$$x$$$ подряд идущих дней.</p><p>В Ньаху используется очень необычный календарь: всего в году $$$n$$$ месяцев, $$$i$$$-й месяц длится ровно $$$d_i$$$ дней. Дни в $$$i$$$-м месяце пронумерованы от $$$1$$$ до $$$d_i$$$. В Ньаху нет високосных годов.</p><p>Настроение Коронавирус-тян (и, соответственно, её желание вас обнять) зависит от номера дня в месяце. А именно, в $$$j$$$-й день месяца вы получаете $$$j$$$ объятий, если вы находитесь в гостях у Коронавирус-тян.</p><p>Вы знаете об этой особенности своей подруги и хотите спланировать свою поездку так, чтобы суммарно получить наибольшее возможное количество объятий (и тогда, быть может, вы сможете завоевать сердечко Коронавирус-тян). </p><p>Обратите внимание, ваша поездка <span class="tex-font-style-bf">не обязательно</span> должна начаться и закончиться в одном и том же году.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных даны два натуральных числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество месяцев в году и количество дней, которые вы можете провести в гостях у подруги.</p><p>Во второй строке даны $$$n$$$ целых чисел $$$d_1, d_2, \ldots, d_n$$$, где $$$d_i$$$ — количество дней в $$$i$$$-м месяце ($$$1 \le d_i \le 10^6$$$).</p><p>Гарантируется, что $$$1 \le x \le d_1 + d_2 + \ldots + d_n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — максимальное число объятий, которое вы можете получить от Коронавирус-тян за время лучшего отпуска в своей жизни.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 2
1 3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 6
3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 6
4 2 3 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
15</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере номера дней года (номера в соответствующих месяцах) имеет вид: $$$\{1,1,2,3,1\}$$$. Коронавирус-тян обнимет вас больше всего раз, если вы приедете в третий день года: $$$2+3=5$$$ объятий.</p><p>Во втором примере номера дней года (номера в соответствующих месяцах) имеет вид: $$$\{1,2,3,1,2,3,1,2,3\}$$$. Больше всего объятий вы получите если приедете в третий день года: $$$3+1+2+3+1+2=12$$$ объятий.</p><p>В третьем примере номера дней имеют вид: $$$\{1,2,3,4,1,2, 1,2,3, 1, 1,2,3\}$$$. Больше всего объятий вы получите если приедете в двенадцатый день года: подруга обнимет вас $$$2+3+1+2+3+4=15$$$ раз. </p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="e8c03b51848f31c99951a7dccf5d918e"/>
<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="8e1df481a86e7f7980d73e87046bbe9c10ffd3de"/>
<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='e8c03b51848f31c99951a7dccf5d918e'> </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%2F1358%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='e8c03b51848f31c99951a7dccf5d918e'/>
<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/1358">Codeforces Round 645 (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='e8c03b51848f31c99951a7dccf5d918e'/>
<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/1358/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='e8c03b51848f31c99951a7dccf5d918e'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="630278"/>
<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='e8c03b51848f31c99951a7dccf5d918e'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="630278"/>
<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/77664" title="Codeforces Round #645 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10965:10966" 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/77869" title="Codeforces Round #645 (Div. 2) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11200:11201" 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/1358">Задачи</a></li>
<li><a
href="/contest/1358/submit">Отослать</a></li>
<li><a
href="/contest/1358/my">Мои посылки</a></li>
<li><a
href="/contest/1358/status">Статус</a></li>
<li><a
href="/contest/1358/hacks">Взломы</a></li>
<li><a
href="/contest/1358/room/1">Комната</a></li>
<li><a
href="/contest/1358/standings">Положение</a></li>
<li><a
href="/contest/1358/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_e38777c571c7efdc87f416e3ed76cb7904d54d16">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Лучший отпуск</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы давно влюблены в Коронавирус-тян, но до сих пор не знали, где она живёт. И буквально сейчас выяснили, что она живёт в далёком местечке под названием Ньаху. </p><p>Вы немедленно решили взять отпуск на своей скучной работы и навестить Коронавирус-тян. Ваш отпуск длится ровно $$$x$$$ дней, и ровно столько дней вы проведёте в гостях у подруги. В гостях вы проведёте ровно $$$x$$$ подряд идущих дней.</p><p>В Ньаху используется очень необычный календарь: всего в году $$$n$$$ месяцев, $$$i$$$-й месяц длится ровно $$$d_i$$$ дней. Дни в $$$i$$$-м месяце пронумерованы от $$$1$$$ до $$$d_i$$$. В Ньаху нет високосных годов.</p><p>Настроение Коронавирус-тян (и, соответственно, её желание вас обнять) зависит от номера дня в месяце. А именно, в $$$j$$$-й день месяца вы получаете $$$j$$$ объятий, если вы находитесь в гостях у Коронавирус-тян.</p><p>Вы знаете об этой особенности своей подруги и хотите спланировать свою поездку так, чтобы суммарно получить наибольшее возможное количество объятий (и тогда, быть может, вы сможете завоевать сердечко Коронавирус-тян). </p><p>Обратите внимание, ваша поездка <span class="tex-font-style-bf">не обязательно</span> должна начаться и закончиться в одном и том же году.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных даны два натуральных числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — количество месяцев в году и количество дней, которые вы можете провести в гостях у подруги.</p><p>Во второй строке даны $$$n$$$ целых чисел $$$d_1, d_2, \ldots, d_n$$$, где $$$d_i$$$ — количество дней в $$$i$$$-м месяце ($$$1 \le d_i \le 10^6$$$).</p><p>Гарантируется, что $$$1 \le x \le d_1 + d_2 + \ldots + d_n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное число — максимальное число объятий, которое вы можете получить от Коронавирус-тян за время лучшего отпуска в своей жизни.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3 2
1 3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 6
3 3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 6
4 2 3 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
15</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере номера дней года (номера в соответствующих месяцах) имеет вид: $$$\{1,1,2,3,1\}$$$. Коронавирус-тян обнимет вас больше всего раз, если вы приедете в третий день года: $$$2+3=5$$$ объятий.</p><p>Во втором примере номера дней года (номера в соответствующих месяцах) имеет вид: $$$\{1,2,3,1,2,3,1,2,3\}$$$. Больше всего объятий вы получите если приедете в третий день года: $$$3+1+2+3+1+2=12$$$ объятий.</p><p>В третьем примере номера дней имеют вид: $$$\{1,2,3,4,1,2, 1,2,3, 1, 1,2,3\}$$$. Больше всего объятий вы получите если приедете в двенадцатый день года: подруга обнимет вас $$$2+3+1+2+3+4=15$$$ раз. </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:04: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:'8124a1857a8d167e',t:'MTY5NjY2NTg0MS42NDcwMDA='};_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", "\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"] | ["\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1900"] | ||
1358E | 1358 | E | ru | E. Вы уволены? | <div class="problem-statement"><div class="header"><div class="title">E. Вы уволены?</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Левиан работает бухгалтером в большой компании. Он знает, сколько компания заработала в каждый из $$$n$$$ подряд идущих месяцев — в $$$i$$$-й месяц у компании доход был равен $$$a_i$$$ (положительный доход означает прибыль, отрицательный доход означает убыль, нулевой доход означает отсутствие изменений). Из-за всеобщей самоизоляции, первые $$$\lceil \tfrac{n}{2} \rceil$$$ месяцев доход мог быть совершенно нестабилен, но потом всё стабилизировалось и последние $$$\lfloor \tfrac{n}{2} \rfloor$$$ месяцев <span class="tex-font-style-bf">доход был одинаковый</span>.</p><p>Левиан решил, что на совете директоров сообщит $$$n-k+1$$$ число — суммарный доход компании за каждые $$$k$$$ подряд идущих месяцев. Формально, для всех $$$i$$$ от $$$1$$$ до $$$n-k+1$$$ он скажет число $$$a_i + a_{i+1} + \ldots + a_{i + k - 1}$$$. Например, если $$$a=[-1, 0, 1, 2, 2]$$$ и $$$k=3$$$, то он сообщит числа $$$0, 3, 5$$$.</p><p>К большому сожалению, если хоть один суммарный доход, сообщаемый Левианом, не является прибылью (то есть доход $$$\le 0$$$), то начальство разозлится и уволит не справившегося с работой бухгалтера.</p><p>Спасите карьеру Левиана: найдите такое число $$$k$$$, что за любые $$$k$$$ подряд идущих месяцев компания получила прибыль или скажите, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 5\cdot 10^5$$$) — количество месяцев, за которые Левиан должен отчитаться. </p><p>Вторая строка содержит $$$\lceil{\frac{n}{2}}\rceil$$$ целых чисел $$$a_1, a_2, \ldots, a_{\lceil{\frac{n}{2}}\rceil}$$$, где $$$a_i$$$ ($$$-10^9 \le a_i \le 10^9$$$) — доход компании в $$$i$$$-м месяце.</p><p>Третья строка содержит одно целое число $$$x$$$ ($$$-10^9 \le x \le 10^9$$$)— доход в каждый месяц с $$$\lceil{\frac{n}{2}}\rceil + 1$$$ до $$$n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите искомое число $$$k$$$ или $$$-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 -1
2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
2 2 -8
2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
-2 -2 6
-1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подходят $$$k=2$$$ и $$$k=3$$$: в первом случае Левиан сообщит числа $$$1, 1$$$ а во втором — одно число $$$3$$$.</p><p>Во втором примере ни одно $$$k$$$ не подходит.</p><p>В третьем примере ответом является только $$$k=4$$$: он сообщит числа $$$1,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="d811f06cf676a5de18fe0b794c94527d"/>
<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="8e1df481a86e7f7980d73e87046bbe9c10ffd3de"/>
<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='d811f06cf676a5de18fe0b794c94527d'> </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%2F1358%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='d811f06cf676a5de18fe0b794c94527d'/>
<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/1358">Codeforces Round 645 (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='d811f06cf676a5de18fe0b794c94527d'/>
<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/1358/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d811f06cf676a5de18fe0b794c94527d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="630279"/>
<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='d811f06cf676a5de18fe0b794c94527d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="630279"/>
<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/77664" title="Codeforces Round #645 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10965:10966" 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/77869" title="Codeforces Round #645 (Div. 2) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11200:11201" 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/1358">Задачи</a></li>
<li><a
href="/contest/1358/submit">Отослать</a></li>
<li><a
href="/contest/1358/my">Мои посылки</a></li>
<li><a
href="/contest/1358/status">Статус</a></li>
<li><a
href="/contest/1358/hacks">Взломы</a></li>
<li><a
href="/contest/1358/room/1">Комната</a></li>
<li><a
href="/contest/1358/standings">Положение</a></li>
<li><a
href="/contest/1358/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_73d522f00fd404330f9a4a009dbd7282f3c6e8f5">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Вы уволены?</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Левиан работает бухгалтером в большой компании. Он знает, сколько компания заработала в каждый из $$$n$$$ подряд идущих месяцев — в $$$i$$$-й месяц у компании доход был равен $$$a_i$$$ (положительный доход означает прибыль, отрицательный доход означает убыль, нулевой доход означает отсутствие изменений). Из-за всеобщей самоизоляции, первые $$$\lceil \tfrac{n}{2} \rceil$$$ месяцев доход мог быть совершенно нестабилен, но потом всё стабилизировалось и последние $$$\lfloor \tfrac{n}{2} \rfloor$$$ месяцев <span class="tex-font-style-bf">доход был одинаковый</span>.</p><p>Левиан решил, что на совете директоров сообщит $$$n-k+1$$$ число — суммарный доход компании за каждые $$$k$$$ подряд идущих месяцев. Формально, для всех $$$i$$$ от $$$1$$$ до $$$n-k+1$$$ он скажет число $$$a_i + a_{i+1} + \ldots + a_{i + k - 1}$$$. Например, если $$$a=[-1, 0, 1, 2, 2]$$$ и $$$k=3$$$, то он сообщит числа $$$0, 3, 5$$$.</p><p>К большому сожалению, если хоть один суммарный доход, сообщаемый Левианом, не является прибылью (то есть доход $$$\le 0$$$), то начальство разозлится и уволит не справившегося с работой бухгалтера.</p><p>Спасите карьеру Левиана: найдите такое число $$$k$$$, что за любые $$$k$$$ подряд идущих месяцев компания получила прибыль или скажите, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$2 \le n \le 5\cdot 10^5$$$) — количество месяцев, за которые Левиан должен отчитаться. </p><p>Вторая строка содержит $$$\lceil{\frac{n}{2}}\rceil$$$ целых чисел $$$a_1, a_2, \ldots, a_{\lceil{\frac{n}{2}}\rceil}$$$, где $$$a_i$$$ ($$$-10^9 \le a_i \le 10^9$$$) — доход компании в $$$i$$$-м месяце.</p><p>Третья строка содержит одно целое число $$$x$$$ ($$$-10^9 \le x \le 10^9$$$)— доход в каждый месяц с $$$\lceil{\frac{n}{2}}\rceil + 1$$$ до $$$n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите искомое число $$$k$$$ или $$$-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 -1
2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
2 2 -8
2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
-2 -2 6
-1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере подходят $$$k=2$$$ и $$$k=3$$$: в первом случае Левиан сообщит числа $$$1, 1$$$ а во втором — одно число $$$3$$$.</p><p>Во втором примере ни одно $$$k$$$ не подходит.</p><p>В третьем примере ответом является только $$$k=4$$$: он сообщит числа $$$1,2,3$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04: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:'8124a18dfccd3374',t:'MTY5NjY2NTg0My4xNDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"] | ||
1358F | 1358 | 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>О нет!</p><p>Вас поймал коронавирус, и теперь вы сидите в тёмном подвале, связанные по ногам (но не по рукам). У вас есть вкусная печенька, а также перед вами стоит ноутбук, и там открыта ваша любимая среда разработки. Коронавирус убеждает вас решить следующую задачу.</p><p>Вам дано два массива $$$A$$$ и $$$B$$$ размера $$$n$$$. Вы можете делать операции двух типов с массивом $$$A$$$: </p><ul> <li> Развернуть массив $$$A$$$. То есть массив $$$[A_1,\ A_2,\ \ldots,\ A_n]$$$ переходит в $$$[A_n,\ A_{n-1},\ \ldots,\ A_1]$$$ </li><li> Заменить $$$A$$$ на массив его префиксных сумм. То есть массив $$$[A_1,\ A_2,\ \ldots,\ A_n]$$$ переходит в $$$[A_1,\ (A_1+A_2),\ \ldots,\ (A_1+A_2+\ldots+A_n)]$$$ </li></ul><p>Вам нужно понять, можно ли из массива $$$A$$$ получить массив $$$B$$$. Если это можно сделать, то вам придётся восстановить порядок этих операций, минимизировав количество операций второго типа. К счастью, коронавирус сегодня добрый, поэтому он разрешил вам не восстанавливать действия, если минимальное количество операций второго типа превышает $$$2\cdot 10^5$$$. Но коронавирус обижен на вас, поэтому если вы восстанавливаете ответ, то суммарное количество операций не должно превышать $$$5\cdot 10^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><p>Вторая строка содержит $$$n$$$ целых чисел $$$A_1, A_2, \ldots, A_n$$$ ($$$1 \le A_i \le 10 ^ {12}$$$).</p><p>Третья строка содержит $$$n$$$ целых чисел $$$B_1, B_2, \ldots, B_n$$$ ($$$1 \le B_i \le 10 ^ {12}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если из массива $$$A$$$ нельзя получить массив $$$B$$$, в единственной строке выведите «<span class="tex-font-style-tt">IMPOSSIBLE</span>» (без кавычек).</p><p>Если минимальное количество операций второго типа превышает $$$2\cdot 10^5$$$, то в первой строке выведите «<span class="tex-font-style-tt">BIG</span>» (без кавычек). Во второй строке выведите минимальное количество операций второго типа, которые нужно применить, чтобы из массива $$$A$$$ получить $$$B$$$.</p><p>Иначе, в первой строке выведите «<span class="tex-font-style-tt">SMALL</span>» (без кавычек). Во второй строке выведите суммарное количество операций первого и второго типа $$$m \le 5\cdot 10^5$$$ (гарантируется, что в этом случае существует такая последовательность действий). В третьей строке выведите строку длины $$$m$$$, состоящую из символов «<span class="tex-font-style-tt">R</span>» и «<span class="tex-font-style-tt">P</span>» (без кавычек):</p><p>$$$i$$$-й символ должен быть равен '<span class="tex-font-style-tt">R</span>', если $$$i$$$-е действие первого типа, и должен быть равен '<span class="tex-font-style-tt">P</span>', иначе.</p><p>Если таких последовательностей несколько, выведите любую из них.</p><p>Вы можете выводить все символы как в нижнем регистре, так и в верхнем.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
5 7
5 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
SMALL
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
1 1
300000 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
BIG
299999
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
10 1
13 14
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
SMALL
6
RPPPRP
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 2 1
2 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
IMPOSSIBLE
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере массивы $$$A$$$ и $$$B$$$ уже совпадает, поэтому количество нужных операций $$$=0$$$.</p><p>Во втором примере надо $$$299999$$$ раз заменить $$$A$$$ на префиксную сумму, а потом развернуть массив. Так как $$$299999>2\cdot 10^5$$$, то восстанавливать ответ не нужно.</p><p>В четвёртом примере из массива $$$A$$$ никак нельзя получить $$$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="42ddbe890f1af9ac658fd9c2f40bf161"/>
<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="8e1df481a86e7f7980d73e87046bbe9c10ffd3de"/>
<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='42ddbe890f1af9ac658fd9c2f40bf161'> </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%2F1358%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='42ddbe890f1af9ac658fd9c2f40bf161'/>
<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/1358">Codeforces Round 645 (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='42ddbe890f1af9ac658fd9c2f40bf161'/>
<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/1358/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='42ddbe890f1af9ac658fd9c2f40bf161'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="630280"/>
<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='42ddbe890f1af9ac658fd9c2f40bf161'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="630280"/>
<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/77664" title="Codeforces Round #645 (Div. 2)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10965:10966" 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/77869" title="Codeforces Round #645 (Div. 2) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11200:11201" 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/1358">Задачи</a></li>
<li><a
href="/contest/1358/submit">Отослать</a></li>
<li><a
href="/contest/1358/my">Мои посылки</a></li>
<li><a
href="/contest/1358/status">Статус</a></li>
<li><a
href="/contest/1358/hacks">Взломы</a></li>
<li><a
href="/contest/1358/room/1">Комната</a></li>
<li><a
href="/contest/1358/standings">Положение</a></li>
<li><a
href="/contest/1358/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_ed37371db50f72aa748b6fabc679b09d69e91145">
<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>О нет!</p><p>Вас поймал коронавирус, и теперь вы сидите в тёмном подвале, связанные по ногам (но не по рукам). У вас есть вкусная печенька, а также перед вами стоит ноутбук, и там открыта ваша любимая среда разработки. Коронавирус убеждает вас решить следующую задачу.</p><p>Вам дано два массива $$$A$$$ и $$$B$$$ размера $$$n$$$. Вы можете делать операции двух типов с массивом $$$A$$$: </p><ul> <li> Развернуть массив $$$A$$$. То есть массив $$$[A_1,\ A_2,\ \ldots,\ A_n]$$$ переходит в $$$[A_n,\ A_{n-1},\ \ldots,\ A_1]$$$ </li><li> Заменить $$$A$$$ на массив его префиксных сумм. То есть массив $$$[A_1,\ A_2,\ \ldots,\ A_n]$$$ переходит в $$$[A_1,\ (A_1+A_2),\ \ldots,\ (A_1+A_2+\ldots+A_n)]$$$ </li></ul><p>Вам нужно понять, можно ли из массива $$$A$$$ получить массив $$$B$$$. Если это можно сделать, то вам придётся восстановить порядок этих операций, минимизировав количество операций второго типа. К счастью, коронавирус сегодня добрый, поэтому он разрешил вам не восстанавливать действия, если минимальное количество операций второго типа превышает $$$2\cdot 10^5$$$. Но коронавирус обижен на вас, поэтому если вы восстанавливаете ответ, то суммарное количество операций не должно превышать $$$5\cdot 10^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><p>Вторая строка содержит $$$n$$$ целых чисел $$$A_1, A_2, \ldots, A_n$$$ ($$$1 \le A_i \le 10 ^ {12}$$$).</p><p>Третья строка содержит $$$n$$$ целых чисел $$$B_1, B_2, \ldots, B_n$$$ ($$$1 \le B_i \le 10 ^ {12}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если из массива $$$A$$$ нельзя получить массив $$$B$$$, в единственной строке выведите «<span class="tex-font-style-tt">IMPOSSIBLE</span>» (без кавычек).</p><p>Если минимальное количество операций второго типа превышает $$$2\cdot 10^5$$$, то в первой строке выведите «<span class="tex-font-style-tt">BIG</span>» (без кавычек). Во второй строке выведите минимальное количество операций второго типа, которые нужно применить, чтобы из массива $$$A$$$ получить $$$B$$$.</p><p>Иначе, в первой строке выведите «<span class="tex-font-style-tt">SMALL</span>» (без кавычек). Во второй строке выведите суммарное количество операций первого и второго типа $$$m \le 5\cdot 10^5$$$ (гарантируется, что в этом случае существует такая последовательность действий). В третьей строке выведите строку длины $$$m$$$, состоящую из символов «<span class="tex-font-style-tt">R</span>» и «<span class="tex-font-style-tt">P</span>» (без кавычек):</p><p>$$$i$$$-й символ должен быть равен '<span class="tex-font-style-tt">R</span>', если $$$i$$$-е действие первого типа, и должен быть равен '<span class="tex-font-style-tt">P</span>', иначе.</p><p>Если таких последовательностей несколько, выведите любую из них.</p><p>Вы можете выводить все символы как в нижнем регистре, так и в верхнем.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
5 7
5 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
SMALL
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
1 1
300000 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
BIG
299999
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
10 1
13 14
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
SMALL
6
RPPPRP
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 2 1
2 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
IMPOSSIBLE
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере массивы $$$A$$$ и $$$B$$$ уже совпадает, поэтому количество нужных операций $$$=0$$$.</p><p>Во втором примере надо $$$299999$$$ раз заменить $$$A$$$ на префиксную сумму, а потом развернуть массив. Так как $$$299999>2\cdot 10^5$$$, то восстанавливать ответ не нужно.</p><p>В четвёртом примере из массива $$$A$$$ никак нельзя получить $$$B$$$.</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:04: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:'8124a1977b7d1616',t:'MTY5NjY2NTg0NC40OTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2700"] | ||
1359A | 1359 | 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>В берляндский покер играют с колодой из $$$n$$$ карт, $$$m$$$ из которых являются джокерами. В игре участвует $$$k$$$ игроков ($$$n$$$ делится на $$$k$$$).</p><p>В начале игры каждый игрок берет $$$\frac{n}{k}$$$ карт из колоды (таким образом, каждая карта берется ровно одним игроком). Игрок, у которого максимальное количество джокеров в руке, является победителем, и он получает количество очков, равное $$$x - y$$$, где $$$x$$$ — количество джокеров в руке победителя, а $$$y$$$ — максимальное количество джокеров среди всех других игроков. Если есть два или более игроков с максимальным количеством джокеров, все они являются победителями, и они получают $$$0$$$ очков.</p><p>Вот несколько примеров:</p><ul> <li> $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. Если один игрок получает $$$3$$$ джокера и $$$1$$$ простую карту, а другой игрок получает $$$0$$$ джокеров и $$$4$$$ простые карты, то первый игрок является победителем и получает $$$3 - 0 = 3$$$ очка; </li><li> $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Два игрока получают простые карты, а два других игрока получают джокеры, так что оба они являются победителями и получают $$$0$$$ очков; </li><li> $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. Если первый игрок получает $$$3$$$ джокера, второй игрок получает $$$1$$$ джокера и $$$2$$$ простые карты, а третий игрок получает $$$2$$$ джокера и $$$1$$$ простую карту, то первый игрок является победителем, и он получает $$$3 - 2 = 1$$$ очко; </li><li> $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Поскольку джокеров нет, каждый получает $$$0$$$ джокеров, каждый является победителем, и каждый получает $$$0$$$ очков. </li></ul><p>Для заданных $$$n$$$, $$$m$$$ и $$$k$$$ вычислите максимальное количество очков, которое игрок может получить за победу в игре.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 500$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ делит $$$n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — максимальное количество очков, которое игрок может получить за победу в игре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
8 3 2
4 2 4
9 6 3
42 0 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
0
1
0
</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="c7c40a8d3e9d8a9f0778634a38946e06"/>
<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="3913f22e6d079d2e4a21d513a093e067724a767e"/>
<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='c7c40a8d3e9d8a9f0778634a38946e06'> </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%2F1359%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='c7c40a8d3e9d8a9f0778634a38946e06'/>
<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/1359">Educational Codeforces Round 88 (рейтинговый для Див. 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='c7c40a8d3e9d8a9f0778634a38946e06'/>
<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/1359/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='c7c40a8d3e9d8a9f0778634a38946e06'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="634672"/>
<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='c7c40a8d3e9d8a9f0778634a38946e06'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="634672"/>
<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/78016" title="Educational Codeforces Round 88 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10982:10983" 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/78116" title="Разбор Educational Codeforces Round 88" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10993:10994" 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/1359">Задачи</a></li>
<li><a
href="/contest/1359/submit">Отослать</a></li>
<li><a
href="/contest/1359/my">Мои посылки</a></li>
<li><a
href="/contest/1359/status">Статус</a></li>
<li><a
href="/contest/1359/hacks">Взломы</a></li>
<li><a
href="/contest/1359/standings">Положение</a></li>
<li><a
href="/contest/1359/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_7c769024a936721b92ce2d9f854458302dc03a0b">
<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>В берляндский покер играют с колодой из $$$n$$$ карт, $$$m$$$ из которых являются джокерами. В игре участвует $$$k$$$ игроков ($$$n$$$ делится на $$$k$$$).</p><p>В начале игры каждый игрок берет $$$\frac{n}{k}$$$ карт из колоды (таким образом, каждая карта берется ровно одним игроком). Игрок, у которого максимальное количество джокеров в руке, является победителем, и он получает количество очков, равное $$$x - y$$$, где $$$x$$$ — количество джокеров в руке победителя, а $$$y$$$ — максимальное количество джокеров среди всех других игроков. Если есть два или более игроков с максимальным количеством джокеров, все они являются победителями, и они получают $$$0$$$ очков.</p><p>Вот несколько примеров:</p><ul> <li> $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. Если один игрок получает $$$3$$$ джокера и $$$1$$$ простую карту, а другой игрок получает $$$0$$$ джокеров и $$$4$$$ простые карты, то первый игрок является победителем и получает $$$3 - 0 = 3$$$ очка; </li><li> $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Два игрока получают простые карты, а два других игрока получают джокеры, так что оба они являются победителями и получают $$$0$$$ очков; </li><li> $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. Если первый игрок получает $$$3$$$ джокера, второй игрок получает $$$1$$$ джокера и $$$2$$$ простые карты, а третий игрок получает $$$2$$$ джокера и $$$1$$$ простую карту, то первый игрок является победителем, и он получает $$$3 - 2 = 1$$$ очко; </li><li> $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Поскольку джокеров нет, каждый получает $$$0$$$ джокеров, каждый является победителем, и каждый получает $$$0$$$ очков. </li></ul><p>Для заданных $$$n$$$, $$$m$$$ и $$$k$$$ вычислите максимальное количество очков, которое игрок может получить за победу в игре.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ ($$$1 \le t \le 500$$$) — количество наборов входных данных.</p><p>Каждый набор входных данных содержит три целых числа $$$n$$$, $$$m$$$ и $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ делит $$$n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — максимальное количество очков, которое игрок может получить за победу в игре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
8 3 2
4 2 4
9 6 3
42 0 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
0
1
0
</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=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:04: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:'8124a19fcbce75b7',t:'MTY5NjY2NTg0NS44ODQwMDA='};_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", "*1000"] | ||
1359B | 1359 | 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 href="https://codeforces.com/problemset/problem/1/A">задачи 1A</a>. Сегодня ее покрытие наконец-то заменят.</p><p>Площадь все еще является прямоугольником $$$n \times m$$$ метров. Однако, рисунок на ней будет более сложным в этот раз. Пусть $$$a_{i,j}$$$ будет $$$j$$$-й ячейкой в $$$i$$$-м ряду покрытия плитками.</p><p>Вам задан рисунок покрытия:</p><ul> <li> если $$$a_{i,j} = $$$ «<span class="tex-font-style-tt">*</span>», то $$$j$$$-я ячейка в $$$i$$$-м ряду должна быть <span class="tex-font-style-bf">черной</span>; </li><li> если $$$a_{i,j} = $$$ «<span class="tex-font-style-tt">.</span>», то $$$j$$$-я ячейка в $$$i$$$-м ряду должна быть <span class="tex-font-style-bf">белой</span>. </li></ul><p>Черные ячейки уже покрыты. Вам же необходимо покрыть белые ячейки. Существует две опции плиток:</p><ul> <li> $$$1 \times 1$$$ плитки — каждая плитка стоит $$$x$$$ бурлей и покрывает ровно $$$1$$$ ячейку; </li><li> $$$1 \times 2$$$ плитки — каждая плитка стоит $$$y$$$ бурлей и покрывает ровно $$$2$$$ соседние ячейки в <span class="tex-font-style-bf">одном ряду</span>. <span class="tex-font-style-bf">Обратите внимание, что нельзя вращать эти плитки или резать их на плитки $$$1 \times 1$$$.</span> </li></ul><p><span class="tex-font-style-bf">Вам необходимо покрыть все белые ячейки, никакие две плитки не должны накладываться друг на друга и никакие черные ячейки не должны быть накрыты плитками</span>.</p><p>Чему равна наименьшая суммарная цена плиток, которые могут покрыть все белые клетки?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 500$$$) — количество наборов входных данных. Затем следует описание $$$t$$$ наборов.</p><p>В первой строке каждого набора входных данных записаны четыре целых числа $$$n$$$, $$$m$$$, $$$x$$$ и $$$y$$$ ($$$1 \le n \le 100$$$; $$$1 \le m \le 1000$$$; $$$1 \le x, y \le 1000$$$) — размеры Театральной площади, цена плитки $$$1 \times 1$$$ и цена плитки $$$1 \times 2$$$.</p><p>В каждой из следующих $$$n$$$ строк записаны по $$$m$$$ символов. $$$j$$$-й символ в $$$i$$$-й строке — это $$$a_{i,j}$$$. Если $$$a_{i,j} = $$$ «<span class="tex-font-style-tt">*</span>», то $$$j$$$-я ячейка в $$$i$$$-м ряду должна быть <span class="tex-font-style-bf">черной</span>, а если $$$a_{i,j} = $$$ «<span class="tex-font-style-tt">.</span>», то $$$j$$$-я ячейка в $$$i$$$-м ряду должна быть <span class="tex-font-style-bf">белой</span>.</p><p><span class="tex-font-style-bf">Гарантируется, что сумма $$$n \times m$$$ по всем наборам входных данных не превышает $$$10^5$$$</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — наименьшая суммарная цена плиток, которые могут покрыть все белые клетки, в бурлях.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 1 10 1
.
1 2 10 1
..
2 1 10 1
.
.
3 3 3 7
..*
*..
.*.
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
1
20
18
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных необходимо использовать одну плитку $$$1 \times 1$$$, несмотря на то, что плитка $$$1 \times 2$$$ дешевле. Поэтому суммарная цена равна $$$10$$$ бурлей.</p><p>Во втором наборе можно использовать либо две плитки $$$1 \times 1$$$ и потратить $$$20$$$ бурлей, либо одну плитку $$$1 \times 2$$$ плитку и потратить $$$1$$$ бурль. Второй вариант дешевле, поэтому ответ равен $$$1$$$.</p><p>Третий набор показывает, что нельзя поворачивать плитки $$$1 \times 2$$$. Приходится использовать две плитки $$$1 \times 1$$$ с суммарной ценой $$$20$$$.</p><p>В четвертом наборе самый дешевый способ — это использовать $$$1 \times 1$$$ плитки повсюду. Итоговая цена — $$$6 \cdot 3 = 18$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="91ae05409fa717b7f9a633e6ab8763d0"/>
<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="3913f22e6d079d2e4a21d513a093e067724a767e"/>
<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='91ae05409fa717b7f9a633e6ab8763d0'> </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%2F1359%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='91ae05409fa717b7f9a633e6ab8763d0'/>
<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/1359">Educational Codeforces Round 88 (рейтинговый для Див. 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='91ae05409fa717b7f9a633e6ab8763d0'/>
<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/1359/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="Сложность">
*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='91ae05409fa717b7f9a633e6ab8763d0'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="634673"/>
<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='91ae05409fa717b7f9a633e6ab8763d0'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="634673"/>
<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/78016" title="Educational Codeforces Round 88 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10982:10983" 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/78116" title="Разбор Educational Codeforces Round 88" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10993:10994" 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/1359">Задачи</a></li>
<li><a
href="/contest/1359/submit">Отослать</a></li>
<li><a
href="/contest/1359/my">Мои посылки</a></li>
<li><a
href="/contest/1359/status">Статус</a></li>
<li><a
href="/contest/1359/hacks">Взломы</a></li>
<li><a
href="/contest/1359/standings">Положение</a></li>
<li><a
href="/contest/1359/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_1c4161ea25c292facfe47c42c3b9ff50302e7c9f">
<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 href="https://codeforces.com/problemset/problem/1/A">задачи 1A</a>. Сегодня ее покрытие наконец-то заменят.</p><p>Площадь все еще является прямоугольником $$$n \times m$$$ метров. Однако, рисунок на ней будет более сложным в этот раз. Пусть $$$a_{i,j}$$$ будет $$$j$$$-й ячейкой в $$$i$$$-м ряду покрытия плитками.</p><p>Вам задан рисунок покрытия:</p><ul> <li> если $$$a_{i,j} = $$$ «<span class="tex-font-style-tt">*</span>», то $$$j$$$-я ячейка в $$$i$$$-м ряду должна быть <span class="tex-font-style-bf">черной</span>; </li><li> если $$$a_{i,j} = $$$ «<span class="tex-font-style-tt">.</span>», то $$$j$$$-я ячейка в $$$i$$$-м ряду должна быть <span class="tex-font-style-bf">белой</span>. </li></ul><p>Черные ячейки уже покрыты. Вам же необходимо покрыть белые ячейки. Существует две опции плиток:</p><ul> <li> $$$1 \times 1$$$ плитки — каждая плитка стоит $$$x$$$ бурлей и покрывает ровно $$$1$$$ ячейку; </li><li> $$$1 \times 2$$$ плитки — каждая плитка стоит $$$y$$$ бурлей и покрывает ровно $$$2$$$ соседние ячейки в <span class="tex-font-style-bf">одном ряду</span>. <span class="tex-font-style-bf">Обратите внимание, что нельзя вращать эти плитки или резать их на плитки $$$1 \times 1$$$.</span> </li></ul><p><span class="tex-font-style-bf">Вам необходимо покрыть все белые ячейки, никакие две плитки не должны накладываться друг на друга и никакие черные ячейки не должны быть накрыты плитками</span>.</p><p>Чему равна наименьшая суммарная цена плиток, которые могут покрыть все белые клетки?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 500$$$) — количество наборов входных данных. Затем следует описание $$$t$$$ наборов.</p><p>В первой строке каждого набора входных данных записаны четыре целых числа $$$n$$$, $$$m$$$, $$$x$$$ и $$$y$$$ ($$$1 \le n \le 100$$$; $$$1 \le m \le 1000$$$; $$$1 \le x, y \le 1000$$$) — размеры Театральной площади, цена плитки $$$1 \times 1$$$ и цена плитки $$$1 \times 2$$$.</p><p>В каждой из следующих $$$n$$$ строк записаны по $$$m$$$ символов. $$$j$$$-й символ в $$$i$$$-й строке — это $$$a_{i,j}$$$. Если $$$a_{i,j} = $$$ «<span class="tex-font-style-tt">*</span>», то $$$j$$$-я ячейка в $$$i$$$-м ряду должна быть <span class="tex-font-style-bf">черной</span>, а если $$$a_{i,j} = $$$ «<span class="tex-font-style-tt">.</span>», то $$$j$$$-я ячейка в $$$i$$$-м ряду должна быть <span class="tex-font-style-bf">белой</span>.</p><p><span class="tex-font-style-bf">Гарантируется, что сумма $$$n \times m$$$ по всем наборам входных данных не превышает $$$10^5$$$</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число — наименьшая суммарная цена плиток, которые могут покрыть все белые клетки, в бурлях.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
1 1 10 1
.
1 2 10 1
..
2 1 10 1
.
.
3 3 3 7
..*
*..
.*.
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
1
20
18
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных необходимо использовать одну плитку $$$1 \times 1$$$, несмотря на то, что плитка $$$1 \times 2$$$ дешевле. Поэтому суммарная цена равна $$$10$$$ бурлей.</p><p>Во втором наборе можно использовать либо две плитки $$$1 \times 1$$$ и потратить $$$20$$$ бурлей, либо одну плитку $$$1 \times 2$$$ плитку и потратить $$$1$$$ бурль. Второй вариант дешевле, поэтому ответ равен $$$1$$$.</p><p>Третий набор показывает, что нельзя поворачивать плитки $$$1 \times 2$$$. Приходится использовать две плитки $$$1 \times 1$$$ с суммарной ценой $$$20$$$.</p><p>В четвертом наборе самый дешевый способ — это использовать $$$1 \times 1$$$ плитки повсюду. Итоговая цена — $$$6 \cdot 3 = 18$$$.</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:04: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:'8124a1a8595316a7',t:'MTY5NjY2NTg0Ny4yMjkwMDA='};_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", "\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", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1000"] | ||
1359C | 1359 | C | ru | C. Смешиваем воду | <div class="problem-statement"><div class="header"><div class="title">C. Смешиваем воду</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть два бесконечных источника воды:</p><ul> <li> горячая вода температуры $$$h$$$; </li><li> холодная вода температуры $$$c$$$ ($$$c < h$$$). </li></ul><p>Вы совершаете следующую чередующуюся последовательность действий:</p><ol> <li> набрать <span class="tex-font-style-bf">одну</span> кружку <span class="tex-font-style-bf">горячей</span> воды и вылить ее в бесконечно глубокую бочку; </li><li> набрать <span class="tex-font-style-bf">одну</span> кружку <span class="tex-font-style-bf">холодной</span> воды и вылить ее в бесконечно глубокую бочку; </li><li> набрать <span class="tex-font-style-bf">одну</span> кружку <span class="tex-font-style-bf">горячей</span> воды $$$\dots$$$ </li><li> и так далее $$$\dots$$$ </li></ol><p><span class="tex-font-style-bf">Обратите внимание, что вы всегда начинаете с кружки горячей воды</span>.</p><p>Бочка изначально пустая. Необходимо налить <span class="tex-font-style-bf">хотя бы одну кружку</span> в бочку. Температура воды в бочке равна средней температуре вылитых кружек.</p><p>Вы хотите получить воду температуры как можно ближе к $$$t$$$. То есть если температура воды в бочке равна $$$t_b$$$, то <span class="tex-font-style-bf">абсолютная разность</span> $$$t_b$$$ и $$$t$$$ ($$$|t_b - t|$$$) должна быть минимально возможна.</p><p>Сколько кружек необходимо налить в бочку, чтобы температура стала как можно ближе к $$$t$$$? Если существует несколько ответов с минимальной абсолютной разностью, то выведите наименьший из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — количество наборов входных данных.</p><p>В каждой из следующих $$$T$$$ строк записаны по три целых числа $$$h$$$, $$$c$$$ и $$$t$$$ ($$$1 \le c < h \le 10^6$$$; $$$c \le t \le h$$$) — температура горячей воды, температура холодной воды и желаемая температура в бочке.</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
30 10 20
41 15 30
18 13 18
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
7
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных температура после $$$2$$$ налитых кружек: $$$1$$$ горячей и $$$1$$$ холодной — равна $$$20$$$. И это самое близкое возможное значение.</p><p>Во втором наборе температура после $$$7$$$ налитых кружек: $$$4$$$ горячих и $$$3$$$ холодных — примерно $$$29.857$$$. Если наливать больше воды, то температура не станет ближе к $$$t$$$.</p><p>В третьем наборе температура после $$$1$$$ налитой кружки: $$$1$$$ горячей — равна $$$18$$$. Это совпадает с $$$t$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="c3cf21cdabccfbfffa26a89f61fd65cf"/>
<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="3913f22e6d079d2e4a21d513a093e067724a767e"/>
<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='c3cf21cdabccfbfffa26a89f61fd65cf'> </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%2F1359%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='c3cf21cdabccfbfffa26a89f61fd65cf'/>
<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/1359">Educational Codeforces Round 88 (рейтинговый для Див. 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='c3cf21cdabccfbfffa26a89f61fd65cf'/>
<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/1359/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='c3cf21cdabccfbfffa26a89f61fd65cf'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="634674"/>
<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='c3cf21cdabccfbfffa26a89f61fd65cf'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="634674"/>
<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/78016" title="Educational Codeforces Round 88 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10982:10983" 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/78116" title="Разбор Educational Codeforces Round 88" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10993:10994" 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/1359">Задачи</a></li>
<li><a
href="/contest/1359/submit">Отослать</a></li>
<li><a
href="/contest/1359/my">Мои посылки</a></li>
<li><a
href="/contest/1359/status">Статус</a></li>
<li><a
href="/contest/1359/hacks">Взломы</a></li>
<li><a
href="/contest/1359/standings">Положение</a></li>
<li><a
href="/contest/1359/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_025d80038b9e73d7fdec569d21dee734be9084d0">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. Смешиваем воду</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Есть два бесконечных источника воды:</p><ul> <li> горячая вода температуры $$$h$$$; </li><li> холодная вода температуры $$$c$$$ ($$$c < h$$$). </li></ul><p>Вы совершаете следующую чередующуюся последовательность действий:</p><ol> <li> набрать <span class="tex-font-style-bf">одну</span> кружку <span class="tex-font-style-bf">горячей</span> воды и вылить ее в бесконечно глубокую бочку; </li><li> набрать <span class="tex-font-style-bf">одну</span> кружку <span class="tex-font-style-bf">холодной</span> воды и вылить ее в бесконечно глубокую бочку; </li><li> набрать <span class="tex-font-style-bf">одну</span> кружку <span class="tex-font-style-bf">горячей</span> воды $$$\dots$$$ </li><li> и так далее $$$\dots$$$ </li></ol><p><span class="tex-font-style-bf">Обратите внимание, что вы всегда начинаете с кружки горячей воды</span>.</p><p>Бочка изначально пустая. Необходимо налить <span class="tex-font-style-bf">хотя бы одну кружку</span> в бочку. Температура воды в бочке равна средней температуре вылитых кружек.</p><p>Вы хотите получить воду температуры как можно ближе к $$$t$$$. То есть если температура воды в бочке равна $$$t_b$$$, то <span class="tex-font-style-bf">абсолютная разность</span> $$$t_b$$$ и $$$t$$$ ($$$|t_b - t|$$$) должна быть минимально возможна.</p><p>Сколько кружек необходимо налить в бочку, чтобы температура стала как можно ближе к $$$t$$$? Если существует несколько ответов с минимальной абсолютной разностью, то выведите наименьший из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \le T \le 3 \cdot 10^4$$$) — количество наборов входных данных.</p><p>В каждой из следующих $$$T$$$ строк записаны по три целых числа $$$h$$$, $$$c$$$ и $$$t$$$ ($$$1 \le c < h \le 10^6$$$; $$$c \le t \le h$$$) — температура горячей воды, температура холодной воды и желаемая температура в бочке.</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
30 10 20
41 15 30
18 13 18
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
7
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных температура после $$$2$$$ налитых кружек: $$$1$$$ горячей и $$$1$$$ холодной — равна $$$20$$$. И это самое близкое возможное значение.</p><p>Во втором наборе температура после $$$7$$$ налитых кружек: $$$4$$$ горячих и $$$3$$$ холодных — примерно $$$29.857$$$. Если наливать больше воды, то температура не станет ближе к $$$t$$$.</p><p>В третьем наборе температура после $$$1$$$ налитой кружки: $$$1$$$ горячей — равна $$$18$$$. Это совпадает с $$$t$$$.</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:04: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:'8124a1b1f8d075a3',t:'MTY5NjY2NTg0OC45NDAwMDA='};_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", "*1700"] | ||
1359D | 1359 | 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>Алиса и Боб играют в очередную игру с карточками. На этот раз правила следующие. Перед ними в ряд лежат $$$n$$$ карточек. У $$$i$$$-й карточки значение $$$a_i$$$.</p><p>Сначала Алиса выбирает непустой последовательный отрезок карточек $$$[l; r]$$$ ($$$l \le r$$$). Затем Боб удаляет одну карточку $$$j$$$ из этого отрезка $$$(l \le j \le r)$$$. Счет игры равен сумме значений оставшихся на отрезке карточек $$$(a_l + a_{l + 1} + \dots + a_{j - 1} + a_{j + 1} + \dots + a_{r - 1} + a_r)$$$. В частности, если Алиса выбрала отрезок с ровно одним элементом, то после того, как Боб удалит единственную карточку, счет будет равен $$$0$$$.</p><p>Алиса хочет сделать счет как можно больше. Боб удаляет такую карточку, чтобы счет стал как можно меньше.</p><p>Какой отрезок должна выбрать Алиса, чтобы счет был максимально возможным? Выведите максимальный счет.</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, \dots, a_n$$$ ($$$-30 \le a_i \le 30$$$) — значения на карточках.</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
5 -2 10 -1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
5 2 5 3 -30 -30 6 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
-10 6 -15
</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;5]$$$ — весь ряд карточек. Боб удаляет карточку $$$3$$$ со значением $$$10$$$ из этого отрезка. Поэтому итоговый счет равен $$$5 + (-2) + (-1) + 4 = 6$$$.</p><p>Во втором примере Алиса выбирает отрезок $$$[1;4]$$$, и так как Боб удаляет либо карточку $$$1$$$, либо $$$3$$$, со значением $$$5$$$, то ответ становится $$$5 + 2 + 3 = 10$$$.</p><p>В третьем примере Алиса может выбрать любой из отрезков длины $$$1$$$: $$$[1;1]$$$, $$$[2;2]$$$ или $$$[3;3]$$$. Боб удаляет единственную карточку, поэтому счет равен $$$0$$$. Если Алиса выберет любой другой отрезок, то ответ будет меньше $$$0$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="297fdaf98960fed1d7f9054724a8488a"/>
<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="3913f22e6d079d2e4a21d513a093e067724a767e"/>
<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='297fdaf98960fed1d7f9054724a8488a'> </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%2F1359%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='297fdaf98960fed1d7f9054724a8488a'/>
<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/1359">Educational Codeforces Round 88 (рейтинговый для Див. 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='297fdaf98960fed1d7f9054724a8488a'/>
<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/1359/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='297fdaf98960fed1d7f9054724a8488a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="634675"/>
<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='297fdaf98960fed1d7f9054724a8488a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="634675"/>
<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/78016" title="Educational Codeforces Round 88 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10982:10983" 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/78116" title="Разбор Educational Codeforces Round 88" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10993:10994" 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/1359">Задачи</a></li>
<li><a
href="/contest/1359/submit">Отослать</a></li>
<li><a
href="/contest/1359/my">Мои посылки</a></li>
<li><a
href="/contest/1359/status">Статус</a></li>
<li><a
href="/contest/1359/hacks">Взломы</a></li>
<li><a
href="/contest/1359/standings">Положение</a></li>
<li><a
href="/contest/1359/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_97a5ba15f2f12400592344f93e40b34da0b1b506">
<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>Алиса и Боб играют в очередную игру с карточками. На этот раз правила следующие. Перед ними в ряд лежат $$$n$$$ карточек. У $$$i$$$-й карточки значение $$$a_i$$$.</p><p>Сначала Алиса выбирает непустой последовательный отрезок карточек $$$[l; r]$$$ ($$$l \le r$$$). Затем Боб удаляет одну карточку $$$j$$$ из этого отрезка $$$(l \le j \le r)$$$. Счет игры равен сумме значений оставшихся на отрезке карточек $$$(a_l + a_{l + 1} + \dots + a_{j - 1} + a_{j + 1} + \dots + a_{r - 1} + a_r)$$$. В частности, если Алиса выбрала отрезок с ровно одним элементом, то после того, как Боб удалит единственную карточку, счет будет равен $$$0$$$.</p><p>Алиса хочет сделать счет как можно больше. Боб удаляет такую карточку, чтобы счет стал как можно меньше.</p><p>Какой отрезок должна выбрать Алиса, чтобы счет был максимально возможным? Выведите максимальный счет.</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, \dots, a_n$$$ ($$$-30 \le a_i \le 30$$$) — значения на карточках.</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
5 -2 10 -1 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
5 2 5 3 -30 -30 6 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
10
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
-10 6 -15
</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;5]$$$ — весь ряд карточек. Боб удаляет карточку $$$3$$$ со значением $$$10$$$ из этого отрезка. Поэтому итоговый счет равен $$$5 + (-2) + (-1) + 4 = 6$$$.</p><p>Во втором примере Алиса выбирает отрезок $$$[1;4]$$$, и так как Боб удаляет либо карточку $$$1$$$, либо $$$3$$$, со значением $$$5$$$, то ответ становится $$$5 + 2 + 3 = 10$$$.</p><p>В третьем примере Алиса может выбрать любой из отрезков длины $$$1$$$: $$$[1;1]$$$, $$$[2;2]$$$ или $$$[3;3]$$$. Боб удаляет единственную карточку, поэтому счет равен $$$0$$$. Если Алиса выберет любой другой отрезок, то ответ будет меньше $$$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:04: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:'8124a1bb8a9b9d70',t:'MTY5NjY2NTg1MC4zMjMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\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", "\u0434\u043f", "\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", "*2000"] | ||
1359E | 1359 | 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>Обозначим за $$$x \bmod y$$$ остаток от целочисленного деления $$$x$$$ на $$$y$$$ (оператор $$$\%$$$ в C++ или Java, <span class="tex-font-style-tt">mod</span> в Pascal).</p><p>Назовем массив целых чисел $$$[a_1, a_2, \dots, a_k]$$$ <span class="tex-font-style-it">стабильным</span>, если для каждой перестановки $$$p$$$ целых чисел от $$$1$$$ до $$$k$$$, и для каждого неотрицательного целого числа $$$x$$$ выполняется следующее условие:</p><center> $$$ (((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k = (((x \bmod a_{p_1}) \bmod a_{p_2}) \dots \bmod a_{p_{k - 1}}) \bmod a_{p_k} $$$ </center><p>Другими словами, для каждого неотрицательного целого $$$x$$$ значение $$$(((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k$$$ не зависит от порядка элементов в массиве $$$a$$$.</p><p>Для двух заданных целых чисел $$$n$$$ и $$$k$$$ посчитайте количество <span class="tex-font-style-it">стабильных</span> массивов $$$[a_1, a_2, \dots, a_k]$$$, в которых $$$1 \le a_1 < a_2 < \dots < a_k \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке заданы два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество <span class="tex-font-style-it">стабильных</span> массивов $$$[a_1, a_2, \dots, a_k]$$$, в которых $$$1 \le a_1 < a_2 < \dots < a_k \le n$$$. Так как ответ может быть очень большим, выведите его по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
16
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1337 42
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
95147305
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
500000 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
500000
</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="d96b27cbfbc64f2ddb71f8ac78c8132f"/>
<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="3913f22e6d079d2e4a21d513a093e067724a767e"/>
<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='d96b27cbfbc64f2ddb71f8ac78c8132f'> </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%2F1359%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='d96b27cbfbc64f2ddb71f8ac78c8132f'/>
<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/1359">Educational Codeforces Round 88 (рейтинговый для Див. 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='d96b27cbfbc64f2ddb71f8ac78c8132f'/>
<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/1359/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='d96b27cbfbc64f2ddb71f8ac78c8132f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="634676"/>
<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='d96b27cbfbc64f2ddb71f8ac78c8132f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="634676"/>
<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/78016" title="Educational Codeforces Round 88 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10982:10983" 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/78116" title="Разбор Educational Codeforces Round 88" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10993:10994" 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/1359">Задачи</a></li>
<li><a
href="/contest/1359/submit">Отослать</a></li>
<li><a
href="/contest/1359/my">Мои посылки</a></li>
<li><a
href="/contest/1359/status">Статус</a></li>
<li><a
href="/contest/1359/hacks">Взломы</a></li>
<li><a
href="/contest/1359/standings">Положение</a></li>
<li><a
href="/contest/1359/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_4d4b6e45f200efe5e96f2c6f42eb96f2d6567995">
<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>Обозначим за $$$x \bmod y$$$ остаток от целочисленного деления $$$x$$$ на $$$y$$$ (оператор $$$\%$$$ в C++ или Java, <span class="tex-font-style-tt">mod</span> в Pascal).</p><p>Назовем массив целых чисел $$$[a_1, a_2, \dots, a_k]$$$ <span class="tex-font-style-it">стабильным</span>, если для каждой перестановки $$$p$$$ целых чисел от $$$1$$$ до $$$k$$$, и для каждого неотрицательного целого числа $$$x$$$ выполняется следующее условие:</p><center> $$$ (((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k = (((x \bmod a_{p_1}) \bmod a_{p_2}) \dots \bmod a_{p_{k - 1}}) \bmod a_{p_k} $$$ </center><p>Другими словами, для каждого неотрицательного целого $$$x$$$ значение $$$(((x \bmod a_1) \bmod a_2) \dots \bmod a_{k - 1}) \bmod a_k$$$ не зависит от порядка элементов в массиве $$$a$$$.</p><p>Для двух заданных целых чисел $$$n$$$ и $$$k$$$ посчитайте количество <span class="tex-font-style-it">стабильных</span> массивов $$$[a_1, a_2, \dots, a_k]$$$, в которых $$$1 \le a_1 < a_2 < \dots < a_k \le n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке заданы два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 5 \cdot 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество <span class="tex-font-style-it">стабильных</span> массивов $$$[a_1, a_2, \dots, a_k]$$$, в которых $$$1 \le a_1 < a_2 < \dots < a_k \le n$$$. Так как ответ может быть очень большим, выведите его по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
16
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1337 42
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
95147305
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
500000 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
500000
</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:04: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:'8124a1c43b5c9d90',t:'MTY5NjY2NTg1MS42NjAwMDA='};_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.", "\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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2000"] | ||
1359F | 1359 | F | ru | F. Шоу взрывов на радиоуправлении | <div class="problem-statement"><div class="header"><div class="title">F. Шоу взрывов на радиоуправлении</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>6 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Знаете, в наше время довольно сложно организовать шоу с большим количеством участников и зрителей в одном месте. Тем не менее, вы не отказываетесь от своей мечты провести шоу со взрывами машин! Вы решили заменить настоящие машины радиоуправляемыми, назвать мероприятия «Шоу взрывов на радиоуправлении» и транслировать все онлайн.</p><p>Для подготовки вы нашли арену — бесконечную 2D-сетку. Вы также закупили $$$n$$$ радиоуправляемых машинок и расставили их по арене. К сожалению, эти машинки могут ехать только вперед, без возможности поворотов налево, направо или разворотов. Более того, вы направили машинки туда, куда хотите, чтобы они поехали.</p><p>Формально, для каждой машинки $$$i$$$ ($$$1 \le i \le n$$$) вы зафиксировали ее начальную позицию ($$$x_i, y_i$$$) и вектор направление ($$$dx_i, dy_i$$$). Более того, у каждой машинки есть константная скорость $$$s_i$$$ единиц в секунду. То есть после запуска машинка $$$i$$$ двигается из ($$$x_i, y_i$$$) в направлении ($$$dx_i, dy_i$$$) с константной скоростью $$$s_i$$$.</p><p>Цель вашего шоу — столкнуть две машинки как можно скорее! Вы обратили внимание, что если запускать все машинки в самом начале шоу, то довольно часто столкновений не происходит вообще. Поэтому вы решили запустить $$$i$$$-ю машинку в некоторый момент $$$t_i$$$. <span class="tex-font-style-bf">Вы еще не выбрали $$$t_i$$$, это еще надо решить</span>. Обратите внимание, что $$$t_i$$$ не обязательно должно быть целым, и допустимо, чтобы $$$t_i$$$ совпадало с $$$t_j$$$ для любых $$$i, j$$$.</p><p>Шоу начинается в момент времени $$$0$$$. Шоу заканчивается, когда какие-нибудь две машинки $$$i$$$ и $$$j$$$ ($$$i \ne j$$$) сталкиваются (то есть оказываются в одной точке в одно и то же время). Длительность шоу равна времени между началом и концом.</p><p>Какое самое быстрое столкновение вы можете организовать, выбрав все $$$t_i$$$? Если возможно организовать столкновение, тогда выведите минимальную возможную длительность шоу. Иначе сообщите, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 25000$$$) — количество машинок.</p><p>В каждой из следующих $$$n$$$ строк записаны по пять целых чисел $$$x_i$$$, $$$y_i$$$, $$$dx_i$$$, $$$dy_i$$$, $$$s_i$$$ ($$$-10^3 \le x_i, y_i \le 10^3$$$; $$$1 \le |dx_i| \le 10^3$$$; $$$1 \le |dy_i| \le 10^3$$$; $$$1 \le s_i \le 10^3$$$) — начальная позиция $$$i$$$-й машинки, ее вектор направления и ее скорость, соответственно.</p><p><span class="tex-font-style-bf">Гарантируется, что все машинки начинают в различных позициях (то есть $$$(x_i, y_i) \neq (x_j, y_j)$$$ для $$$i \neq j$$$).</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите наименьшую возможную длительность шоу, если возможно организовать столкновение, выбрав все $$$t_i$$$. Иначе, выведите «<span class="tex-font-style-tt">No show :(</span>».</p><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
3 -1 -1 1 2
2 3 -3 -2 10
-4 2 1 -2 1
-2 -2 -1 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0.585902082262898
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
-1 1 -1 1 200
1 1 1 5 200
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No show :(
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка для первого примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/16d5fda96c67dc81d6c6dc1fd5bf565df8b977d7.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Самое раннее возможное столкновение произойдет с машинками $$$2$$$ и $$$4$$$. Запустим машинку $$$2$$$ в $$$0$$$, машинку $$$4$$$ примерно в $$$0.096762$$$ и машинки $$$1$$$ и $$$3$$$ когда угодно. Тогда машинки $$$2$$$ и $$$4$$$ столкнутся примерно в $$$0.585902$$$. Тогда вот как поле будет выглядеть в момент столкновения:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9f49bf567d0bcdd60779341a6bf1da70d18c03cb.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Вот картинка для второго примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f0eac2dc847f0751a4ef51982a70780b0311fdc7.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="457ebdb2ff5c82a7c9d175c6756ce0c0"/>
<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="3913f22e6d079d2e4a21d513a093e067724a767e"/>
<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='457ebdb2ff5c82a7c9d175c6756ce0c0'> </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%2F1359%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='457ebdb2ff5c82a7c9d175c6756ce0c0'/>
<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/1359">Educational Codeforces Round 88 (рейтинговый для Див. 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='457ebdb2ff5c82a7c9d175c6756ce0c0'/>
<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/1359/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Геометрия">
геометрия
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2900
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='457ebdb2ff5c82a7c9d175c6756ce0c0'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="634677"/>
<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='457ebdb2ff5c82a7c9d175c6756ce0c0'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="634677"/>
<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/78016" title="Educational Codeforces Round 88 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10982:10983" 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/78116" title="Разбор Educational Codeforces Round 88" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10993:10994" 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/1359">Задачи</a></li>
<li><a
href="/contest/1359/submit">Отослать</a></li>
<li><a
href="/contest/1359/my">Мои посылки</a></li>
<li><a
href="/contest/1359/status">Статус</a></li>
<li><a
href="/contest/1359/hacks">Взломы</a></li>
<li><a
href="/contest/1359/standings">Положение</a></li>
<li><a
href="/contest/1359/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_ed249e9b7e6d3578d4a3b73137a07ed30a66b08f">
<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>6 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Знаете, в наше время довольно сложно организовать шоу с большим количеством участников и зрителей в одном месте. Тем не менее, вы не отказываетесь от своей мечты провести шоу со взрывами машин! Вы решили заменить настоящие машины радиоуправляемыми, назвать мероприятия «Шоу взрывов на радиоуправлении» и транслировать все онлайн.</p><p>Для подготовки вы нашли арену — бесконечную 2D-сетку. Вы также закупили $$$n$$$ радиоуправляемых машинок и расставили их по арене. К сожалению, эти машинки могут ехать только вперед, без возможности поворотов налево, направо или разворотов. Более того, вы направили машинки туда, куда хотите, чтобы они поехали.</p><p>Формально, для каждой машинки $$$i$$$ ($$$1 \le i \le n$$$) вы зафиксировали ее начальную позицию ($$$x_i, y_i$$$) и вектор направление ($$$dx_i, dy_i$$$). Более того, у каждой машинки есть константная скорость $$$s_i$$$ единиц в секунду. То есть после запуска машинка $$$i$$$ двигается из ($$$x_i, y_i$$$) в направлении ($$$dx_i, dy_i$$$) с константной скоростью $$$s_i$$$.</p><p>Цель вашего шоу — столкнуть две машинки как можно скорее! Вы обратили внимание, что если запускать все машинки в самом начале шоу, то довольно часто столкновений не происходит вообще. Поэтому вы решили запустить $$$i$$$-ю машинку в некоторый момент $$$t_i$$$. <span class="tex-font-style-bf">Вы еще не выбрали $$$t_i$$$, это еще надо решить</span>. Обратите внимание, что $$$t_i$$$ не обязательно должно быть целым, и допустимо, чтобы $$$t_i$$$ совпадало с $$$t_j$$$ для любых $$$i, j$$$.</p><p>Шоу начинается в момент времени $$$0$$$. Шоу заканчивается, когда какие-нибудь две машинки $$$i$$$ и $$$j$$$ ($$$i \ne j$$$) сталкиваются (то есть оказываются в одной точке в одно и то же время). Длительность шоу равна времени между началом и концом.</p><p>Какое самое быстрое столкновение вы можете организовать, выбрав все $$$t_i$$$? Если возможно организовать столкновение, тогда выведите минимальную возможную длительность шоу. Иначе сообщите, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 25000$$$) — количество машинок.</p><p>В каждой из следующих $$$n$$$ строк записаны по пять целых чисел $$$x_i$$$, $$$y_i$$$, $$$dx_i$$$, $$$dy_i$$$, $$$s_i$$$ ($$$-10^3 \le x_i, y_i \le 10^3$$$; $$$1 \le |dx_i| \le 10^3$$$; $$$1 \le |dy_i| \le 10^3$$$; $$$1 \le s_i \le 10^3$$$) — начальная позиция $$$i$$$-й машинки, ее вектор направления и ее скорость, соответственно.</p><p><span class="tex-font-style-bf">Гарантируется, что все машинки начинают в различных позициях (то есть $$$(x_i, y_i) \neq (x_j, y_j)$$$ для $$$i \neq j$$$).</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите наименьшую возможную длительность шоу, если возможно организовать столкновение, выбрав все $$$t_i$$$. Иначе, выведите «<span class="tex-font-style-tt">No show :(</span>».</p><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
3 -1 -1 1 2
2 3 -3 -2 10
-4 2 1 -2 1
-2 -2 -1 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0.585902082262898
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
-1 1 -1 1 200
1 1 1 5 200
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
No show :(
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка для первого примера: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/16d5fda96c67dc81d6c6dc1fd5bf565df8b977d7.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Самое раннее возможное столкновение произойдет с машинками $$$2$$$ и $$$4$$$. Запустим машинку $$$2$$$ в $$$0$$$, машинку $$$4$$$ примерно в $$$0.096762$$$ и машинки $$$1$$$ и $$$3$$$ когда угодно. Тогда машинки $$$2$$$ и $$$4$$$ столкнутся примерно в $$$0.585902$$$. Тогда вот как поле будет выглядеть в момент столкновения:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/9f49bf567d0bcdd60779341a6bf1da70d18c03cb.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Вот картинка для второго примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f0eac2dc847f0751a4ef51982a70780b0311fdc7.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=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:04: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:'8124a1ccae897a7d',t:'MTY5NjY2NTg1My4wNzIwMDA='};_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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2900"] | ||
1360A | 1360 | A | ru | A. Минимальный квадрат | <div class="problem-statement"><div class="header"><div class="title">A. Минимальный квадрат</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Найдите минимальную площадь <span class="tex-font-style-bf">квадратного</span> участка земли, на котором можно разместить два одинаковых прямоугольных дома размерами $$$a \times b$$$. Стороны домов должны быть параллельны сторонам искомого квадратного участка.</p><p>Формально:</p><ul> <li> Вам даны два одинаковых прямоугольника с длинами сторон $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le 100$$$) — целые положительные числа (вам заданы просто размеры, но <span class="tex-font-style-bf">не</span> их положения). </li><li> Найдите квадрат минимальной площади, который содержит в себе оба заданных прямоугольника. Прямоугольники можно поворачивать (оба или любой один), перемещать, но стороны прямоугольников должны быть параллельны сторонам искомого квадрата. </li></ul><p>Два прямоугольника могут произвольным образом касаться друг друга (по стороне или углу), но не могут пересекаться. Также прямоугольники могут касаться сторон квадрата, но обязаны полностью находиться внутри него. Поворачивать прямоугольники можно. Изучите примеры для лучшего понимания.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1e598f03ef46e0e02e952a4624168bc6f2799a22.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">На картинке изображен квадрат, который содержит в себе красный и зеленый прямоугольники.</span> </center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10\,000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор представляет собой строку, в которой записано два целых числа $$$a$$$, $$$b$$$ ($$$1 \le a, b \le 100$$$) — стороны прямоугольников.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы тестовых данных. Каждый ответ должен содержать одно целое число — минимальную площадь квадрата, содержащего два прямоугольника $$$a \times b$$$.</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 2
4 2
1 1
3 1
4 7
1 3
7 4
100 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
16
16
4
9
64
9
64
40000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже изображены ответы для первых двух наборов тестовых данных: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1e598f03ef46e0e02e952a4624168bc6f2799a22.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center> <center> <img class="tex-graphics" src="https://espresso.codeforces.com/c543a559b4f04d83008aa7bcd6d11c643dba8b4d.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="d2b104b6434f85ed4f2a2f41bd524c6a"/>
<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="d404244f00d9c513cd4a88bd3efe601bfad1b606"/>
<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='d2b104b6434f85ed4f2a2f41bd524c6a'> </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%2F1360%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='d2b104b6434f85ed4f2a2f41bd524c6a'/>
<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/1360">Codeforces Round 644 (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='d2b104b6434f85ed4f2a2f41bd524c6a'/>
<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/1360/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='d2b104b6434f85ed4f2a2f41bd524c6a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="629821"/>
<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='d2b104b6434f85ed4f2a2f41bd524c6a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="629821"/>
<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/77796" title="Codeforces Round #644 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10949:10950" 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/77846" title="Codeforces Round #644 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11453:11454" 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/1360">Задачи</a></li>
<li><a
href="/contest/1360/submit">Отослать</a></li>
<li><a
href="/contest/1360/my">Мои посылки</a></li>
<li><a
href="/contest/1360/status">Статус</a></li>
<li><a
href="/contest/1360/hacks">Взломы</a></li>
<li><a
href="/contest/1360/standings">Положение</a></li>
<li><a
href="/contest/1360/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_18468f1f9badb5e6d7fd13d800740d8d66ce9093">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Минимальный квадрат</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Найдите минимальную площадь <span class="tex-font-style-bf">квадратного</span> участка земли, на котором можно разместить два одинаковых прямоугольных дома размерами $$$a \times b$$$. Стороны домов должны быть параллельны сторонам искомого квадратного участка.</p><p>Формально:</p><ul> <li> Вам даны два одинаковых прямоугольника с длинами сторон $$$a$$$ и $$$b$$$ ($$$1 \le a, b \le 100$$$) — целые положительные числа (вам заданы просто размеры, но <span class="tex-font-style-bf">не</span> их положения). </li><li> Найдите квадрат минимальной площади, который содержит в себе оба заданных прямоугольника. Прямоугольники можно поворачивать (оба или любой один), перемещать, но стороны прямоугольников должны быть параллельны сторонам искомого квадрата. </li></ul><p>Два прямоугольника могут произвольным образом касаться друг друга (по стороне или углу), но не могут пересекаться. Также прямоугольники могут касаться сторон квадрата, но обязаны полностью находиться внутри него. Поворачивать прямоугольники можно. Изучите примеры для лучшего понимания.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1e598f03ef46e0e02e952a4624168bc6f2799a22.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">На картинке изображен квадрат, который содержит в себе красный и зеленый прямоугольники.</span> </center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10\,000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор представляет собой строку, в которой записано два целых числа $$$a$$$, $$$b$$$ ($$$1 \le a, b \le 100$$$) — стороны прямоугольников.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы тестовых данных. Каждый ответ должен содержать одно целое число — минимальную площадь квадрата, содержащего два прямоугольника $$$a \times b$$$.</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 2
4 2
1 1
3 1
4 7
1 3
7 4
100 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
16
16
4
9
64
9
64
40000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже изображены ответы для первых двух наборов тестовых данных: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1e598f03ef46e0e02e952a4624168bc6f2799a22.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center> <center> <img class="tex-graphics" src="https://espresso.codeforces.com/c543a559b4f04d83008aa7bcd6d11c643dba8b4d.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:04: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:'8124a1d56f1c9d3f',t:'MTY5NjY2NTg1NC41MjIwMDA='};_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"] | ||
1360B | 1360 | 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>Перед вами стоит $$$n$$$ спортсменов. Спортсмены пронумерованы от $$$1$$$ до $$$n$$$ слева направо. Про каждого спортсмена вы знаете его силу — спортсмен с номером $$$i$$$ имеет силу $$$s_i$$$.</p><p>Вы хотите разделить всех спортсменов на две команды. В каждой команде должен быть хотя бы один спортсмен, и каждый спортсмен должен быть ровно в одной команде.</p><p>Вы хотите, чтобы самый сильный спортсмен из первой команды по силе как можно меньше отличался от самого слабого спортсмена из второй команды. Формально, вы хотите разделить спортсменов на две команды $$$A$$$ и $$$B$$$ так, чтобы величина $$$|\max(A) - \min(B)|$$$ была как можно меньше, где $$$\max(A)$$$ — максимальная сила спортсмена из команды $$$A$$$, а $$$\min(B)$$$ — минимальная сила спортсмена из команды $$$B$$$.</p><p>Например, если $$$n=5$$$ и силы спортсменов равны $$$s=[3, 1, 2, 6, 4]$$$, то одно из возможных разделений на команды имеет вид: </p><ul> <li> первая команда: $$$A = [1, 2, 4]$$$, </li><li> вторая команда: $$$B = [3, 6]$$$. </li></ul><p>В этом случае величина $$$|\max(A) - \min(B)|$$$ будет равна $$$|4-3|=1$$$. Этот пример иллюстрирует один из способов оптимального разбиения на две команды.</p><p>Выведите минимальное значение $$$|\max(A) - \min(B)|$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее записаны $$$t$$$ наборов тестовых данных.</p><p>Каждый набор состоит из двух строк. В первой строке содержится целое положительное число $$$n$$$ ($$$2 \le n \le 50$$$) — количество спортсменов. </p><p>В следующей строке содержится $$$n$$$ положительных целых чисел $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 1000$$$), где $$$s_i$$$ — это сила $$$i$$$-го спортсмена. Обратите внимание, что среди элементов массива $$$s$$$ могут быть равные значения.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число — минимальное значение величины $$$|\max(A) - \min(B)|$$$ при оптимальном разбиении всех спортсменов на команды. Каждый из спортсменов должен оказаться членом ровно одной из двух команд.</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
3 1 2 6 4
6
2 1 3 2 4 3
4
7 9 3 1
2
1 1000
3
100 150 200
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
0
2
999
50
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных разобран в условии. Во втором наборе одно из оптимальных разбиений имеет вид $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, поэтому ответ равен $$$|2-2|=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="0d51c49c4a069f25d512a9378ff169d7"/>
<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="d404244f00d9c513cd4a88bd3efe601bfad1b606"/>
<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='0d51c49c4a069f25d512a9378ff169d7'> </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%2F1360%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='0d51c49c4a069f25d512a9378ff169d7'/>
<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/1360">Codeforces Round 644 (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='0d51c49c4a069f25d512a9378ff169d7'/>
<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/1360/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='0d51c49c4a069f25d512a9378ff169d7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="629822"/>
<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='0d51c49c4a069f25d512a9378ff169d7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="629822"/>
<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/77796" title="Codeforces Round #644 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10949:10950" 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/77846" title="Codeforces Round #644 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11453:11454" 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/1360">Задачи</a></li>
<li><a
href="/contest/1360/submit">Отослать</a></li>
<li><a
href="/contest/1360/my">Мои посылки</a></li>
<li><a
href="/contest/1360/status">Статус</a></li>
<li><a
href="/contest/1360/hacks">Взломы</a></li>
<li><a
href="/contest/1360/standings">Положение</a></li>
<li><a
href="/contest/1360/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_299aec498b3dff82d32ecb9dd3a57174c122535c">
<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>Перед вами стоит $$$n$$$ спортсменов. Спортсмены пронумерованы от $$$1$$$ до $$$n$$$ слева направо. Про каждого спортсмена вы знаете его силу — спортсмен с номером $$$i$$$ имеет силу $$$s_i$$$.</p><p>Вы хотите разделить всех спортсменов на две команды. В каждой команде должен быть хотя бы один спортсмен, и каждый спортсмен должен быть ровно в одной команде.</p><p>Вы хотите, чтобы самый сильный спортсмен из первой команды по силе как можно меньше отличался от самого слабого спортсмена из второй команды. Формально, вы хотите разделить спортсменов на две команды $$$A$$$ и $$$B$$$ так, чтобы величина $$$|\max(A) - \min(B)|$$$ была как можно меньше, где $$$\max(A)$$$ — максимальная сила спортсмена из команды $$$A$$$, а $$$\min(B)$$$ — минимальная сила спортсмена из команды $$$B$$$.</p><p>Например, если $$$n=5$$$ и силы спортсменов равны $$$s=[3, 1, 2, 6, 4]$$$, то одно из возможных разделений на команды имеет вид: </p><ul> <li> первая команда: $$$A = [1, 2, 4]$$$, </li><li> вторая команда: $$$B = [3, 6]$$$. </li></ul><p>В этом случае величина $$$|\max(A) - \min(B)|$$$ будет равна $$$|4-3|=1$$$. Этот пример иллюстрирует один из способов оптимального разбиения на две команды.</p><p>Выведите минимальное значение $$$|\max(A) - \min(B)|$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее записаны $$$t$$$ наборов тестовых данных.</p><p>Каждый набор состоит из двух строк. В первой строке содержится целое положительное число $$$n$$$ ($$$2 \le n \le 50$$$) — количество спортсменов. </p><p>В следующей строке содержится $$$n$$$ положительных целых чисел $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 1000$$$), где $$$s_i$$$ — это сила $$$i$$$-го спортсмена. Обратите внимание, что среди элементов массива $$$s$$$ могут быть равные значения.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число — минимальное значение величины $$$|\max(A) - \min(B)|$$$ при оптимальном разбиении всех спортсменов на команды. Каждый из спортсменов должен оказаться членом ровно одной из двух команд.</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
3 1 2 6 4
6
2 1 3 2 4 3
4
7 9 3 1
2
1 1000
3
100 150 200
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
0
2
999
50
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных разобран в условии. Во втором наборе одно из оптимальных разбиений имеет вид $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, поэтому ответ равен $$$|2-2|=0$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=B]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04: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:'8124a1de59931654',t:'MTY5NjY2NTg1NS44NjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*800"] | ||
1360C | 1360 | 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$$$ и $$$y$$$ <span class="tex-font-style-it">похожими</span>, если они имеют одинаковую четность (одинаковый остаток при делении на $$$2$$$), или если $$$|x-y|=1$$$. Например, в каждой из пар $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$ числа похожи между собой, а в парах $$$(1, 4)$$$, $$$(3, 12)$$$ — нет.</p><p>Вам дан массив $$$a$$$ из $$$n$$$ (число $$$n$$$ четно) целых положительных чисел. Проверьте, существует ли такое разбиение массива на пары, что каждый элемент массива принадлежит ровно одной паре, и в каждой паре числа похожи между собой.</p><p>Например для массива $$$a = [11, 14, 16, 12]$$$ существует разбиение на пары $$$(11, 12)$$$ и $$$(14, 16)$$$. Числа в первой паре похожи, потому что модуль их разности равен единице, а во второй паре — потому что они оба четные.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор задается двумя строками. В первой строке записано <span class="tex-font-style-bf">четное</span> целое число $$$n$$$ ($$$2 \le n \le 50$$$) — длина массива $$$a$$$. </p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите:</p><ul> <li> <span class="tex-font-style-tt">YES</span>, если разбиение существует; </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> можно выводить в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
YES
YES
YES
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных примера разобран в условии.</p><p>Во втором наборе два заданных числа не являются похожими.</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="b230b0fda0a7447eacc971d71902a72a"/>
<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="d404244f00d9c513cd4a88bd3efe601bfad1b606"/>
<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='b230b0fda0a7447eacc971d71902a72a'> </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%2F1360%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='b230b0fda0a7447eacc971d71902a72a'/>
<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/1360">Codeforces Round 644 (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='b230b0fda0a7447eacc971d71902a72a'/>
<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/1360/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="Сложность">
*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='b230b0fda0a7447eacc971d71902a72a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="629823"/>
<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='b230b0fda0a7447eacc971d71902a72a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="629823"/>
<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/77796" title="Codeforces Round #644 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10949:10950" 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/77846" title="Codeforces Round #644 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11453:11454" 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/1360">Задачи</a></li>
<li><a
href="/contest/1360/submit">Отослать</a></li>
<li><a
href="/contest/1360/my">Мои посылки</a></li>
<li><a
href="/contest/1360/status">Статус</a></li>
<li><a
href="/contest/1360/hacks">Взломы</a></li>
<li><a
href="/contest/1360/standings">Положение</a></li>
<li><a
href="/contest/1360/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_2ff56acc565414ed6aa7b78092c3b234976c469a">
<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$$$ и $$$y$$$ <span class="tex-font-style-it">похожими</span>, если они имеют одинаковую четность (одинаковый остаток при делении на $$$2$$$), или если $$$|x-y|=1$$$. Например, в каждой из пар $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$ числа похожи между собой, а в парах $$$(1, 4)$$$, $$$(3, 12)$$$ — нет.</p><p>Вам дан массив $$$a$$$ из $$$n$$$ (число $$$n$$$ четно) целых положительных чисел. Проверьте, существует ли такое разбиение массива на пары, что каждый элемент массива принадлежит ровно одной паре, и в каждой паре числа похожи между собой.</p><p>Например для массива $$$a = [11, 14, 16, 12]$$$ существует разбиение на пары $$$(11, 12)$$$ и $$$(14, 16)$$$. Числа в первой паре похожи, потому что модуль их разности равен единице, а во второй паре — потому что они оба четные.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор задается двумя строками. В первой строке записано <span class="tex-font-style-bf">четное</span> целое число $$$n$$$ ($$$2 \le n \le 50$$$) — длина массива $$$a$$$. </p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите:</p><ul> <li> <span class="tex-font-style-tt">YES</span>, если разбиение существует; </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> можно выводить в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
4
11 14 16 12
2
1 8
4
1 1 1 1
4
1 2 5 6
2
12 13
6
1 6 3 10 5 8
6
1 12 3 10 5 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
YES
YES
YES
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных примера разобран в условии.</p><p>Во втором наборе два заданных числа не являются похожими.</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:04: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:'8124a1e6df9f75a3',t:'MTY5NjY2NTg1Ny4xNzIwMDA='};_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", "\u041f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f, \u0442\u0435\u043e\u0440\u0435\u043c\u0430 \u041a\u0451\u043d\u0438\u0433\u0430, \u0432\u0435\u0440\u0448\u0438\u043d\u043d\u044b\u0435 \u0438 \u0440\u0435\u0431\u0435\u0440\u043d\u044b\u0435 \u043f\u043e\u043a\u0440\u044b\u0442\u0438\u044f \u0432 \u0434\u0432\u0443\u0434\u043e\u043b\u044c\u043d\u044b\u0445 \u0433\u0440\u0430\u0444\u0430\u0445", "\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", "\u043f\u0430\u0440\u043e\u0441\u043e\u0447\u0435\u0442\u0430\u043d\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1100"] | ||
1360D | 1360 | 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>Поликарп хочет купить <span class="tex-font-style-bf">ровно</span> $$$n$$$ лопат. В магазине продаются упаковки с лопатами. Всего в магазине $$$k$$$ различных видов упаковок — упаковка $$$i$$$-го вида состоит из $$$i$$$ лопат ($$$1 \le i \le k$$$). В магазине есть бесконечное количество упаковок каждого вида.</p><p>Поликарп хочет выбрать <span class="tex-font-style-bf">один</span> вид упаковки и после этого купить несколько (одну или более) упаковок этого вида. Какое наименьшее количество упаковок придется купить Поликарпу, чтобы суммарно купить ровно $$$n$$$ лопат?</p><p>Например, если $$$n=8$$$ и $$$k=7$$$, то Поликарп купит $$$2$$$ упаковки из $$$4$$$ лопат.</p><p>Помогите Поликарпу найти минимальное количество упаковок, которое необходимо купить при условии, что он:</p><ul> <li> суммарно купит ровно $$$n$$$ лопат; </li><li> размеры <span class="tex-font-style-bf">всех</span> купленных им упаковок одинаковы и являются целым числом от $$$1$$$ до $$$k$$$ включительно. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных в тесте. Далее записаны $$$t$$$ наборов тестовых данных по одному в строке.</p><p>Каждый набор представляет собой два целых положительных числа $$$n$$$ ($$$1 \le n \le 10^9$$$) и $$$k$$$ ($$$1 \le k \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>
5
8 7
8 1
6 10
999999733 999999732
999999733 999999733
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
8
1
999999733
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответ на первый набор тестовых данных разобран в условии.</p><p>Во втором наборе существует только один способ купить $$$8$$$ лопат — $$$8$$$ упаковок по одной лопате.</p><p>В третьем наборе нужно купить $$$1$$$ упаковку из $$$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="cf1fba68b43efcd76bbffe9a579604f7"/>
<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="d404244f00d9c513cd4a88bd3efe601bfad1b606"/>
<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='cf1fba68b43efcd76bbffe9a579604f7'> </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%2F1360%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='cf1fba68b43efcd76bbffe9a579604f7'/>
<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/1360">Codeforces Round 644 (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='cf1fba68b43efcd76bbffe9a579604f7'/>
<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/1360/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='cf1fba68b43efcd76bbffe9a579604f7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="629824"/>
<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='cf1fba68b43efcd76bbffe9a579604f7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="629824"/>
<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/77796" title="Codeforces Round #644 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10949:10950" 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/77846" title="Codeforces Round #644 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11453:11454" 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/1360">Задачи</a></li>
<li><a
href="/contest/1360/submit">Отослать</a></li>
<li><a
href="/contest/1360/my">Мои посылки</a></li>
<li><a
href="/contest/1360/status">Статус</a></li>
<li><a
href="/contest/1360/hacks">Взломы</a></li>
<li><a
href="/contest/1360/standings">Положение</a></li>
<li><a
href="/contest/1360/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_4fb349b0ce0fff910a651c58fefc69dee1dda4e0">
<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>Поликарп хочет купить <span class="tex-font-style-bf">ровно</span> $$$n$$$ лопат. В магазине продаются упаковки с лопатами. Всего в магазине $$$k$$$ различных видов упаковок — упаковка $$$i$$$-го вида состоит из $$$i$$$ лопат ($$$1 \le i \le k$$$). В магазине есть бесконечное количество упаковок каждого вида.</p><p>Поликарп хочет выбрать <span class="tex-font-style-bf">один</span> вид упаковки и после этого купить несколько (одну или более) упаковок этого вида. Какое наименьшее количество упаковок придется купить Поликарпу, чтобы суммарно купить ровно $$$n$$$ лопат?</p><p>Например, если $$$n=8$$$ и $$$k=7$$$, то Поликарп купит $$$2$$$ упаковки из $$$4$$$ лопат.</p><p>Помогите Поликарпу найти минимальное количество упаковок, которое необходимо купить при условии, что он:</p><ul> <li> суммарно купит ровно $$$n$$$ лопат; </li><li> размеры <span class="tex-font-style-bf">всех</span> купленных им упаковок одинаковы и являются целым числом от $$$1$$$ до $$$k$$$ включительно. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных в тесте. Далее записаны $$$t$$$ наборов тестовых данных по одному в строке.</p><p>Каждый набор представляет собой два целых положительных числа $$$n$$$ ($$$1 \le n \le 10^9$$$) и $$$k$$$ ($$$1 \le k \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>
5
8 7
8 1
6 10
999999733 999999732
999999733 999999733
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
8
1
999999733
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответ на первый набор тестовых данных разобран в условии.</p><p>Во втором наборе существует только один способ купить $$$8$$$ лопат — $$$8$$$ упаковок по одной лопате.</p><p>В третьем наборе нужно купить $$$1$$$ упаковку из $$$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:04: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:'8124a1eeeb1e9d70',t:'MTY5NjY2NTg1OC41MDcwMDA='};_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", "*1300"] | ||
1360E | 1360 | 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$$$, изначально состоящая из нулей.</p><p>На полигоне проводятся боевые учения. Поэтому над каждой клеткой в первой строке и слева от каждой клетки первого столбца находится пушка. Таким образом, всего есть $$$2n$$$ пушек.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5c881cddb6835c9ccbae4d64339c61ee89ca98e6.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Изначальный полигон для $$$n=4$$$.</span> </center><p>Пушки стреляют единицами. В один момент времени стреляет не больше одной пушки. Когда единица вылетает из пушки, то она летит вперед, по направлению выстрела, до тех пор, пока не столкнется с границей полигона или другой единицей. После этого она занимает клетку, в которой находилась перед столкновением, и остается там. Изучите примеры для лучшего понимания.</p><p>Более формально: </p><ul> <li> если пушка, стоящая в строке $$$i$$$ перед первым столбцом, стреляет единицей, то единица начинает свой полет из клетки ($$$i, 1$$$) и заканчивает в какой-то клетке ($$$i, j$$$); </li><li> если пушка, стоящая в столбце $$$j$$$ над первой строкой, стреляет единицей, то единица начинает свой полет из клетки ($$$1, j$$$) и заканчивает в какой-то клетке ($$$i, j$$$). </li></ul><p>Например, рассмотрим следующую последовательность выстрелов:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/477656491c995331732d67143a59e43b21075bcc.png" style="max-width: 100.0%;max-height: 100.0%;"/> <p> <span class="tex-font-size-small">1. Стреляет пушка в строке $$$2$$$. 2. Стреляет пушка в строке $$$2$$$. 3. Стреляет пушка в столбце $$$3$$$.</span> </p></center><p>У вас на столе лежит отчет с проведенных учений. Этот отчет является квадратной матрицей с длиной стороны $$$n$$$, состоящей из нулей и единиц. Вам интересно, действительно ли произошли учения. Другими словами, существует ли такая последовательность выстрелов, что в конце получится заданная матрица?</p><p>Каждая пушка может сделать произвольное количество выстрелов. Перед началом учений полигон состоит из нулей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано целое число $$$n$$$ ($$$1 \le n \le 50$$$) — размер полигона.</p><p>Далее следуют $$$n$$$ строк длины $$$n$$$, состоящих из нулей и единиц — матрица полигона после проведения учений.</p><p>Суммарная площадь матриц во всех наборах тестовых данных в одном тесте не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите:</p><ul> <li> <span class="tex-font-style-tt">YES</span>, если существует последовательность выстрелов, приводящая к заданной матрице; </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> можно выводить в любом регистре.</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
0010
0011
0000
0000
2
10
01
2
00
00
4
0101
1111
0101
0111
4
0100
1110
0101
0111
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
YES
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных примера разобран в условии.</p><p>Ответ на второй набор <span class="tex-font-style-tt">NO</span>, так как, вылетев из любой пушки, единица в клетке ($$$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="a4dc2c57900ea35bfd4053f09474f97b"/>
<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="d404244f00d9c513cd4a88bd3efe601bfad1b606"/>
<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='a4dc2c57900ea35bfd4053f09474f97b'> </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%2F1360%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='a4dc2c57900ea35bfd4053f09474f97b'/>
<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/1360">Codeforces Round 644 (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='a4dc2c57900ea35bfd4053f09474f97b'/>
<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/1360/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='a4dc2c57900ea35bfd4053f09474f97b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="629825"/>
<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='a4dc2c57900ea35bfd4053f09474f97b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="629825"/>
<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/77796" title="Codeforces Round #644 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10949:10950" 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/77846" title="Codeforces Round #644 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11453:11454" 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/1360">Задачи</a></li>
<li><a
href="/contest/1360/submit">Отослать</a></li>
<li><a
href="/contest/1360/my">Мои посылки</a></li>
<li><a
href="/contest/1360/status">Статус</a></li>
<li><a
href="/contest/1360/hacks">Взломы</a></li>
<li><a
href="/contest/1360/standings">Положение</a></li>
<li><a
href="/contest/1360/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_3d185f58f9812af1b1b405ae34a4b9930c99d05e">
<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$$$, изначально состоящая из нулей.</p><p>На полигоне проводятся боевые учения. Поэтому над каждой клеткой в первой строке и слева от каждой клетки первого столбца находится пушка. Таким образом, всего есть $$$2n$$$ пушек.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5c881cddb6835c9ccbae4d64339c61ee89ca98e6.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Изначальный полигон для $$$n=4$$$.</span> </center><p>Пушки стреляют единицами. В один момент времени стреляет не больше одной пушки. Когда единица вылетает из пушки, то она летит вперед, по направлению выстрела, до тех пор, пока не столкнется с границей полигона или другой единицей. После этого она занимает клетку, в которой находилась перед столкновением, и остается там. Изучите примеры для лучшего понимания.</p><p>Более формально: </p><ul> <li> если пушка, стоящая в строке $$$i$$$ перед первым столбцом, стреляет единицей, то единица начинает свой полет из клетки ($$$i, 1$$$) и заканчивает в какой-то клетке ($$$i, j$$$); </li><li> если пушка, стоящая в столбце $$$j$$$ над первой строкой, стреляет единицей, то единица начинает свой полет из клетки ($$$1, j$$$) и заканчивает в какой-то клетке ($$$i, j$$$). </li></ul><p>Например, рассмотрим следующую последовательность выстрелов:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/477656491c995331732d67143a59e43b21075bcc.png" style="max-width: 100.0%;max-height: 100.0%;" /> <p> <span class="tex-font-size-small">1. Стреляет пушка в строке $$$2$$$. 2. Стреляет пушка в строке $$$2$$$. 3. Стреляет пушка в столбце $$$3$$$.</span> </p></center><p>У вас на столе лежит отчет с проведенных учений. Этот отчет является квадратной матрицей с длиной стороны $$$n$$$, состоящей из нулей и единиц. Вам интересно, действительно ли произошли учения. Другими словами, существует ли такая последовательность выстрелов, что в конце получится заданная матрица?</p><p>Каждая пушка может сделать произвольное количество выстрелов. Перед началом учений полигон состоит из нулей.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано целое число $$$n$$$ ($$$1 \le n \le 50$$$) — размер полигона.</p><p>Далее следуют $$$n$$$ строк длины $$$n$$$, состоящих из нулей и единиц — матрица полигона после проведения учений.</p><p>Суммарная площадь матриц во всех наборах тестовых данных в одном тесте не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите:</p><ul> <li> <span class="tex-font-style-tt">YES</span>, если существует последовательность выстрелов, приводящая к заданной матрице; </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> можно выводить в любом регистре.</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
0010
0011
0000
0000
2
10
01
2
00
00
4
0101
1111
0101
0111
4
0100
1110
0101
0111
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
NO
YES
YES
NO
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных примера разобран в условии.</p><p>Ответ на второй набор <span class="tex-font-style-tt">NO</span>, так как, вылетев из любой пушки, единица в клетке ($$$1, 1$$$) продолжила бы свой полет дальше.</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:04: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:'8124a1f7384600bc',t:'MTY5NjY2NTg1OS44NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1300"] | ||
1360F | 1360 | F | ru | F. Строка-шпион | <div class="problem-statement"><div class="header"><div class="title">F. Строка-шпион</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны $$$n$$$ строк $$$a_1, a_2, \ldots, a_n$$$, все они имеют одинаковую длину $$$m$$$. Строки состоят из строчных букв латинского алфавита.</p><p>Найдите любую такую строку $$$s$$$ длины $$$m$$$, что каждая из заданных $$$n$$$ строк отличается от $$$s$$$ не более чем в одной позиции. Формально, для каждой заданной строки $$$a_i$$$ должно существовать не более одной позиции $$$j$$$, в которой $$$a_i[j] \ne s[j]$$$.</p><p>Заметим, что искомая строка $$$s$$$ может как совпадать с одной из заданных строк $$$a_i$$$, так и отличаться от всех заданных строк.</p><p>Например, если вам даны строки <span class="tex-font-style-tt">abac</span> и <span class="tex-font-style-tt">zbab</span>, тогда ответом на задачу может быть строка <span class="tex-font-style-tt">abab</span>, которая отличается от первой только последним символом, а от второй только первым.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных в тесте. Далее записаны $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записаны целые числа $$$n$$$ ($$$1 \le n \le 10$$$) и $$$m$$$ ($$$1 \le m \le 10$$$) — количество заданных строк и их длина.</p><p>Далее следуют $$$n$$$ строк $$$a_i$$$. Каждая имеет длину $$$m$$$ и состоит из строчных латинских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы тестовых данных. Каждый ответ (если он существует) — это строка длины $$$m$$$, состоящая из строчных латинских букв. Если существует несколько ответов, то выведите любой из них. Если ответа не существует, выведите «<span class="tex-font-style-tt">-1</span>» («минус один», без кавычек).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
abab
-1
aaa
ab
z</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных примера разобран в условии.</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="613924fb9465884f533f6a84c9e0fc69"/>
<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="d404244f00d9c513cd4a88bd3efe601bfad1b606"/>
<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='613924fb9465884f533f6a84c9e0fc69'> </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%2F1360%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='613924fb9465884f533f6a84c9e0fc69'/>
<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/1360">Codeforces Round 644 (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='613924fb9465884f533f6a84c9e0fc69'/>
<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/1360/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="Префикс- и 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="Сложность">
*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='613924fb9465884f533f6a84c9e0fc69'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="629826"/>
<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='613924fb9465884f533f6a84c9e0fc69'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="629826"/>
<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/77796" title="Codeforces Round #644 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10949:10950" 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/77846" title="Codeforces Round #644 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11453:11454" 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/1360">Задачи</a></li>
<li><a
href="/contest/1360/submit">Отослать</a></li>
<li><a
href="/contest/1360/my">Мои посылки</a></li>
<li><a
href="/contest/1360/status">Статус</a></li>
<li><a
href="/contest/1360/hacks">Взломы</a></li>
<li><a
href="/contest/1360/standings">Положение</a></li>
<li><a
href="/contest/1360/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_abc6ce46f05c17c7c9d011d8521a5d2f881e26a8">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Строка-шпион</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны $$$n$$$ строк $$$a_1, a_2, \ldots, a_n$$$, все они имеют одинаковую длину $$$m$$$. Строки состоят из строчных букв латинского алфавита.</p><p>Найдите любую такую строку $$$s$$$ длины $$$m$$$, что каждая из заданных $$$n$$$ строк отличается от $$$s$$$ не более чем в одной позиции. Формально, для каждой заданной строки $$$a_i$$$ должно существовать не более одной позиции $$$j$$$, в которой $$$a_i[j] \ne s[j]$$$.</p><p>Заметим, что искомая строка $$$s$$$ может как совпадать с одной из заданных строк $$$a_i$$$, так и отличаться от всех заданных строк.</p><p>Например, если вам даны строки <span class="tex-font-style-tt">abac</span> и <span class="tex-font-style-tt">zbab</span>, тогда ответом на задачу может быть строка <span class="tex-font-style-tt">abab</span>, которая отличается от первой только последним символом, а от второй только первым.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных в тесте. Далее записаны $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записаны целые числа $$$n$$$ ($$$1 \le n \le 10$$$) и $$$m$$$ ($$$1 \le m \le 10$$$) — количество заданных строк и их длина.</p><p>Далее следуют $$$n$$$ строк $$$a_i$$$. Каждая имеет длину $$$m$$$ и состоит из строчных латинских букв.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы тестовых данных. Каждый ответ (если он существует) — это строка длины $$$m$$$, состоящая из строчных латинских букв. Если существует несколько ответов, то выведите любой из них. Если ответа не существует, выведите «<span class="tex-font-style-tt">-1</span>» («минус один», без кавычек).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
abab
-1
aaa
ab
z</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных примера разобран в условии.</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:04: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:'8124a1ffccf29d45',t:'MTY5NjY2NTg2MS4yMDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\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", "\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"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0445\u044d\u0448\u0438", "*1700"] | ||
1360G | 1360 | G | ru | G. A/B матрица | <div class="problem-statement"><div class="header"><div class="title">G. A/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>Вам даны четыре целых положительных числа $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$). Найдите любую такую прямоугольную матрицу размера $$$n \times m$$$, что выполняются все следующие условия:</p><ul> <li> в каждой строке матрицы ровно $$$a$$$ единиц; </li><li> в каждом столбце матрицы ровно $$$b$$$ единиц; </li><li> все остальные элементы — нули. </li></ul><p>Если искомой матрицы не существует, то укажите это.</p><p>Например, для $$$n=3$$$, $$$m=6$$$, $$$a=2$$$, $$$b=1$$$ существует такая матрица, удовлетворяющая условиям выше:</p><p>$$$$$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор тестовых данных описывается четырьмя целыми положительными числами $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$), где $$$n$$$ и $$$m$$$ — размеры матрицы, а $$$a$$$ и $$$b$$$ — ограничения на количества единиц для строк и столбцов, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите:</p><ul> <li> «YES» (без кавычек) и искомую матрицу (если существует несколько ответов, выведите любой), если она существует, или, </li><li> «NO» (без кавычек), если ее не существует. </li></ul><p>Чтобы вывести матрицу $$$n \times m$$$, выведите $$$n$$$ строк, каждая из которых содержит $$$m$$$ чисел $$$0$$$ или $$$1$$$, описывающих очередную строку матрицы. Числа нужно выводить <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 6 2 1
2 2 2 1
2 2 2 2
4 4 2 2
2 1 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
010001
100100
001010
NO
YES
11
11
YES
1100
1100
0011
0011
YES
1
1
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="0c7b60b7b6972aa2753c78eedb45452b"/>
<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="d404244f00d9c513cd4a88bd3efe601bfad1b606"/>
<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='0c7b60b7b6972aa2753c78eedb45452b'> </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%2F1360%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='0c7b60b7b6972aa2753c78eedb45452b'/>
<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/1360">Codeforces Round 644 (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='0c7b60b7b6972aa2753c78eedb45452b'/>
<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/1360/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="Сложность">
*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='0c7b60b7b6972aa2753c78eedb45452b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="629827"/>
<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='0c7b60b7b6972aa2753c78eedb45452b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="629827"/>
<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/77796" title="Codeforces Round #644 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10949:10950" 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/77846" title="Codeforces Round #644 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11453:11454" 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/1360">Задачи</a></li>
<li><a
href="/contest/1360/submit">Отослать</a></li>
<li><a
href="/contest/1360/my">Мои посылки</a></li>
<li><a
href="/contest/1360/status">Статус</a></li>
<li><a
href="/contest/1360/hacks">Взломы</a></li>
<li><a
href="/contest/1360/standings">Положение</a></li>
<li><a
href="/contest/1360/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_89c3494fc6d07c63aa40c887df45e4929a03932e">
<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. A/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>Вам даны четыре целых положительных числа $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$). Найдите любую такую прямоугольную матрицу размера $$$n \times m$$$, что выполняются все следующие условия:</p><ul> <li> в каждой строке матрицы ровно $$$a$$$ единиц; </li><li> в каждом столбце матрицы ровно $$$b$$$ единиц; </li><li> все остальные элементы — нули. </li></ul><p>Если искомой матрицы не существует, то укажите это.</p><p>Например, для $$$n=3$$$, $$$m=6$$$, $$$a=2$$$, $$$b=1$$$ существует такая матрица, удовлетворяющая условиям выше:</p><p>$$$$$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор тестовых данных описывается четырьмя целыми положительными числами $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$), где $$$n$$$ и $$$m$$$ — размеры матрицы, а $$$a$$$ и $$$b$$$ — ограничения на количества единиц для строк и столбцов, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите:</p><ul> <li> «YES» (без кавычек) и искомую матрицу (если существует несколько ответов, выведите любой), если она существует, или, </li><li> «NO» (без кавычек), если ее не существует. </li></ul><p>Чтобы вывести матрицу $$$n \times m$$$, выведите $$$n$$$ строк, каждая из которых содержит $$$m$$$ чисел $$$0$$$ или $$$1$$$, описывающих очередную строку матрицы. Числа нужно выводить <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 6 2 1
2 2 2 1
2 2 2 2
4 4 2 2
2 1 1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
YES
010001
100100
001010
NO
YES
11
11
YES
1100
1100
0011
0011
YES
1
1
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=G]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04: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:'8124a20838449d57',t:'MTY5NjY2NTg2Mi42MzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1900"] | ||
1360H | 1360 | H | ru | H. Двоичная медиана | <div class="problem-statement"><div class="header"><div class="title">H. Двоичная медиана</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим все двоичные строки длины $$$m$$$ ($$$1 \le m \le 60$$$), то есть строки, состоящие из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Например, <span class="tex-font-style-tt">0110</span> является двоичной строкой, а <span class="tex-font-style-tt">012aba</span> — нет. Очевидно, что всего таких строк ровно $$$2^m$$$.</p><p>Строка $$$s$$$ лексикографически меньше строки $$$t$$$ (обе имеют одинаковую длину $$$m$$$), если в первой слева позиции $$$i$$$, в которой они отличаются, верно $$$s[i] < t[i]$$$. Именно такой способ сравнения строк используется в словарях и в большинстве современных языков программирования при их сравнении стандартным способом. Например, строка <span class="tex-font-style-tt">01011</span> лексикографически меньше строки <span class="tex-font-style-tt">01100</span>, потому что первые два символа совпадают, а третий символ в первой строке меньше, чем во второй.</p><p>Удалим из этого множества $$$n$$$ ($$$1 \le n \le \min(2^m-1, 100)$$$) <span class="tex-font-style-bf">различных</span> двоичных строк $$$a_1, a_2, \ldots, a_n$$$, каждая длины $$$m$$$. Таким образом, в множестве останется $$$k=2^m-n$$$ строк. Отсортируем все строки полученного множества в порядке лексикографического возрастания (как в словаре).</p><p>Пронумеруем все строки после сортировки от $$$0$$$ до $$$k-1$$$. Выведите строку, номер которой равен $$$\lfloor \frac{k-1}{2} \rfloor$$$ (такой элемент называется <span class="tex-font-style-it">медианой</span>), где $$$\lfloor x \rfloor$$$ является округлением числа вниз к ближайшему целому.</p><p>Например, если $$$n=3$$$, $$$m=3$$$ и $$$a=[$$$<span class="tex-font-style-tt">010</span>, <span class="tex-font-style-tt">111</span>, <span class="tex-font-style-tt">001</span>$$$]$$$, то после удаления строк $$$a_i$$$ и сортировки результат примет вид: $$$[$$$<span class="tex-font-style-tt">000</span>, <span class="tex-font-style-tt">011</span>, <span class="tex-font-style-tt">100</span>, <span class="tex-font-style-tt">101</span>, <span class="tex-font-style-tt">110</span>$$$]$$$. Таким образом, искомая медиана равна <span class="tex-font-style-tt">100</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>В первой строке каждого набора записаны целые числа $$$n$$$ ($$$1 \le n \le \min(2^m-1, 100)$$$) и $$$m$$$ ($$$1 \le m \le 60$$$), где $$$n$$$ — количество удаляемых строк, $$$m$$$ — длина двоичных строк. Следующие $$$n$$$ строк содержат $$$a_1, a_2, \ldots, a_n$$$ — <span class="tex-font-style-bf">различные</span> двоичные строки длины $$$m$$$.</p><p>Суммарная длина всех заданных двоичных строк во всех наборах тестовых данных в одном тесте не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы тестовых данных. Ответом является строка длины $$$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 3
010
001
111
4 3
000
111
100
011
1 1
1
1 1
0
3 2
00
01
10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
100
010
0
1
11
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных примера разобран в условии.</p><p>Во втором наборе результат после удаления строк и сортировки равен $$$[$$$<span class="tex-font-style-tt">001</span>, <span class="tex-font-style-tt">010</span>, <span class="tex-font-style-tt">101</span>, <span class="tex-font-style-tt">110</span>$$$]$$$. Следовательно, искомая медиана равна <span class="tex-font-style-tt">010</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="b4b0f96fa1b7ef3ab9e76e46178b8e4f"/>
<meta id="viewport" name="viewport" content="width=device-width, initial-scale=0.01"/>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery-1.8.3.js"></script>
<script type="application/javascript">
window.locale = "ru";
window.standaloneContest = false;
function adjustViewport() {
var screenWidthPx = Math.min($(window).width(), window.screen.width);
var siteWidthPx = 1100; // min width of site
var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0);
var viewport = "width=device-width, initial-scale=" + ratio;
$('#viewport').attr('content', viewport);
var style = $('<style>html * { max-height: 1000000px; }</style>');
$('html > head').append(style);
}
if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
adjustViewport();
}
/* Protection against trailing dot in domain. */
let hostLength = window.location.host.length;
if (hostLength > 1 && window.location.host[hostLength - 1] === '.') {
window.location = window.location.protocol + "//" + window.location.host.substring(0, hostLength - 1);
}
</script>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="expires" content="-1">
<meta http-equiv="profileName" content="j3">
<meta name="google-site-verification" content="OTd2dN5x4nS4OPknPI9JFg36fKxjqY0i1PSfFPv_J90"/>
<meta property="fb:admins" content="100001352546622" />
<meta property="og:image" content="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<link rel="image_src" href="//codeforces.org/s/36819/images/codeforces-sponsored-by-ton.png" />
<meta property="og:title" content="Задача - H - Codeforces"/>
<meta property="og:description" content=""/>
<meta property="og:site_name" content="Codeforces"/>
<meta name="cc" content="d404244f00d9c513cd4a88bd3efe601bfad1b606"/>
<meta name="utc_offset" content="+03:00"/>
<meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" />
<title>Задача - H - Codeforces</title>
<meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" />
<meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" />
<meta name="robots" content="index, follow" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/font-awesome.min.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/line-awesome.min.css" type="text/css" charset="utf-8" />
<link href='//fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Cuprum&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="apple-touch-icon" sizes="57x57" href="//codeforces.org/s/36819/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="//codeforces.org/s/36819/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="//codeforces.org/s/36819/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="//codeforces.org/s/36819/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="//codeforces.org/s/36819/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="//codeforces.org/s/36819/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="//codeforces.org/s/36819/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="//codeforces.org/s/36819/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="//codeforces.org/s/36819/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="//codeforces.org/s/36819/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="//codeforces.org/s/36819/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="//codeforces.org/s/36819/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="//codeforces.org/s/36819/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="//codeforces.org/s/36819/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!--CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/css/prettify.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/clear.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/ttypography.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/problem-statement.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/second-level-menu.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/roundbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/datatable.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/table-form.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/topic.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.jgrowl.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/facebox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.wysiwyg.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.autocomplete.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/codeforces.datepick.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/colorbox.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/jquery.drafts.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/community.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/css/sidebar-menu.css" type="text/css" charset="utf-8" />
<!-- MathJax -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]}
});
MathJax.Hub.Register.StartupHook("End", function () {
Codeforces.runMathJaxListeners();
});
</script>
<script type="text/javascript" async
src="https://mathjax.codeforces.org/MathJax.js?config=TeX-AMS_HTML-full"
>
</script>
<!-- /MathJax -->
<script type="text/javascript" src="//codeforces.org/s/36819/js/prettify/prettify.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/moment-with-locales.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/pushstream.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.jgrowl.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.swipe.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.hotkeys.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/facebox.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.wysiwyg.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.colorpicker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.table.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.image.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/controls/wysiwyg.link.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.autocomplete.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ie6blocker.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.colorbox-min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.ba-bbq.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.drafts.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/clipboard.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/autosize.min.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/sjcl.js"></script>
<script type="text/javascript" src="/scripts/d6f1367b70ec83a8355f663476cb5b0f/ru/codeforces-options.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/codeforces.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/EventCatcher.js?v=20160131"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/preparedVerdictFormats-ru.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/js/confetti.min.js"></script>
<!--/CombineResourcesFilter-->
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/skins/markitup/style.css" type="text/css" charset="utf-8" />
<link rel="stylesheet" href="//codeforces.org/s/36819/markitup/sets/markdown/style.css" type="text/css" charset="utf-8" />
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/jquery.markitup.js"></script>
<script type="text/javascript" src="//codeforces.org/s/36819/markitup/sets/markdown/set.js"></script>
<!--[if IE]>
<style>
#sidebar {
padding-left: 1em;
margin: 1em 1em 1em 0;
}
</style>
<![endif]-->
<script type="text/javascript" src="//codeforces.org/s/36819/js/jquery.datepick-ru.js"></script>
</head>
<body class=" "><span style='display:none;' class='csrf-token' data-csrf='b4b0f96fa1b7ef3ab9e76e46178b8e4f'> </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%2F1360%2Fproblem%2FH%3Flocale%3Dru">Войти</a>
|
<a href="/register">Зарегистрироваться</a>
</div>
</div>
<br style="clear: both;"/>
</div>
<div class="roundbox menu-box borderTopRound borderBottomRound" style="">
<div class="menu-list-container">
<ul class="menu-list main-menu-list">
<li class=""><a href="/">Главная</a></li>
<li class=""><a href="/top">Топ</a></li>
<li class=""><a href="/catalog">Каталог</a></li>
<li class="current"><a href="/contests">Соревнования</a></li>
<li class=""><a href="/gyms">Тренировки</a></li>
<li class=""><a href="/problemset">Архив</a></li>
<li class=""><a href="/groups">Группы</a></li>
<li class=""><a href="/ratings">Рейтинг</a></li>
<li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li>
<li class=""><a href="/apiHelp">API</a></li>
<li class=""><a href="/calendar">Календарь</a></li>
<li class=""><a href="/help">Помощь</a></li>
</ul>
<form method="post" action="/search"><input type='hidden' name='csrf_token' value='b4b0f96fa1b7ef3ab9e76e46178b8e4f'/>
<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/1360">Codeforces Round 644 (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='b4b0f96fa1b7ef3ab9e76e46178b8e4f'/>
<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/1360/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='b4b0f96fa1b7ef3ab9e76e46178b8e4f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="629828"/>
<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='b4b0f96fa1b7ef3ab9e76e46178b8e4f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="629828"/>
<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/77796" title="Codeforces Round #644 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10949:10950" 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/77846" title="Codeforces Round #644 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11453:11454" 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/1360">Задачи</a></li>
<li><a
href="/contest/1360/submit">Отослать</a></li>
<li><a
href="/contest/1360/my">Мои посылки</a></li>
<li><a
href="/contest/1360/status">Статус</a></li>
<li><a
href="/contest/1360/hacks">Взломы</a></li>
<li><a
href="/contest/1360/standings">Положение</a></li>
<li><a
href="/contest/1360/customtest">Запуск</a></li>
</ul>
</div>
<style>
#facebox .content:has(.diff-popup) {
width: 90vw;
max-width: 120rem !important;
}
.testCaseMarker {
position: absolute;
font-weight: bold;
font-size: 1rem;
}
.diff-popup {
width: 90vw;
max-width: 120rem !important;
display: none;
overflow: auto;
}
.input-output-copier {
font-size: 1.2rem;
float: right;
color: #888 !important;
cursor: pointer;
border: 1px solid rgb(185, 185, 185);
padding: 3px;
margin: 1px;
line-height: 1.1rem;
text-transform: none;
}
.input-output-copier:hover {
background-color: #def;
}
.test-explanation textarea {
width: 100%;
height: 1.5em;
}
.pending-submission-message {
color: darkorange !important;
}
</style>
<script>
const OPENING_SPACE = String.fromCharCode(1001);
const CLOSING_SPACE = String.fromCharCode(1002);
const nodeToText = function (node, pre) {
let result = [];
if (node.tagName === "SCRIPT" || node.tagName === "math"
|| (node.classList && node.classList.contains("input-output-copier")))
return [];
if (node.tagName === "NOBR") {
result.push(OPENING_SPACE);
}
if (node.nodeType === Node.TEXT_NODE) {
let s = node.textContent;
if (!pre) {
s = s.replace(/\s+/g, " ");
}
if (s.length > 0) {
result.push(s);
}
}
if (pre && node.tagName === "BR") {
result.push("\n");
}
node.childNodes.forEach(function (child) {
result.push(nodeToText(child, node.tagName === "PRE").join(""));
});
if (node.tagName === "DIV"
|| node.tagName === "P"
|| node.tagName === "PRE"
|| node.tagName === "UL"
|| node.tagName === "LI"
) {
result.push("\n");
}
if (node.tagName === "NOBR") {
result.push(CLOSING_SPACE);
}
return result;
}
const isSpecial = function (c) {
return c === ',' || c === '.' || c === ';' || c === ')' || c === ' ';
}
const convertStatementToText = function(statmentNode) {
const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n");
let result = [];
for (let i = 0; i < text.length; i++) {
const c = text.charAt(i);
if (c === OPENING_SPACE) {
if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) {
result.push('+');
}
} else if (c === CLOSING_SPACE) {
if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) {
result.push('-');
}
} else {
result.push(c);
}
}
return result.join("").split("\n").map(value => value.trim()).join("\n");
};
</script>
<div class="diff-popup">
</div>
<div class="problemindexholder" problemindex="H" data-uuid="ps_4e5ef7f1c8af4a20940992b6516cd81aa2d93c97">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">H. Двоичная медиана</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Рассмотрим все двоичные строки длины $$$m$$$ ($$$1 \le m \le 60$$$), то есть строки, состоящие из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>. Например, <span class="tex-font-style-tt">0110</span> является двоичной строкой, а <span class="tex-font-style-tt">012aba</span> — нет. Очевидно, что всего таких строк ровно $$$2^m$$$.</p><p>Строка $$$s$$$ лексикографически меньше строки $$$t$$$ (обе имеют одинаковую длину $$$m$$$), если в первой слева позиции $$$i$$$, в которой они отличаются, верно $$$s[i] < t[i]$$$. Именно такой способ сравнения строк используется в словарях и в большинстве современных языков программирования при их сравнении стандартным способом. Например, строка <span class="tex-font-style-tt">01011</span> лексикографически меньше строки <span class="tex-font-style-tt">01100</span>, потому что первые два символа совпадают, а третий символ в первой строке меньше, чем во второй.</p><p>Удалим из этого множества $$$n$$$ ($$$1 \le n \le \min(2^m-1, 100)$$$) <span class="tex-font-style-bf">различных</span> двоичных строк $$$a_1, a_2, \ldots, a_n$$$, каждая длины $$$m$$$. Таким образом, в множестве останется $$$k=2^m-n$$$ строк. Отсортируем все строки полученного множества в порядке лексикографического возрастания (как в словаре).</p><p>Пронумеруем все строки после сортировки от $$$0$$$ до $$$k-1$$$. Выведите строку, номер которой равен $$$\lfloor \frac{k-1}{2} \rfloor$$$ (такой элемент называется <span class="tex-font-style-it">медианой</span>), где $$$\lfloor x \rfloor$$$ является округлением числа вниз к ближайшему целому.</p><p>Например, если $$$n=3$$$, $$$m=3$$$ и $$$a=[$$$<span class="tex-font-style-tt">010</span>, <span class="tex-font-style-tt">111</span>, <span class="tex-font-style-tt">001</span>$$$]$$$, то после удаления строк $$$a_i$$$ и сортировки результат примет вид: $$$[$$$<span class="tex-font-style-tt">000</span>, <span class="tex-font-style-tt">011</span>, <span class="tex-font-style-tt">100</span>, <span class="tex-font-style-tt">101</span>, <span class="tex-font-style-tt">110</span>$$$]$$$. Таким образом, искомая медиана равна <span class="tex-font-style-tt">100</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>В первой строке каждого набора записаны целые числа $$$n$$$ ($$$1 \le n \le \min(2^m-1, 100)$$$) и $$$m$$$ ($$$1 \le m \le 60$$$), где $$$n$$$ — количество удаляемых строк, $$$m$$$ — длина двоичных строк. Следующие $$$n$$$ строк содержат $$$a_1, a_2, \ldots, a_n$$$ — <span class="tex-font-style-bf">различные</span> двоичные строки длины $$$m$$$.</p><p>Суммарная длина всех заданных двоичных строк во всех наборах тестовых данных в одном тесте не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы тестовых данных. Ответом является строка длины $$$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 3
010
001
111
4 3
000
111
100
011
1 1
1
1 1
0
3 2
00
01
10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
100
010
0
1
11
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных примера разобран в условии.</p><p>Во втором наборе результат после удаления строк и сортировки равен $$$[$$$<span class="tex-font-style-tt">001</span>, <span class="tex-font-style-tt">010</span>, <span class="tex-font-style-tt">101</span>, <span class="tex-font-style-tt">110</span>$$$]$$$. Следовательно, искомая медиана равна <span class="tex-font-style-tt">010</span>.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=H]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04: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:'8124a2114cae75a3',t:'MTY5NjY2NTg2My45ODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u041a\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"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2100"] | ||
1361A | 1361 | 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>Сегодня Джонни хочет увеличить свой вклад. Его план подразумевает написание $$$n$$$ блогов. Один блог покрывает одну тему, но одна тема может быть покрыта несколькими блогами. Также, некоторые блоги связаны друг с другом ссылками. Каждая пара блогов, связанных ссылкой, должна покрывать две разные темы. Потому что иначе читатели могут заметить, что блоги разделены только для того, чтобы набрать больше вклада. Множество блогов и двусторонние ссылки между некоторыми парами из них называются сетью блогов.</p><p>Всего есть $$$n$$$ различных тем, пронумерованных от $$$1$$$ до $$$n$$$, упорядоченных по пониманию Джонни. Структура сети блогов уже приготовлена. Теперь Джонни должен написать все блоги в некотором порядке. Он ленивый, поэтому каждый раз перед написанием блога, он смотрит на все уже написанные соседние блоги (связанные ссылкой с текущим) и выбирает тему с минимальным номером, которая еще не покрыта соседними блогами. Можно заметить, что такая стратегия всегда позволит ему выбрать тему, потому что максимальное количество соседних блогов равно $$$n - 1$$$.</p><p>Например, если уже написанные, соседние с текущим, блоги покрывают темы с номерами $$$1$$$, $$$3$$$, $$$1$$$, $$$5$$$ и $$$2$$$, Джонни выберет тему номер $$$4$$$ для текущего блога, потому что темы номер $$$1$$$, $$$2$$$ и $$$3$$$ уже покрыты соседними блогами, а тема номер $$$4$$$ — нет.</p><p>Как хороший друг, вы провели некоторые исследования и предсказали наилучшую темы для каждого блога. Не могли бы вы сказать Джонни, в каком порядке он должен писать блоги, чтобы в результате его стратегии каждый блог покрывал выбранную вами тему?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ и $$$m$$$ $$$(0 \leq m \leq 5 \cdot 10^5)$$$ — количество блогов и ссылок, соответственно.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$a$$$ и $$$b$$$ ($$$a \neq b$$$; $$$1 \leq a, b \leq n$$$), которые означают, что в сети блогов есть ссылка между блогами с номерами $$$a$$$ и $$$b$$$. Гарантируется, что граф сети блогов не содержит кратных ребер.</p><p>Последняя строка содержит $$$n$$$ целых чисел $$$t_1, t_2, \ldots, t_n$$$, $$$i$$$-е из них обозначает желаемую тему для $$$i$$$-го блога ($$$1 \le t_i \le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если решение не существует, выведите $$$-1$$$. Иначе, выведите $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ $$$(1 \leq p_i \leq 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 3
1 2
2 3
3 1
2 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1 3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 3
1 2
2 3
3 1
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 3
1 2
2 3
4 5
2 1 2 2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 5 1 3 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, Джонни начинает с написания блога номер $$$2$$$, у него пока еще нет написанных соседних блогов, поэтому Джонни выбирает тему номер один. Потом он пишет блог номер $$$1$$$, у него есть ссылка на уже написанный второй блог, поэтому Джонни выбирает вторую тему. Наконец, он пишет блог номер $$$3$$$, у него есть ссылки на блоги номер $$$1$$$ и $$$2$$$, поэтому Джонни выбирает третью тему.</p><p>Второй пример: Не существует ни одной перестановки, удовлетворяющей всем условиям.</p><p>Третий пример: Сначала Джонни пишет блог номер $$$2$$$, который получает тему $$$1$$$. Затем, он пишет блог $$$5$$$, который тоже получает тему $$$1$$$, потому из него нет ссылки на единственный уже написанный блог (номер $$$2$$$). Затем, он пишет блог $$$1$$$, он получает тему $$$2$$$, потому что из него есть ссылка на блог $$$2$$$ с темой $$$1$$$. Затем, он пишет блог $$$3$$$, из него есть ссылка на блог $$$2$$$, поэтому он получает тему $$$2$$$. Наконец, он пишет блог $$$4$$$, из него есть ссылка на блог $$$5$$$, поэтому он получает тему $$$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="45d7bd45f51fb59a211e03d8102e0bf0"/>
<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="3af69f2430b8a1773b93ec948f84f678696264d9"/>
<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='45d7bd45f51fb59a211e03d8102e0bf0'> </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%2F1361%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='45d7bd45f51fb59a211e03d8102e0bf0'/>
<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/1361">Codeforces Round 647 (Div. 1) - Thanks, Algo Muse!</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='45d7bd45f51fb59a211e03d8102e0bf0'/>
<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/1361/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='45d7bd45f51fb59a211e03d8102e0bf0'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640968"/>
<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='45d7bd45f51fb59a211e03d8102e0bf0'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640968"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11022" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11032" resourceName="Codeforces Round #647 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/1361">Задачи</a></li>
<li><a
href="/contest/1361/submit">Отослать</a></li>
<li><a
href="/contest/1361/my">Мои посылки</a></li>
<li><a
href="/contest/1361/status">Статус</a></li>
<li><a
href="/contest/1361/hacks">Взломы</a></li>
<li><a
href="/contest/1361/room/1">Комната</a></li>
<li><a
href="/contest/1361/standings">Положение</a></li>
<li><a
href="/contest/1361/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_c8b5bbd4749dc75eac98920c60f9da8983208954">
<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>Сегодня Джонни хочет увеличить свой вклад. Его план подразумевает написание $$$n$$$ блогов. Один блог покрывает одну тему, но одна тема может быть покрыта несколькими блогами. Также, некоторые блоги связаны друг с другом ссылками. Каждая пара блогов, связанных ссылкой, должна покрывать две разные темы. Потому что иначе читатели могут заметить, что блоги разделены только для того, чтобы набрать больше вклада. Множество блогов и двусторонние ссылки между некоторыми парами из них называются сетью блогов.</p><p>Всего есть $$$n$$$ различных тем, пронумерованных от $$$1$$$ до $$$n$$$, упорядоченных по пониманию Джонни. Структура сети блогов уже приготовлена. Теперь Джонни должен написать все блоги в некотором порядке. Он ленивый, поэтому каждый раз перед написанием блога, он смотрит на все уже написанные соседние блоги (связанные ссылкой с текущим) и выбирает тему с минимальным номером, которая еще не покрыта соседними блогами. Можно заметить, что такая стратегия всегда позволит ему выбрать тему, потому что максимальное количество соседних блогов равно $$$n - 1$$$.</p><p>Например, если уже написанные, соседние с текущим, блоги покрывают темы с номерами $$$1$$$, $$$3$$$, $$$1$$$, $$$5$$$ и $$$2$$$, Джонни выберет тему номер $$$4$$$ для текущего блога, потому что темы номер $$$1$$$, $$$2$$$ и $$$3$$$ уже покрыты соседними блогами, а тема номер $$$4$$$ — нет.</p><p>Как хороший друг, вы провели некоторые исследования и предсказали наилучшую темы для каждого блога. Не могли бы вы сказать Джонни, в каком порядке он должен писать блоги, чтобы в результате его стратегии каждый блог покрывал выбранную вами тему?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ и $$$m$$$ $$$(0 \leq m \leq 5 \cdot 10^5)$$$ — количество блогов и ссылок, соответственно.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$a$$$ и $$$b$$$ ($$$a \neq b$$$; $$$1 \leq a, b \leq n$$$), которые означают, что в сети блогов есть ссылка между блогами с номерами $$$a$$$ и $$$b$$$. Гарантируется, что граф сети блогов не содержит кратных ребер.</p><p>Последняя строка содержит $$$n$$$ целых чисел $$$t_1, t_2, \ldots, t_n$$$, $$$i$$$-е из них обозначает желаемую тему для $$$i$$$-го блога ($$$1 \le t_i \le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если решение не существует, выведите $$$-1$$$. Иначе, выведите $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ $$$(1 \leq p_i \leq 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 3
1 2
2 3
3 1
2 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1 3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 3
1 2
2 3
3 1
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 3
1 2
2 3
4 5
2 1 2 2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 5 1 3 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, Джонни начинает с написания блога номер $$$2$$$, у него пока еще нет написанных соседних блогов, поэтому Джонни выбирает тему номер один. Потом он пишет блог номер $$$1$$$, у него есть ссылка на уже написанный второй блог, поэтому Джонни выбирает вторую тему. Наконец, он пишет блог номер $$$3$$$, у него есть ссылки на блоги номер $$$1$$$ и $$$2$$$, поэтому Джонни выбирает третью тему.</p><p>Второй пример: Не существует ни одной перестановки, удовлетворяющей всем условиям.</p><p>Третий пример: Сначала Джонни пишет блог номер $$$2$$$, который получает тему $$$1$$$. Затем, он пишет блог $$$5$$$, который тоже получает тему $$$1$$$, потому из него нет ссылки на единственный уже написанный блог (номер $$$2$$$). Затем, он пишет блог $$$1$$$, он получает тему $$$2$$$, потому что из него есть ссылка на блог $$$2$$$ с темой $$$1$$$. Затем, он пишет блог $$$3$$$, из него есть ссылка на блог $$$2$$$, поэтому он получает тему $$$2$$$. Наконец, он пишет блог $$$4$$$, из него есть ссылка на блог $$$5$$$, поэтому он получает тему $$$2$$$.</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:04: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:'8124a2198b759d5b',t:'MTY5NjY2NTg2NS4zNjEwMDA='};_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\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"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1700"] | ||
1361B | 1361 | 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>Мальчик нашел онлайн архив с задачами, разделенными по темам. Он выбрал $$$p^{k_i}$$$ задач из $$$i$$$-й категории ($$$p$$$ — его любимое число). Он хочет решить все эти задачи за две недели (терпение еще слишком сложно для Джонни, поэтому он смотрит только на простые задачи, которые могут быть решены за такой период). Теперь наш будущий гроссмейстер должен решить, какие темы покрыть на первой неделе, а какие на второй. Помогите ему распределить темы таким образом, чтобы нагрузка была равномерной.</p><p>Формально, дано $$$n$$$ чисел $$$p^{k_i}$$$, мальчик хочет разделить их на два непересекающихся набора, минимизировав разность между суммами чисел в наборах. Найдите минимальное значение модуля такой разности. Выведите остаток от деления результата на $$$10^{9}+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов входных данных. Первая строка содержит одно целое число $$$t$$$ $$$(1 \leq t \leq 10^5)$$$ — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. Вторая строка содержит $$$n$$$ целых чисел $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — остаток от деления ответа на $$$1\,000\,000\,007$$$.</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 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
1
146981438
747093407
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вы должны минимизировать модуль разности, а не остаток модуля разности. Например, если минимальная разность равна $$$2$$$, но существует также разбиение, при котором разность равна $$$10^9 + 8$$$, ответ равен $$$2$$$, а не $$$1$$$.</p><p>В первом наборе входных данных числа равны: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$ и $$$8$$$. Мы можем разделить их на два набора: $$${4, 8, 16}$$$ и $$${8, 16}$$$. Тогда модуль разности между суммами чисел в наборах будет равен $$$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="5b2a27cc1622e2b7d9b03feedb06af90"/>
<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="3af69f2430b8a1773b93ec948f84f678696264d9"/>
<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='5b2a27cc1622e2b7d9b03feedb06af90'> </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%2F1361%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='5b2a27cc1622e2b7d9b03feedb06af90'/>
<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/1361">Codeforces Round 647 (Div. 1) - Thanks, Algo Muse!</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='5b2a27cc1622e2b7d9b03feedb06af90'/>
<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/1361/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='5b2a27cc1622e2b7d9b03feedb06af90'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640969"/>
<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='5b2a27cc1622e2b7d9b03feedb06af90'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640969"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11022" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11032" resourceName="Codeforces Round #647 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/1361">Задачи</a></li>
<li><a
href="/contest/1361/submit">Отослать</a></li>
<li><a
href="/contest/1361/my">Мои посылки</a></li>
<li><a
href="/contest/1361/status">Статус</a></li>
<li><a
href="/contest/1361/hacks">Взломы</a></li>
<li><a
href="/contest/1361/room/1">Комната</a></li>
<li><a
href="/contest/1361/standings">Положение</a></li>
<li><a
href="/contest/1361/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_980ea4ce9fb6c153a91a1bd54948f82e734c5b9d">
<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>Мальчик нашел онлайн архив с задачами, разделенными по темам. Он выбрал $$$p^{k_i}$$$ задач из $$$i$$$-й категории ($$$p$$$ — его любимое число). Он хочет решить все эти задачи за две недели (терпение еще слишком сложно для Джонни, поэтому он смотрит только на простые задачи, которые могут быть решены за такой период). Теперь наш будущий гроссмейстер должен решить, какие темы покрыть на первой неделе, а какие на второй. Помогите ему распределить темы таким образом, чтобы нагрузка была равномерной.</p><p>Формально, дано $$$n$$$ чисел $$$p^{k_i}$$$, мальчик хочет разделить их на два непересекающихся набора, минимизировав разность между суммами чисел в наборах. Найдите минимальное значение модуля такой разности. Выведите остаток от деления результата на $$$10^{9}+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов входных данных. Первая строка содержит одно целое число $$$t$$$ $$$(1 \leq t \leq 10^5)$$$ — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. Вторая строка содержит $$$n$$$ целых чисел $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — остаток от деления ответа на $$$1\,000\,000\,007$$$.</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 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
1
146981438
747093407
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вы должны минимизировать модуль разности, а не остаток модуля разности. Например, если минимальная разность равна $$$2$$$, но существует также разбиение, при котором разность равна $$$10^9 + 8$$$, ответ равен $$$2$$$, а не $$$1$$$.</p><p>В первом наборе входных данных числа равны: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$ и $$$8$$$. Мы можем разделить их на два набора: $$${4, 8, 16}$$$ и $$${8, 16}$$$. Тогда модуль разности между суммами чисел в наборах будет равен $$$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:04: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:'8124a222285e9d86',t:'MTY5NjY2NTg2Ni43MTYwMDA='};_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\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", "\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", "*1900"] | ||
1361C | 1361 | 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>У младшей сестры Джонни, Меган, недавно был день рождения. Её брат подарил ей коробочку, подписанную как: «Твое прекрасное ожерелье — сделай сама!». Коробочка содержит много частей ожерелья и магический клей.</p><p>Каждая часть ожерелья представляет собой цепочку, соединяющую две жемчужины. Цвет каждой из жемчужин может быть представлен целым неотрицательным числом. Магический клей позволяет Меган склеивать две жемчужины (возможно, из одной части ожерелья) в одну. Красота соединения двух жемчужин цветов $$$u$$$ и $$$v$$$ определяется следующим образом: пусть $$$2^k$$$ — максимальная степень двух, делящая $$$u \oplus v$$$ — <a href="https://en.wikipedia.org/wiki/Exclusive_or#Computer_science">исключающее или</a> $$$u$$$ и $$$v$$$. Тогда красота соединения равна $$$k$$$. Если $$$u = v$$$, вы можете считать, что красота равна $$$20$$$.</p><p>Каждая жемчужина может быть склеена с другой максимум один раз. Склеивание двух частей ожерелья объединяет их. Используя клей несколько раз, Меган может наконец получить свое ожерелье, которое является циклом, сделанным из соединенных последовательно частей ожерелья (так, что каждая жемчужина в ожерелье соединена с ровно одной другой жемчужиной). Красота такого ожерелья равна минимальной красоте соединений в нем. Девочка хочет использовать все доступные части ожерелья, чтобы получить <span class="tex-font-style-bf">ровно одно</span> ожерелье, содержащее <span class="tex-font-style-bf">все части</span>, с максимальной возможной красотой. Помогите ей!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ — количество частей ожерелья в коробочке.</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$a$$$ и $$$b$$$ $$$(0 \leq a, b < 2^{20})$$$, которые обозначают цвета жемчужин из этой части ожерелья. Жемчужины на $$$i$$$-й строке имеют индексы $$$2i - 1$$$ и $$$2i$$$, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Первая строка должна содержать одно целое число $$$b$$$, обозначающее максимальную возможную красоту ожерелья, собранного из всех данных частей.</p><p>Следующая строка должна содержать $$$2n$$$ различных целых чисел $$$p_i$$$ $$$(1 \leq p_i \leq 2n)$$$ — индексы исходных жемчужин в порядке, в котором они должны быть расположены в ожерелье. Индексы жемчужин, принадлежащих одной части, должны быть расположены на соседних позициях в перестановке (поэтому $$$1\,4\,3\,2$$$ не является корректным выводом, а $$$2\,1\,4\,3$$$ и $$$4\,3\,1\,2$$$ являются). Если существует несколько подходящих ответов, вы можете вывести любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
13 11
11 1
3 5
17 1
9 27
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
8 7 9 10 5 6 1 2 3 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
13 11
11 1
3 5
17 1
7 29
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
8 7 10 9 5 6 4 3 2 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
20
2 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере следующие пары жемчужин объединяются: $$$(7, 9)$$$, $$$(10, 5)$$$, $$$(6, 1)$$$, $$$(2, 3)$$$ и $$$(4, 8)$$$. Красота соединений равна: $$$3$$$, $$$3$$$, $$$3$$$, $$$20$$$, $$$20$$$, соответственно.</p><p>Иллюстрация показывает эту конструкцию:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/69d60d8bfa6bc79bd945ddb77b0979b45ae8d7f1.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="33974299ae8ffd5aefc46fe85d4e5b17"/>
<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="3af69f2430b8a1773b93ec948f84f678696264d9"/>
<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='33974299ae8ffd5aefc46fe85d4e5b17'> </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%2F1361%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='33974299ae8ffd5aefc46fe85d4e5b17'/>
<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/1361">Codeforces Round 647 (Div. 1) - Thanks, Algo Muse!</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='33974299ae8ffd5aefc46fe85d4e5b17'/>
<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/1361/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Битовые маски">
битмаски
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Система непересекающихся множеств">
снм
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='33974299ae8ffd5aefc46fe85d4e5b17'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640970"/>
<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='33974299ae8ffd5aefc46fe85d4e5b17'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640970"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11022" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11032" resourceName="Codeforces Round #647 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/1361">Задачи</a></li>
<li><a
href="/contest/1361/submit">Отослать</a></li>
<li><a
href="/contest/1361/my">Мои посылки</a></li>
<li><a
href="/contest/1361/status">Статус</a></li>
<li><a
href="/contest/1361/hacks">Взломы</a></li>
<li><a
href="/contest/1361/room/1">Комната</a></li>
<li><a
href="/contest/1361/standings">Положение</a></li>
<li><a
href="/contest/1361/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_1861fd526a6aedd0fd7537465f0ae033ab4cf902">
<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>У младшей сестры Джонни, Меган, недавно был день рождения. Её брат подарил ей коробочку, подписанную как: «Твое прекрасное ожерелье — сделай сама!». Коробочка содержит много частей ожерелья и магический клей.</p><p>Каждая часть ожерелья представляет собой цепочку, соединяющую две жемчужины. Цвет каждой из жемчужин может быть представлен целым неотрицательным числом. Магический клей позволяет Меган склеивать две жемчужины (возможно, из одной части ожерелья) в одну. Красота соединения двух жемчужин цветов $$$u$$$ и $$$v$$$ определяется следующим образом: пусть $$$2^k$$$ — максимальная степень двух, делящая $$$u \oplus v$$$ — <a href="https://en.wikipedia.org/wiki/Exclusive_or#Computer_science">исключающее или</a> $$$u$$$ и $$$v$$$. Тогда красота соединения равна $$$k$$$. Если $$$u = v$$$, вы можете считать, что красота равна $$$20$$$.</p><p>Каждая жемчужина может быть склеена с другой максимум один раз. Склеивание двух частей ожерелья объединяет их. Используя клей несколько раз, Меган может наконец получить свое ожерелье, которое является циклом, сделанным из соединенных последовательно частей ожерелья (так, что каждая жемчужина в ожерелье соединена с ровно одной другой жемчужиной). Красота такого ожерелья равна минимальной красоте соединений в нем. Девочка хочет использовать все доступные части ожерелья, чтобы получить <span class="tex-font-style-bf">ровно одно</span> ожерелье, содержащее <span class="tex-font-style-bf">все части</span>, с максимальной возможной красотой. Помогите ей!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ — количество частей ожерелья в коробочке.</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$a$$$ и $$$b$$$ $$$(0 \leq a, b < 2^{20})$$$, которые обозначают цвета жемчужин из этой части ожерелья. Жемчужины на $$$i$$$-й строке имеют индексы $$$2i - 1$$$ и $$$2i$$$, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Первая строка должна содержать одно целое число $$$b$$$, обозначающее максимальную возможную красоту ожерелья, собранного из всех данных частей.</p><p>Следующая строка должна содержать $$$2n$$$ различных целых чисел $$$p_i$$$ $$$(1 \leq p_i \leq 2n)$$$ — индексы исходных жемчужин в порядке, в котором они должны быть расположены в ожерелье. Индексы жемчужин, принадлежащих одной части, должны быть расположены на соседних позициях в перестановке (поэтому $$$1\,4\,3\,2$$$ не является корректным выводом, а $$$2\,1\,4\,3$$$ и $$$4\,3\,1\,2$$$ являются). Если существует несколько подходящих ответов, вы можете вывести любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
13 11
11 1
3 5
17 1
9 27
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
8 7 9 10 5 6 1 2 3 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
13 11
11 1
3 5
17 1
7 29
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
8 7 10 9 5 6 4 3 2 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
20
2 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере следующие пары жемчужин объединяются: $$$(7, 9)$$$, $$$(10, 5)$$$, $$$(6, 1)$$$, $$$(2, 3)$$$ и $$$(4, 8)$$$. Красота соединений равна: $$$3$$$, $$$3$$$, $$$3$$$, $$$20$$$, $$$20$$$, соответственно.</p><p>Иллюстрация показывает эту конструкцию:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/69d60d8bfa6bc79bd945ddb77b0979b45ae8d7f1.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=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:04: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:'8124a22a88e63a7d',t:'MTY5NjY2NTg2OC4wMDYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\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"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\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", "*2500"] | ||
1361D | 1361 | D | ru | D. Джонни и Джеймс | <div class="problem-statement"><div class="header"><div class="title">D. Джонни и Джеймс</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Джеймса Бонда, любимого секретного агента Джонни, новая миссия. Есть $$$n$$$ вражеских баз, каждая из которых задана своими координатами, так что мы можем рассматривать их как точки на плоскости.</p><p>Базы могут общаться друг с другом, посылая сигнал, который является лучом, из выбранной точки в направлении начала координат или в противоположном направлении. Исключением является центральная база, расположенная в начале координат. Она может посылать сигнал в любом направлении.</p><p>Когда какие-то две базы хотят коммуницировать, существует два возможных сценария. Если они лежат на одной прямой с началом координат, одна из них посылает сигнал непосредственно второй. Иначе, из первой базы сигнал посылается на центральную, и оттуда — на вторую. Обозначим расстоянием между двумя базами суммарное Евклидово расстояние, которое сигнал, посланный между ними, должен пройти.</p><p>Бонд может повредить все, кроме некоторых $$$k$$$ баз, которые он может выбрать на свое усмотрение. Поврежденная база не может посылать или получать сигнал напрямую, но все еще может передавать его между двумя работающими базами. В частности, Джеймс может повредить центральную базу, и сигнал <span class="tex-font-style-bf">все еще может быть послан</span> между любыми двумя неповрежденными базами, как и раньше, и расстояние между ними останется неизменным. Какова максимальная сумма расстояний между всеми парами оставшихся баз, которую 007 может достичь, уничтожив ровно $$$n - k$$$ баз?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ $$$(2 \leq k \leq n \leq 5 \cdot 10^5)$$$ — количество баз и количество баз, которое должно остаться, соответственно.</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$x$$$ и $$$y$$$ $$$(-10^9 \leq x, y \leq 10^9)$$$, $$$i$$$-я строка содержит координаты $$$i$$$-й базы. Гарантируется, что никакие две точки не совпадают и что одна из точек равна $$$(0, 0)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести одно число — максимальную возможную сумму расстояний между всеми парами некоторых $$$k$$$ из баз. Ваш ответ будет считаться правильным, если его абсолютная или относительная погрешность не превышает $$$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>
6 2
0 0
1 1
2 2
3 3
0 1
0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6.24264069
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 5
0 0
1 1
2 2
3 3
0 1
0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
32.62741700
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
13 10
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
0 -2
0 1
0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
237.00000000
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 5
2 2
4 4
3 5
6 10
0 5
0 0
5 0
10 0
0 10
4 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
181.52406315
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, в оптимальном решении Бонд <span class="tex-font-style-bf">не</span> разрушает базы с номерами $$$4$$$ и $$$6$$$ (помечены оранжевым): </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c9fb6601db4a76fcc522afb554b05909e0e2f21b.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Следующая иллюстрация показывает оптимальное решение для второго примера. Следующие базы <span class="tex-font-style-bf">не</span> разрушены: $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$ (помечены оранжевым).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c10877d2e8cc4d3f6b67968e0f6dba15f95304fc.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Оптимальное решение для третьего теста изображено на иллюстрации. Только базы с номерами $$$3$$$, $$$4$$$ и $$$5$$$ разрушены. Снова, <span class="tex-font-style-bf">не</span> разрушенные базы помечены оранжевым.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b8d1a440b2809b2e3febfca36b2927b7baa80213.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="6bee767d50f8a4bccb34a6e5e539b0ed"/>
<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="3af69f2430b8a1773b93ec948f84f678696264d9"/>
<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='6bee767d50f8a4bccb34a6e5e539b0ed'> </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%2F1361%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='6bee767d50f8a4bccb34a6e5e539b0ed'/>
<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/1361">Codeforces Round 647 (Div. 1) - Thanks, Algo Muse!</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='6bee767d50f8a4bccb34a6e5e539b0ed'/>
<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/1361/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="Сложность">
*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='6bee767d50f8a4bccb34a6e5e539b0ed'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640971"/>
<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='6bee767d50f8a4bccb34a6e5e539b0ed'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640971"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11022" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11032" resourceName="Codeforces Round #647 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/1361">Задачи</a></li>
<li><a
href="/contest/1361/submit">Отослать</a></li>
<li><a
href="/contest/1361/my">Мои посылки</a></li>
<li><a
href="/contest/1361/status">Статус</a></li>
<li><a
href="/contest/1361/hacks">Взломы</a></li>
<li><a
href="/contest/1361/room/1">Комната</a></li>
<li><a
href="/contest/1361/standings">Положение</a></li>
<li><a
href="/contest/1361/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_c7bbc1e6761970c8d07985fa18b484658a977af4">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Джонни и Джеймс</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Джеймса Бонда, любимого секретного агента Джонни, новая миссия. Есть $$$n$$$ вражеских баз, каждая из которых задана своими координатами, так что мы можем рассматривать их как точки на плоскости.</p><p>Базы могут общаться друг с другом, посылая сигнал, который является лучом, из выбранной точки в направлении начала координат или в противоположном направлении. Исключением является центральная база, расположенная в начале координат. Она может посылать сигнал в любом направлении.</p><p>Когда какие-то две базы хотят коммуницировать, существует два возможных сценария. Если они лежат на одной прямой с началом координат, одна из них посылает сигнал непосредственно второй. Иначе, из первой базы сигнал посылается на центральную, и оттуда — на вторую. Обозначим расстоянием между двумя базами суммарное Евклидово расстояние, которое сигнал, посланный между ними, должен пройти.</p><p>Бонд может повредить все, кроме некоторых $$$k$$$ баз, которые он может выбрать на свое усмотрение. Поврежденная база не может посылать или получать сигнал напрямую, но все еще может передавать его между двумя работающими базами. В частности, Джеймс может повредить центральную базу, и сигнал <span class="tex-font-style-bf">все еще может быть послан</span> между любыми двумя неповрежденными базами, как и раньше, и расстояние между ними останется неизменным. Какова максимальная сумма расстояний между всеми парами оставшихся баз, которую 007 может достичь, уничтожив ровно $$$n - k$$$ баз?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$k$$$ $$$(2 \leq k \leq n \leq 5 \cdot 10^5)$$$ — количество баз и количество баз, которое должно остаться, соответственно.</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$x$$$ и $$$y$$$ $$$(-10^9 \leq x, y \leq 10^9)$$$, $$$i$$$-я строка содержит координаты $$$i$$$-й базы. Гарантируется, что никакие две точки не совпадают и что одна из точек равна $$$(0, 0)$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Вы должны вывести одно число — максимальную возможную сумму расстояний между всеми парами некоторых $$$k$$$ из баз. Ваш ответ будет считаться правильным, если его абсолютная или относительная погрешность не превышает $$$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>
6 2
0 0
1 1
2 2
3 3
0 1
0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6.24264069
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 5
0 0
1 1
2 2
3 3
0 1
0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
32.62741700
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
13 10
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
0 -2
0 1
0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
237.00000000
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10 5
2 2
4 4
3 5
6 10
0 5
0 0
5 0
10 0
0 10
4 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
181.52406315
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, в оптимальном решении Бонд <span class="tex-font-style-bf">не</span> разрушает базы с номерами $$$4$$$ и $$$6$$$ (помечены оранжевым): </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c9fb6601db4a76fcc522afb554b05909e0e2f21b.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Следующая иллюстрация показывает оптимальное решение для второго примера. Следующие базы <span class="tex-font-style-bf">не</span> разрушены: $$$2$$$, $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$ (помечены оранжевым).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c10877d2e8cc4d3f6b67968e0f6dba15f95304fc.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Оптимальное решение для третьего теста изображено на иллюстрации. Только базы с номерами $$$3$$$, $$$4$$$ и $$$5$$$ разрушены. Снова, <span class="tex-font-style-bf">не</span> разрушенные базы помечены оранжевым.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/b8d1a440b2809b2e3febfca36b2927b7baa80213.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04: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:'8124a2333f5816cf',t:'MTY5NjY2NTg2OS40NzMwMDA='};_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", "\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"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\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", "*2900"] | ||
1361E | 1361 | 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.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Джеймса Бонда есть новый план, как поймать своего врага. Есть несколько городов и <span class="tex-font-style-bf">ориентированные</span> дороги между ними, причем используя эти дороги можно добраться из любого города до любого другого. Когда враг появляется в каком-то городе, Бонд знает её следующий пункт назначения, но понятия не имеет, какой путь она выберет, чтобы ехать туда.</p><p>Город $$$a$$$ называется интересным, если для любого города $$$b$$$, существует ровно один простой путь из $$$a$$$ в $$$b$$$. Простым путем называется последовательность различных городов, в которой для каждых двух соседних городов есть дорога, ведущая из первого города во второй.</p><p>Враг Бонда хороша в побегах, поэтому только погоня, начатая в интересном городе дает шанс поймать её. Джеймс хочет расположить своих людей в таких городах. Однако, если интересных городов недостаточно много, весь план не имеет смысла, потому что людям Бонда, возможно, придется ждать появления врага очень долго.</p><p>Вы ответственны за поиск всех интересных городов. Выведите их, либо сообщите, что их недостаточно много. Под недостаточно много, Джеймс подразумевает строго меньше $$$20\%$$$ всех городов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 2\,000$$$) — количество наборов входных данных. Каждый набор входных данных описывается следующим образом:</p><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \le 10^5$$$, $$$0 \leq m \le 2 \cdot 10^5$$$) — количество городов и дорог между ними. Каждая из следующих $$$m$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$u \neq v$$$; $$$1 \leq u, v \leq n$$$), которые обозначают дорогу из города $$$u$$$ в город $$$v$$$.</p><p>Гарантируется, что между каждой упорядоченной парой городов существует максимум одна дорога. Сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$, а сумма $$$m$$$ не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если строго меньше $$$20\%$$$ всех городов являются интересными, выведите $$$-1$$$. Иначе, пусть $$$k$$$ равно количеству интересных городов. Выведите $$$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
3 3
1 2
2 3
3 1
3 6
1 2
2 1
2 3
3 2
1 3
3 1
7 10
1 2
2 3
3 1
1 4
4 5
5 1
4 6
6 7
7 4
6 1
6 8
1 2
2 3
3 4
4 5
5 6
6 1
6 2
5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 2 3
-1
1 2 3 5
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На всех иллюстрациях, если город интересный, он помечен зеленым, а иначе — красным.</p><p>В первом наборе входных данных, все города интересные. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/87e0bbcee48594de37b23a676007c13fed7e8861.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Во втором наборе входных данных, ни один город не интересен. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/67e3f1d2fe5a3ae679a81637a28cba8d10690d12.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В третьем наборе входных данных, города $$$1$$$, $$$2$$$, $$$3$$$ и $$$5$$$ интересные. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/770d1dc42d1d76bc99074e566acc63becca03f19.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В четвертом наборе входных данных, только город $$$1$$$ является интересным. Это строго меньше, чем $$$20\%$$$ всех городов, поэтому ответ $$$-1$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/feac6ccbfd9e4443658aaf9c32ad9b3ca8ef3cb2.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="ef30f38fbbb3b20b428b126797becbb9"/>
<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="3af69f2430b8a1773b93ec948f84f678696264d9"/>
<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='ef30f38fbbb3b20b428b126797becbb9'> </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%2F1361%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='ef30f38fbbb3b20b428b126797becbb9'/>
<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/1361">Codeforces Round 647 (Div. 1) - Thanks, Algo Muse!</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='ef30f38fbbb3b20b428b126797becbb9'/>
<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/1361/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Вероятности, мат. ожидания, случайные величины и др.">
теория вероятностей
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*3000
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ef30f38fbbb3b20b428b126797becbb9'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640972"/>
<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='ef30f38fbbb3b20b428b126797becbb9'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640972"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11022" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11032" resourceName="Codeforces Round #647 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/1361">Задачи</a></li>
<li><a
href="/contest/1361/submit">Отослать</a></li>
<li><a
href="/contest/1361/my">Мои посылки</a></li>
<li><a
href="/contest/1361/status">Статус</a></li>
<li><a
href="/contest/1361/hacks">Взломы</a></li>
<li><a
href="/contest/1361/room/1">Комната</a></li>
<li><a
href="/contest/1361/standings">Положение</a></li>
<li><a
href="/contest/1361/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_ca80b901b0590b1dea94b266020ed3a620c53ca8">
<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.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Джеймса Бонда есть новый план, как поймать своего врага. Есть несколько городов и <span class="tex-font-style-bf">ориентированные</span> дороги между ними, причем используя эти дороги можно добраться из любого города до любого другого. Когда враг появляется в каком-то городе, Бонд знает её следующий пункт назначения, но понятия не имеет, какой путь она выберет, чтобы ехать туда.</p><p>Город $$$a$$$ называется интересным, если для любого города $$$b$$$, существует ровно один простой путь из $$$a$$$ в $$$b$$$. Простым путем называется последовательность различных городов, в которой для каждых двух соседних городов есть дорога, ведущая из первого города во второй.</p><p>Враг Бонда хороша в побегах, поэтому только погоня, начатая в интересном городе дает шанс поймать её. Джеймс хочет расположить своих людей в таких городах. Однако, если интересных городов недостаточно много, весь план не имеет смысла, потому что людям Бонда, возможно, придется ждать появления врага очень долго.</p><p>Вы ответственны за поиск всех интересных городов. Выведите их, либо сообщите, что их недостаточно много. Под недостаточно много, Джеймс подразумевает строго меньше $$$20\%$$$ всех городов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 2\,000$$$) — количество наборов входных данных. Каждый набор входных данных описывается следующим образом:</p><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \le 10^5$$$, $$$0 \leq m \le 2 \cdot 10^5$$$) — количество городов и дорог между ними. Каждая из следующих $$$m$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$u \neq v$$$; $$$1 \leq u, v \leq n$$$), которые обозначают дорогу из города $$$u$$$ в город $$$v$$$.</p><p>Гарантируется, что между каждой упорядоченной парой городов существует максимум одна дорога. Сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$, а сумма $$$m$$$ не превышает $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если строго меньше $$$20\%$$$ всех городов являются интересными, выведите $$$-1$$$. Иначе, пусть $$$k$$$ равно количеству интересных городов. Выведите $$$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
3 3
1 2
2 3
3 1
3 6
1 2
2 1
2 3
3 2
1 3
3 1
7 10
1 2
2 3
3 1
1 4
4 5
5 1
4 6
6 7
7 4
6 1
6 8
1 2
2 3
3 4
4 5
5 6
6 1
6 2
5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 2 3
-1
1 2 3 5
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На всех иллюстрациях, если город интересный, он помечен зеленым, а иначе — красным.</p><p>В первом наборе входных данных, все города интересные. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/87e0bbcee48594de37b23a676007c13fed7e8861.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Во втором наборе входных данных, ни один город не интересен. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/67e3f1d2fe5a3ae679a81637a28cba8d10690d12.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В третьем наборе входных данных, города $$$1$$$, $$$2$$$, $$$3$$$ и $$$5$$$ интересные. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/770d1dc42d1d76bc99074e566acc63becca03f19.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В четвертом наборе входных данных, только город $$$1$$$ является интересным. Это строго меньше, чем $$$20\%$$$ всех городов, поэтому ответ $$$-1$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/feac6ccbfd9e4443658aaf9c32ad9b3ca8ef3cb2.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:04: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:'8124a23bdfd39d63',t:'MTY5NjY2NTg3MC43ODMwMDA='};_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", "\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", "\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"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3000"] | ||
1361F | 1361 | F | ru | F. Джонни и новая игрушка | <div class="problem-statement"><div class="header"><div class="title">F. Джонни и новая игрушка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>15 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</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$$$ до $$$n$$$, записанных в строку друг за другом.</p><p>Для каждого $$$i$$$ от $$$1$$$ до $$$n - 1$$$, между $$$P_i$$$ и $$$P_{i + 1}$$$ написан вес $$$W_i$$$, и эти веса также образуют перестановку чисел от $$$1$$$ до $$$n - 1$$$. Дополнительно есть веса $$$W_0 = W_n = 0$$$.</p><p>Инструкция гласит, что отрезок $$$[L, R]$$$ является хорошим, если $$$W_{L - 1} < W_i$$$ и $$$W_R < W_i$$$ для всех $$$i$$$ из $$$\{L, L + 1, \ldots, R - 1\}$$$. Для такого отрезка она также определяет $$$W_M$$$ как минимум из множества $$$\{W_L, W_{L + 1}, \ldots, W_{R - 1}\}$$$. </p><p>Теперь начинается веселье. За один ход, игрок может выбрать один из хороших подотрезков, разрезать на $$$[L, M]$$$ и $$$[M + 1, R]$$$ и поменять местами эти части. Более точно, до операции выбранный подотрезок игрушки выглядел следующим образом: $$$$$$W_{L - 1}, P_L, W_L, \ldots, W_{M - 1}, P_M, W_M, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_R$$$$$$ А после, он стал выглядеть так: $$$$$$W_{L - 1}, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_M, P_L, W_L, \ldots, W_{M - 1}, P_M, W_R$$$$$$</p><p>Такая операция может быть выполнена несколько раз (возможно, ноль), и целью является получить минимальное возможное количество инверсий в $$$P$$$.</p><p>Младшая сестра Джонни, Меган, считает, что правила слишком запутанные, поэтому она хочет проверить своего брата, выбирая некоторые пары индексов $$$X$$$ и $$$Y$$$, и меняя местами $$$P_X$$$ и $$$P_Y$$$ ($$$X$$$ может быть равно $$$Y$$$). После каждого действия сестры, Джонни интересуется, какого минимального количества инверсий можно достичь, начиная с текущего $$$P$$$ и делая корректные действия?</p><p>Вы можете считать, что входные данные были сгенерированы <span class="tex-font-style-bf">случайно</span>. $$$P$$$ и $$$W$$$ были выбраны случайно и равновероятно среди всех перестановок, а запросы Меган были выбраны случайно и равновероятно среди всех пар индексов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ $$$(2 \leq n \leq 2 \cdot 10^5)$$$, обозначающее длину игрушки.</p><p>Вторая строка содержит $$$n$$$ различных целых чисел $$$P_1, P_2, \ldots, P_n$$$ $$$(1 \leq P_i \leq n)$$$, обозначающих исходную перестановку $$$P$$$. Третья строка содержит $$$n - 1$$$ различных целых чисел $$$W_1, W_2, \ldots, W_{n - 1}$$$ $$$(1 \leq W_i \leq n - 1)$$$, обозначающих веса.</p><p>Четвертая строка содержит одно целое число $$$q$$$ $$$(1 \leq q \leq 5 \cdot 10^4)$$$ — количество действий Меган. Следующие $$$q$$$ строк содержат по два целых числа $$$X$$$ и $$$Y$$$ $$$(1 \leq X, Y \leq n)$$$ — индексы элементов $$$P$$$, меняющихся местами. Запросы не независимы, после каждого из них перестановка меняется.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. Строка номер $$$i$$$ должна содержать одно целое число — минимальное количество инверсий в перестановке, которое может быть получено, если начинать с $$$P$$$ после первых $$$i$$$ запросов и выполнять операции, описанные в инструкции.</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 1
2 1
3
1 3
3 2
3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
4 3 2 5 1
3 2 1 4
7
5 4
5 2
1 5
2 4
2 4
4 3
3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
1
2
1
2
3
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример. После первого запроса, $$$P$$$ отсортирована, поэтому мы уже получили перестановку без инверсий.</p><p>После второго запроса, $$$P$$$ равна [$$$1$$$, $$$3$$$, $$$2$$$], в ней есть одна инверсия, и можно доказать, что получить $$$0$$$ инверсий невозможно.</p><p>В конце, $$$P$$$ равна [$$$2$$$, $$$3$$$, $$$1$$$]. Мы можем выбрать всю перестановку в качестве хорошего подотрезка, после чего $$$P$$$ станет равным [$$$1$$$, $$$2$$$, $$$3$$$], в котором $$$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="669cb5b45bfcde35d2d774d8cf1128f1"/>
<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="3af69f2430b8a1773b93ec948f84f678696264d9"/>
<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='669cb5b45bfcde35d2d774d8cf1128f1'> </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%2F1361%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='669cb5b45bfcde35d2d774d8cf1128f1'/>
<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/1361">Codeforces Round 647 (Div. 1) - Thanks, Algo Muse!</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='669cb5b45bfcde35d2d774d8cf1128f1'/>
<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/1361/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='669cb5b45bfcde35d2d774d8cf1128f1'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640973"/>
<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='669cb5b45bfcde35d2d774d8cf1128f1'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640973"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11022" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11032" resourceName="Codeforces Round #647 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/1361">Задачи</a></li>
<li><a
href="/contest/1361/submit">Отослать</a></li>
<li><a
href="/contest/1361/my">Мои посылки</a></li>
<li><a
href="/contest/1361/status">Статус</a></li>
<li><a
href="/contest/1361/hacks">Взломы</a></li>
<li><a
href="/contest/1361/room/1">Комната</a></li>
<li><a
href="/contest/1361/standings">Положение</a></li>
<li><a
href="/contest/1361/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_08349e19278dda86aa25d0e1077a89fa1ea9a0bc">
<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>15 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>1024 мегабайта</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$$$ до $$$n$$$, записанных в строку друг за другом.</p><p>Для каждого $$$i$$$ от $$$1$$$ до $$$n - 1$$$, между $$$P_i$$$ и $$$P_{i + 1}$$$ написан вес $$$W_i$$$, и эти веса также образуют перестановку чисел от $$$1$$$ до $$$n - 1$$$. Дополнительно есть веса $$$W_0 = W_n = 0$$$.</p><p>Инструкция гласит, что отрезок $$$[L, R]$$$ является хорошим, если $$$W_{L - 1} < W_i$$$ и $$$W_R < W_i$$$ для всех $$$i$$$ из $$$\{L, L + 1, \ldots, R - 1\}$$$. Для такого отрезка она также определяет $$$W_M$$$ как минимум из множества $$$\{W_L, W_{L + 1}, \ldots, W_{R - 1}\}$$$. </p><p>Теперь начинается веселье. За один ход, игрок может выбрать один из хороших подотрезков, разрезать на $$$[L, M]$$$ и $$$[M + 1, R]$$$ и поменять местами эти части. Более точно, до операции выбранный подотрезок игрушки выглядел следующим образом: $$$$$$W_{L - 1}, P_L, W_L, \ldots, W_{M - 1}, P_M, W_M, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_R$$$$$$ А после, он стал выглядеть так: $$$$$$W_{L - 1}, P_{M + 1}, W_{M + 1}, \ldots, W_{R - 1}, P_R, W_M, P_L, W_L, \ldots, W_{M - 1}, P_M, W_R$$$$$$</p><p>Такая операция может быть выполнена несколько раз (возможно, ноль), и целью является получить минимальное возможное количество инверсий в $$$P$$$.</p><p>Младшая сестра Джонни, Меган, считает, что правила слишком запутанные, поэтому она хочет проверить своего брата, выбирая некоторые пары индексов $$$X$$$ и $$$Y$$$, и меняя местами $$$P_X$$$ и $$$P_Y$$$ ($$$X$$$ может быть равно $$$Y$$$). После каждого действия сестры, Джонни интересуется, какого минимального количества инверсий можно достичь, начиная с текущего $$$P$$$ и делая корректные действия?</p><p>Вы можете считать, что входные данные были сгенерированы <span class="tex-font-style-bf">случайно</span>. $$$P$$$ и $$$W$$$ были выбраны случайно и равновероятно среди всех перестановок, а запросы Меган были выбраны случайно и равновероятно среди всех пар индексов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ $$$(2 \leq n \leq 2 \cdot 10^5)$$$, обозначающее длину игрушки.</p><p>Вторая строка содержит $$$n$$$ различных целых чисел $$$P_1, P_2, \ldots, P_n$$$ $$$(1 \leq P_i \leq n)$$$, обозначающих исходную перестановку $$$P$$$. Третья строка содержит $$$n - 1$$$ различных целых чисел $$$W_1, W_2, \ldots, W_{n - 1}$$$ $$$(1 \leq W_i \leq n - 1)$$$, обозначающих веса.</p><p>Четвертая строка содержит одно целое число $$$q$$$ $$$(1 \leq q \leq 5 \cdot 10^4)$$$ — количество действий Меган. Следующие $$$q$$$ строк содержат по два целых числа $$$X$$$ и $$$Y$$$ $$$(1 \leq X, Y \leq n)$$$ — индексы элементов $$$P$$$, меняющихся местами. Запросы не независимы, после каждого из них перестановка меняется.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. Строка номер $$$i$$$ должна содержать одно целое число — минимальное количество инверсий в перестановке, которое может быть получено, если начинать с $$$P$$$ после первых $$$i$$$ запросов и выполнять операции, описанные в инструкции.</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 1
2 1
3
1 3
3 2
3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
4 3 2 5 1
3 2 1 4
7
5 4
5 2
1 5
2 4
2 4
4 3
3 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
1
2
1
2
3
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример. После первого запроса, $$$P$$$ отсортирована, поэтому мы уже получили перестановку без инверсий.</p><p>После второго запроса, $$$P$$$ равна [$$$1$$$, $$$3$$$, $$$2$$$], в ней есть одна инверсия, и можно доказать, что получить $$$0$$$ инверсий невозможно.</p><p>В конце, $$$P$$$ равна [$$$2$$$, $$$3$$$, $$$1$$$]. Мы можем выбрать всю перестановку в качестве хорошего подотрезка, после чего $$$P$$$ станет равным [$$$1$$$, $$$2$$$, $$$3$$$], в котором $$$0$$$ инверсий.</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:04: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:'8124a2440fb776b5',t:'MTY5NjY2NTg3Mi4wNzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\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"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\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", "*3300"] | ||
1362A | 1362 | 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>Недавно Джонни обнаружил древний сломанный компьютер. У него есть только один регистр, в который можно записать некоторое значение. После чего, за одну операцию вы можете применить к значению битовый сдвиг влево или вправо на не более чем три позиции. Сдвиг вправо запрещен, если в результате <span class="tex-font-style-bf">будут потеряны единичные биты</span>. Так что, на самом деле, за одну операцию вы можете умножить или разделить значение на $$$2$$$, $$$4$$$ или $$$8$$$, и деление разрешено только если значение делится нацело на выбранный делитель.</p><p>Формально, если регистр содержит целое положительное число $$$x$$$, за одну операцию оно может быть заменено одним из следующих: </p><ul> <li> $$$x \cdot 2$$$ </li><li> $$$x \cdot 4$$$ </li><li> $$$x \cdot 8$$$ </li><li> $$$x / 2$$$, если $$$x$$$ делится на $$$2$$$ </li><li> $$$x / 4$$$, если $$$x$$$ делится на $$$4$$$ </li><li> $$$x / 8$$$, если $$$x$$$ делится на $$$8$$$ </li></ul><p>Например, если $$$x = 6$$$, за одну операцию оно может быть заменено на $$$12$$$, $$$24$$$, $$$48$$$ или $$$3$$$. Значение $$$6$$$ не делится на $$$4$$$ или $$$8$$$, поэтому существуют только четыре варианта замены.</p><p>Теперь Джонни интересуется, какое минимальное количество операций необходимо, если он запишет в регистр значение $$$a$$$ и в конце хочет получить там значение $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов входных данных. Первая строка содержит целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество наборов входных данных. Следующие $$$t$$$ строк содержат описание наборов входных данных.</p><p>Первая и единственная строка каждого набора входных данных содержит целые числа $$$a$$$ и $$$b$$$ ($$$1 \leq a, b \leq 10^{18}$$$) — исходное значение и желаемое итоговое значение, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, каждая строка должна содержать одно целое число, обозначающее минимальное количество операций, которое Джонни должен выполнить. Если Джонни не сможет получить значение $$$b$$$ в конце, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
10
10 5
11 44
17 21
1 1
96 3
2 128
1001 1100611139403776
1000000000000000000 1000000000000000000
7 1
10 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1
-1
0
2
2
14
0
-1
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, Джонни может получить $$$5$$$ из $$$10$$$ сделав один сдвиг вправо на один (т.е. поделив на $$$2$$$).</p><p>Во втором наборе входных данных, Джонни может получить $$$44$$$ из $$$11$$$ сделав один сдвиг влево на два (т.е. умножив на $$$4$$$).</p><p>В третьем наборе входных данных, Джонни не может получить значение $$$21$$$ из значения $$$17$$$.</p><p>В четвертом наборе входных данных, исходное и желаемое значения совпадают, поэтому Джонни придется сделать $$$0$$$ операций.</p><p>В пятом наборе входных данных, Джонни может получить $$$3$$$ из $$$96$$$ сделав два сдвига вправо: один на $$$2$$$, и другой на $$$3$$$ (т.е. поделив на $$$4$$$ и $$$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="7aeddf06e78cb8f92c200eacd8142513"/>
<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="8d18d602cf77141b71dd1ccf82b854ddbe4b7f9f"/>
<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='7aeddf06e78cb8f92c200eacd8142513'> </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%2F1362%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='7aeddf06e78cb8f92c200eacd8142513'/>
<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/1362">Codeforces Round 647 (Div. 2) - Thanks, Algo Muse!</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='7aeddf06e78cb8f92c200eacd8142513'/>
<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/1362/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="Сложность">
*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='7aeddf06e78cb8f92c200eacd8142513'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640962"/>
<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='7aeddf06e78cb8f92c200eacd8142513'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640962"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11023" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11031" resourceName="Codeforces Round #647 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/1362">Задачи</a></li>
<li><a
href="/contest/1362/submit">Отослать</a></li>
<li><a
href="/contest/1362/my">Мои посылки</a></li>
<li><a
href="/contest/1362/status">Статус</a></li>
<li><a
href="/contest/1362/hacks">Взломы</a></li>
<li><a
href="/contest/1362/room/1">Комната</a></li>
<li><a
href="/contest/1362/standings">Положение</a></li>
<li><a
href="/contest/1362/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_1bc42ebca7b501ae3f9d7cba28bf7d6367c9ed0b">
<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>Недавно Джонни обнаружил древний сломанный компьютер. У него есть только один регистр, в который можно записать некоторое значение. После чего, за одну операцию вы можете применить к значению битовый сдвиг влево или вправо на не более чем три позиции. Сдвиг вправо запрещен, если в результате <span class="tex-font-style-bf">будут потеряны единичные биты</span>. Так что, на самом деле, за одну операцию вы можете умножить или разделить значение на $$$2$$$, $$$4$$$ или $$$8$$$, и деление разрешено только если значение делится нацело на выбранный делитель.</p><p>Формально, если регистр содержит целое положительное число $$$x$$$, за одну операцию оно может быть заменено одним из следующих: </p><ul> <li> $$$x \cdot 2$$$ </li><li> $$$x \cdot 4$$$ </li><li> $$$x \cdot 8$$$ </li><li> $$$x / 2$$$, если $$$x$$$ делится на $$$2$$$ </li><li> $$$x / 4$$$, если $$$x$$$ делится на $$$4$$$ </li><li> $$$x / 8$$$, если $$$x$$$ делится на $$$8$$$ </li></ul><p>Например, если $$$x = 6$$$, за одну операцию оно может быть заменено на $$$12$$$, $$$24$$$, $$$48$$$ или $$$3$$$. Значение $$$6$$$ не делится на $$$4$$$ или $$$8$$$, поэтому существуют только четыре варианта замены.</p><p>Теперь Джонни интересуется, какое минимальное количество операций необходимо, если он запишет в регистр значение $$$a$$$ и в конце хочет получить там значение $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов входных данных. Первая строка содержит целое число $$$t$$$ ($$$1 \leq t \leq 1000$$$) — количество наборов входных данных. Следующие $$$t$$$ строк содержат описание наборов входных данных.</p><p>Первая и единственная строка каждого набора входных данных содержит целые числа $$$a$$$ и $$$b$$$ ($$$1 \leq a, b \leq 10^{18}$$$) — исходное значение и желаемое итоговое значение, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, каждая строка должна содержать одно целое число, обозначающее минимальное количество операций, которое Джонни должен выполнить. Если Джонни не сможет получить значение $$$b$$$ в конце, выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
10
10 5
11 44
17 21
1 1
96 3
2 128
1001 1100611139403776
1000000000000000000 1000000000000000000
7 1
10 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1
-1
0
2
2
14
0
-1
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, Джонни может получить $$$5$$$ из $$$10$$$ сделав один сдвиг вправо на один (т.е. поделив на $$$2$$$).</p><p>Во втором наборе входных данных, Джонни может получить $$$44$$$ из $$$11$$$ сделав один сдвиг влево на два (т.е. умножив на $$$4$$$).</p><p>В третьем наборе входных данных, Джонни не может получить значение $$$21$$$ из значения $$$17$$$.</p><p>В четвертом наборе входных данных, исходное и желаемое значения совпадают, поэтому Джонни придется сделать $$$0$$$ операций.</p><p>В пятом наборе входных данных, Джонни может получить $$$3$$$ из $$$96$$$ сделав два сдвига вправо: один на $$$2$$$, и другой на $$$3$$$ (т.е. поделив на $$$4$$$ и $$$8$$$).</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:04: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:'8124a24c1f3f16af',t:'MTY5NjY2NTg3My40NDAwMDA='};_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", "*1000"] | ||
1362B | 1362 | B | ru | B. Джонни и его хобби | <div class="problem-statement"><div class="header"><div class="title">B. Джонни и его хобби</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Среди многочисленных хобби Джонни, есть два, казалось бы, безвредных: применение побитовых операций и прокрадывание в офис его отца. Как это обычно и бывает у маленьких детей, Джонни не подозревает, что комбинирование этих двух занятий может доставить ему много неприятностей.</p><p>На столе его отца хранится множество $$$S$$$, содержащее очень важные числа. В момент, когда Джонни узнал об этом, он решил, что это хорошая идея выбрать <span class="tex-font-style-bf">положительное</span> целое число $$$k$$$ и заменить все элементы $$$s$$$ из множества $$$S$$$ на $$$s \oplus k$$$ ($$$\oplus$$$ обозначает операцию <a href="https://en.wikipedia.org/wiki/Exclusive_or#Computer_science">исключающего или</a>).</p><p>Помогите Джонни выбрать такое $$$k$$$, что его отец не заметит никакой разницы после того, как Джонни закончит играть (т.е. Джонни должен получить такое же множество, какое было изначально). Возможно, что ни одного такого числа не существует. Также, возможно, что существует несколько подходящих чисел. В таком случае, выведите минимальное из них. Обратите внимание, что порядок элементов в множестве не имеет значения, т.е. множество $$$\{1, 2, 3\}$$$ равно множеству $$$\{2, 1, 3\}$$$.</p><p>Формально, требуется найти минимальное положительное целое число $$$k$$$, такое что $$$\{s \oplus k | s \in S\} = S$$$ или сообщить, что ни одного подходящего числа не существует.</p><p>Например, если $$$S = \{1, 3, 4\}$$$ и $$$k = 2$$$, новое множество будет равно $$$\{3, 1, 6\}$$$. Если $$$S = \{0, 1, 2, 3\}$$$ и $$$k = 1$$$, после игры множество останется таким же.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано одно целое число $$$t$$$ ($$$1 \leq t \leq 1024$$$) — количество наборов входных данных. В следующих строках даны $$$t$$$ наборов входных данных, каждый из них занимает две строки.</p><p>В первой строке набора входных данных дано одно целое число $$$n$$$ ($$$1 \leq n \leq 1024$$$), обозначающее количество элементов в множестве $$$S$$$. Вторая строка содержит $$$n$$$ <span class="tex-font-style-bf">различных</span> целых чисел $$$s_i$$$ ($$$0 \leq s_i < 1024$$$) — элементы $$$S$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$1024$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, $$$i$$$-я из них должна содержать ответ на $$$i$$$-й набор входных данных — минимальное положительное целое число $$$k$$$, удовлетворяющее условиям, или $$$-1$$$, если ни одного подходящего $$$k$$$ не существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
4
1 0 2 3
6
10 7 14 8 3 12
2
0 2
3
1 2 3
6
1 4 6 10 11 12
2
0 1023
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
4
2
-1
-1
1023
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, ответ $$$1$$$, потому что это минимальное положительное целое число и оно удовлетворяет всем условиям.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="a613b0c70b5681b129131c25c2f1322c"/>
<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="8d18d602cf77141b71dd1ccf82b854ddbe4b7f9f"/>
<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='a613b0c70b5681b129131c25c2f1322c'> </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%2F1362%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='a613b0c70b5681b129131c25c2f1322c'/>
<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/1362">Codeforces Round 647 (Div. 2) - Thanks, Algo Muse!</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='a613b0c70b5681b129131c25c2f1322c'/>
<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/1362/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='a613b0c70b5681b129131c25c2f1322c'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640963"/>
<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='a613b0c70b5681b129131c25c2f1322c'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640963"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11023" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11031" resourceName="Codeforces Round #647 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/1362">Задачи</a></li>
<li><a
href="/contest/1362/submit">Отослать</a></li>
<li><a
href="/contest/1362/my">Мои посылки</a></li>
<li><a
href="/contest/1362/status">Статус</a></li>
<li><a
href="/contest/1362/hacks">Взломы</a></li>
<li><a
href="/contest/1362/room/1">Комната</a></li>
<li><a
href="/contest/1362/standings">Положение</a></li>
<li><a
href="/contest/1362/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_0e7831d722bf23c1334a3af2525b354db7747f1c">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Джонни и его хобби</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Среди многочисленных хобби Джонни, есть два, казалось бы, безвредных: применение побитовых операций и прокрадывание в офис его отца. Как это обычно и бывает у маленьких детей, Джонни не подозревает, что комбинирование этих двух занятий может доставить ему много неприятностей.</p><p>На столе его отца хранится множество $$$S$$$, содержащее очень важные числа. В момент, когда Джонни узнал об этом, он решил, что это хорошая идея выбрать <span class="tex-font-style-bf">положительное</span> целое число $$$k$$$ и заменить все элементы $$$s$$$ из множества $$$S$$$ на $$$s \oplus k$$$ ($$$\oplus$$$ обозначает операцию <a href="https://en.wikipedia.org/wiki/Exclusive_or#Computer_science">исключающего или</a>).</p><p>Помогите Джонни выбрать такое $$$k$$$, что его отец не заметит никакой разницы после того, как Джонни закончит играть (т.е. Джонни должен получить такое же множество, какое было изначально). Возможно, что ни одного такого числа не существует. Также, возможно, что существует несколько подходящих чисел. В таком случае, выведите минимальное из них. Обратите внимание, что порядок элементов в множестве не имеет значения, т.е. множество $$$\{1, 2, 3\}$$$ равно множеству $$$\{2, 1, 3\}$$$.</p><p>Формально, требуется найти минимальное положительное целое число $$$k$$$, такое что $$$\{s \oplus k | s \in S\} = S$$$ или сообщить, что ни одного подходящего числа не существует.</p><p>Например, если $$$S = \{1, 3, 4\}$$$ и $$$k = 2$$$, новое множество будет равно $$$\{3, 1, 6\}$$$. Если $$$S = \{0, 1, 2, 3\}$$$ и $$$k = 1$$$, после игры множество останется таким же.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке дано одно целое число $$$t$$$ ($$$1 \leq t \leq 1024$$$) — количество наборов входных данных. В следующих строках даны $$$t$$$ наборов входных данных, каждый из них занимает две строки.</p><p>В первой строке набора входных данных дано одно целое число $$$n$$$ ($$$1 \leq n \leq 1024$$$), обозначающее количество элементов в множестве $$$S$$$. Вторая строка содержит $$$n$$$ <span class="tex-font-style-bf">различных</span> целых чисел $$$s_i$$$ ($$$0 \leq s_i < 1024$$$) — элементы $$$S$$$.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превышает $$$1024$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк, $$$i$$$-я из них должна содержать ответ на $$$i$$$-й набор входных данных — минимальное положительное целое число $$$k$$$, удовлетворяющее условиям, или $$$-1$$$, если ни одного подходящего $$$k$$$ не существует.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
4
1 0 2 3
6
10 7 14 8 3 12
2
0 2
3
1 2 3
6
1 4 6 10 11 12
2
0 1023
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
4
2
-1
-1
1023
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, ответ $$$1$$$, потому что это минимальное положительное целое число и оно удовлетворяет всем условиям.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=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:04: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:'8124a25498ad163d',t:'MTY5NjY2NTg3NC43ODgwMDA='};_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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1200"] | ||
1362C | 1362 | 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>Теперь мальчик смотрит на рейтинги соседних участников, записанные в двоичной системе счисления. Он считает, что чем больше эти рейтинги различаются, тем более нечестно, что эти участники расположены на соседних позициях. Он определяет различие между двумя числами как количество позиций битов, на которых одно из чисел содержит ноль, а другое — единицу (мы считаем, что числа дополнены ведущими нулями до одинаковой длины). Например, различие между числами $$$5 = 101_2$$$ и $$$14 = 1110_2$$$ равно $$$3$$$, так как $$$0101$$$ и $$$1110$$$ отличаются в $$$3$$$ позициях. Джонни определяет нечестность контеста как сумму таких различий для всех пар соседних участников.</p><p>Джонни только что прислал вам последовательность рейтингов и хочет, чтобы вы вычислили нечестность контеста. Вы заметили, что вы получили последовательные целые числа от $$$0$$$ до $$$n$$$. Это странно, но мальчик упорно твердит, что все правильно. Поэтому, помогите ему и вычислите желаемую нечестность для полученной последовательности чисел.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — количество наборов входных данных. Следующие $$$t$$$ строк содержат описание наборов входных данных.</p><p>Первая и единственная строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^{18})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Для каждого набора входных данных, вы должны вывести одну строку, содержащую одно целое число — нечестность контеста, если последовательность рейтингов равна $$$0$$$, $$$1$$$, ..., $$$n - 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
5
7
11
1
2000000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
11
19
1
3999999999987
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для $$$n = 5$$$, мы вычисляем нечестность следующей последовательности (числа от $$$0$$$ до $$$5$$$, записанные в двоичной системе счисления и дополненные ведущими нулями до одинаковой длины): </p><ul> <li> $$$000$$$ </li><li> $$$001$$$ </li><li> $$$010$$$ </li><li> $$$011$$$ </li><li> $$$100$$$ </li><li> $$$101$$$ </li></ul><p>Различия равны $$$1$$$, $$$2$$$, $$$1$$$, $$$3$$$, $$$1$$$, соответственно. Поэтому, нечестность равна $$$1 + 2 + 1 + 3 + 1 = 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="24eef680b89e8a554566befa281832b7"/>
<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="8d18d602cf77141b71dd1ccf82b854ddbe4b7f9f"/>
<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='24eef680b89e8a554566befa281832b7'> </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%2F1362%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='24eef680b89e8a554566befa281832b7'/>
<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/1362">Codeforces Round 647 (Div. 2) - Thanks, Algo Muse!</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='24eef680b89e8a554566befa281832b7'/>
<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/1362/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='24eef680b89e8a554566befa281832b7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640964"/>
<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='24eef680b89e8a554566befa281832b7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640964"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11023" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11031" resourceName="Codeforces Round #647 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/1362">Задачи</a></li>
<li><a
href="/contest/1362/submit">Отослать</a></li>
<li><a
href="/contest/1362/my">Мои посылки</a></li>
<li><a
href="/contest/1362/status">Статус</a></li>
<li><a
href="/contest/1362/hacks">Взломы</a></li>
<li><a
href="/contest/1362/room/1">Комната</a></li>
<li><a
href="/contest/1362/standings">Положение</a></li>
<li><a
href="/contest/1362/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_478d1a8e002f3a4b30d1a8e202c82c4780ca1179">
<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>Теперь мальчик смотрит на рейтинги соседних участников, записанные в двоичной системе счисления. Он считает, что чем больше эти рейтинги различаются, тем более нечестно, что эти участники расположены на соседних позициях. Он определяет различие между двумя числами как количество позиций битов, на которых одно из чисел содержит ноль, а другое — единицу (мы считаем, что числа дополнены ведущими нулями до одинаковой длины). Например, различие между числами $$$5 = 101_2$$$ и $$$14 = 1110_2$$$ равно $$$3$$$, так как $$$0101$$$ и $$$1110$$$ отличаются в $$$3$$$ позициях. Джонни определяет нечестность контеста как сумму таких различий для всех пар соседних участников.</p><p>Джонни только что прислал вам последовательность рейтингов и хочет, чтобы вы вычислили нечестность контеста. Вы заметили, что вы получили последовательные целые числа от $$$0$$$ до $$$n$$$. Это странно, но мальчик упорно твердит, что все правильно. Поэтому, помогите ему и вычислите желаемую нечестность для полученной последовательности чисел.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов входных данных. Первая строка содержит одно целое число $$$t$$$ ($$$1 \leq t \leq 10\,000$$$) — количество наборов входных данных. Следующие $$$t$$$ строк содержат описание наборов входных данных.</p><p>Первая и единственная строка каждого набора входных данных содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 10^{18})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк. Для каждого набора входных данных, вы должны вывести одну строку, содержащую одно целое число — нечестность контеста, если последовательность рейтингов равна $$$0$$$, $$$1$$$, ..., $$$n - 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
5
7
11
1
2000000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
8
11
19
1
3999999999987
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для $$$n = 5$$$, мы вычисляем нечестность следующей последовательности (числа от $$$0$$$ до $$$5$$$, записанные в двоичной системе счисления и дополненные ведущими нулями до одинаковой длины): </p><ul> <li> $$$000$$$ </li><li> $$$001$$$ </li><li> $$$010$$$ </li><li> $$$011$$$ </li><li> $$$100$$$ </li><li> $$$101$$$ </li></ul><p>Различия равны $$$1$$$, $$$2$$$, $$$1$$$, $$$3$$$, $$$1$$$, соответственно. Поэтому, нечестность равна $$$1 + 2 + 1 + 3 + 1 = 8$$$.</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:04: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:'8124a25d1a2a9d37',t:'MTY5NjY2NTg3Ni4wOTgwMDA='};_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", "\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", "\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", "*1400"] | ||
1362D | 1362 | D | ru | D. Джонни и вклад | <div class="problem-statement"><div class="header"><div class="title">D. Джонни и вклад</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Сегодня Джонни хочет увеличить свой вклад. Его план подразумевает написание $$$n$$$ блогов. Один блог покрывает одну тему, но одна тема может быть покрыта несколькими блогами. Также, некоторые блоги связаны друг с другом ссылками. Каждая пара блогов, связанных ссылкой, должна покрывать две разные темы. Потому что иначе читатели могут заметить, что блоги разделены только для того, чтобы набрать больше вклада. Множество блогов и двусторонние ссылки между некоторыми парами из них называются сетью блогов.</p><p>Всего есть $$$n$$$ различных тем, пронумерованных от $$$1$$$ до $$$n$$$, упорядоченных по пониманию Джонни. Структура сети блогов уже приготовлена. Теперь Джонни должен написать все блоги в некотором порядке. Он ленивый, поэтому каждый раз перед написанием блога, он смотрит на все уже написанные соседние блоги (связанные ссылкой с текущим) и выбирает тему с минимальным номером, которая еще не покрыта соседними блогами. Можно заметить, что такая стратегия всегда позволит ему выбрать тему, потому что максимальное количество соседних блогов равно $$$n - 1$$$.</p><p>Например, если уже написанные, соседние с текущим, блоги покрывают темы с номерами $$$1$$$, $$$3$$$, $$$1$$$, $$$5$$$ и $$$2$$$, Джонни выберет тему номер $$$4$$$ для текущего блога, потому что темы номер $$$1$$$, $$$2$$$ и $$$3$$$ уже покрыты соседними блогами, а тема номер $$$4$$$ — нет.</p><p>Как хороший друг, вы провели некоторые исследования и предсказали наилучшую темы для каждого блога. Не могли бы вы сказать Джонни, в каком порядке он должен писать блоги, чтобы в результате его стратегии каждый блог покрывал выбранную вами тему?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ и $$$m$$$ $$$(0 \leq m \leq 5 \cdot 10^5)$$$ — количество блогов и ссылок, соответственно.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$a$$$ и $$$b$$$ ($$$a \neq b$$$; $$$1 \leq a, b \leq n$$$), которые означают, что в сети блогов есть ссылка между блогами с номерами $$$a$$$ и $$$b$$$. Гарантируется, что граф сети блогов не содержит кратных ребер.</p><p>Последняя строка содержит $$$n$$$ целых чисел $$$t_1, t_2, \ldots, t_n$$$, $$$i$$$-е из них обозначает желаемую тему для $$$i$$$-го блога ($$$1 \le t_i \le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если решение не существует, выведите $$$-1$$$. Иначе, выведите $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ $$$(1 \leq p_i \leq 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 3
1 2
2 3
3 1
2 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1 3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 3
1 2
2 3
3 1
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 3
1 2
2 3
4 5
2 1 2 2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 5 1 3 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, Джонни начинает с написания блога номер $$$2$$$, у него пока еще нет написанных соседних блогов, поэтому Джонни выбирает тему номер один. Потом он пишет блог номер $$$1$$$, у него есть ссылка на уже написанный второй блог, поэтому Джонни выбирает вторую тему. Наконец, он пишет блог номер $$$3$$$, у него есть ссылки на блоги номер $$$1$$$ и $$$2$$$, поэтому Джонни выбирает третью тему.</p><p>Второй пример: Не существует ни одной перестановки, удовлетворяющей всем условиям.</p><p>Третий пример: Сначала Джонни пишет блог номер $$$2$$$, который получает тему $$$1$$$. Затем, он пишет блог $$$5$$$, который тоже получает тему $$$1$$$, потому из него нет ссылки на единственный уже написанный блог (номер $$$2$$$). Затем, он пишет блог $$$1$$$, он получает тему $$$2$$$, потому что из него есть ссылка на блог $$$2$$$ с темой $$$1$$$. Затем, он пишет блог $$$3$$$, из него есть ссылка на блог $$$2$$$, поэтому он получает тему $$$2$$$. Наконец, он пишет блог $$$4$$$, из него есть ссылка на блог $$$5$$$, поэтому он получает тему $$$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="fde3b9192b56827bc1a6c3905d26ae49"/>
<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="8d18d602cf77141b71dd1ccf82b854ddbe4b7f9f"/>
<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='fde3b9192b56827bc1a6c3905d26ae49'> </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%2F1362%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='fde3b9192b56827bc1a6c3905d26ae49'/>
<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/1362">Codeforces Round 647 (Div. 2) - Thanks, Algo Muse!</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='fde3b9192b56827bc1a6c3905d26ae49'/>
<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/1362/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="Сложность">
*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='fde3b9192b56827bc1a6c3905d26ae49'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640965"/>
<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='fde3b9192b56827bc1a6c3905d26ae49'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640965"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11023" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11031" resourceName="Codeforces Round #647 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/1362">Задачи</a></li>
<li><a
href="/contest/1362/submit">Отослать</a></li>
<li><a
href="/contest/1362/my">Мои посылки</a></li>
<li><a
href="/contest/1362/status">Статус</a></li>
<li><a
href="/contest/1362/hacks">Взломы</a></li>
<li><a
href="/contest/1362/room/1">Комната</a></li>
<li><a
href="/contest/1362/standings">Положение</a></li>
<li><a
href="/contest/1362/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_f7d51287be34bd62acb534985b6c043672522ed4">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Джонни и вклад</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Сегодня Джонни хочет увеличить свой вклад. Его план подразумевает написание $$$n$$$ блогов. Один блог покрывает одну тему, но одна тема может быть покрыта несколькими блогами. Также, некоторые блоги связаны друг с другом ссылками. Каждая пара блогов, связанных ссылкой, должна покрывать две разные темы. Потому что иначе читатели могут заметить, что блоги разделены только для того, чтобы набрать больше вклада. Множество блогов и двусторонние ссылки между некоторыми парами из них называются сетью блогов.</p><p>Всего есть $$$n$$$ различных тем, пронумерованных от $$$1$$$ до $$$n$$$, упорядоченных по пониманию Джонни. Структура сети блогов уже приготовлена. Теперь Джонни должен написать все блоги в некотором порядке. Он ленивый, поэтому каждый раз перед написанием блога, он смотрит на все уже написанные соседние блоги (связанные ссылкой с текущим) и выбирает тему с минимальным номером, которая еще не покрыта соседними блогами. Можно заметить, что такая стратегия всегда позволит ему выбрать тему, потому что максимальное количество соседних блогов равно $$$n - 1$$$.</p><p>Например, если уже написанные, соседние с текущим, блоги покрывают темы с номерами $$$1$$$, $$$3$$$, $$$1$$$, $$$5$$$ и $$$2$$$, Джонни выберет тему номер $$$4$$$ для текущего блога, потому что темы номер $$$1$$$, $$$2$$$ и $$$3$$$ уже покрыты соседними блогами, а тема номер $$$4$$$ — нет.</p><p>Как хороший друг, вы провели некоторые исследования и предсказали наилучшую темы для каждого блога. Не могли бы вы сказать Джонни, в каком порядке он должен писать блоги, чтобы в результате его стратегии каждый блог покрывал выбранную вами тему?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ и $$$m$$$ $$$(0 \leq m \leq 5 \cdot 10^5)$$$ — количество блогов и ссылок, соответственно.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$a$$$ и $$$b$$$ ($$$a \neq b$$$; $$$1 \leq a, b \leq n$$$), которые означают, что в сети блогов есть ссылка между блогами с номерами $$$a$$$ и $$$b$$$. Гарантируется, что граф сети блогов не содержит кратных ребер.</p><p>Последняя строка содержит $$$n$$$ целых чисел $$$t_1, t_2, \ldots, t_n$$$, $$$i$$$-е из них обозначает желаемую тему для $$$i$$$-го блога ($$$1 \le t_i \le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если решение не существует, выведите $$$-1$$$. Иначе, выведите $$$n$$$ различных целых чисел $$$p_1, p_2, \ldots, p_n$$$ $$$(1 \leq p_i \leq 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 3
1 2
2 3
3 1
2 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1 3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 3
1 2
2 3
3 1
1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 3
1 2
2 3
4 5
2 1 2 2 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 5 1 3 4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, Джонни начинает с написания блога номер $$$2$$$, у него пока еще нет написанных соседних блогов, поэтому Джонни выбирает тему номер один. Потом он пишет блог номер $$$1$$$, у него есть ссылка на уже написанный второй блог, поэтому Джонни выбирает вторую тему. Наконец, он пишет блог номер $$$3$$$, у него есть ссылки на блоги номер $$$1$$$ и $$$2$$$, поэтому Джонни выбирает третью тему.</p><p>Второй пример: Не существует ни одной перестановки, удовлетворяющей всем условиям.</p><p>Третий пример: Сначала Джонни пишет блог номер $$$2$$$, который получает тему $$$1$$$. Затем, он пишет блог $$$5$$$, который тоже получает тему $$$1$$$, потому из него нет ссылки на единственный уже написанный блог (номер $$$2$$$). Затем, он пишет блог $$$1$$$, он получает тему $$$2$$$, потому что из него есть ссылка на блог $$$2$$$ с темой $$$1$$$. Затем, он пишет блог $$$3$$$, из него есть ссылка на блог $$$2$$$, поэтому он получает тему $$$2$$$. Наконец, он пишет блог $$$4$$$, из него есть ссылка на блог $$$5$$$, поэтому он получает тему $$$2$$$.</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:04: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:'8124a2654bdc13ba',t:'MTY5NjY2NTg3Ny4zNzIwMDA='};_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\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\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", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1700"] | ||
1362E | 1362 | 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>Мальчик нашел онлайн архив с задачами, разделенными по темам. Он выбрал $$$p^{k_i}$$$ задач из $$$i$$$-й категории ($$$p$$$ — его любимое число). Он хочет решить все эти задачи за две недели (терпение еще слишком сложно для Джонни, поэтому он смотрит только на простые задачи, которые могут быть решены за такой период). Теперь наш будущий гроссмейстер должен решить, какие темы покрыть на первой неделе, а какие на второй. Помогите ему распределить темы таким образом, чтобы нагрузка была равномерной.</p><p>Формально, дано $$$n$$$ чисел $$$p^{k_i}$$$, мальчик хочет разделить их на два непересекающихся набора, минимизировав разность между суммами чисел в наборах. Найдите минимальное значение модуля такой разности. Выведите остаток от деления результата на $$$10^{9}+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов входных данных. Первая строка содержит одно целое число $$$t$$$ $$$(1 \leq t \leq 10^5)$$$ — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. Вторая строка содержит $$$n$$$ целых чисел $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — остаток от деления ответа на $$$1\,000\,000\,007$$$.</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 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
1
146981438
747093407
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вы должны минимизировать модуль разности, а не остаток модуля разности. Например, если минимальная разность равна $$$2$$$, но существует также разбиение, при котором разность равна $$$10^9 + 8$$$, ответ равен $$$2$$$, а не $$$1$$$.</p><p>В первом наборе входных данных числа равны: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$ и $$$8$$$. Мы можем разделить их на два набора: $$${4, 8, 16}$$$ и $$${8, 16}$$$. Тогда модуль разности между суммами чисел в наборах будет равен $$$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="6ef088f49beddcf4dca6f3376c0ea2b2"/>
<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="8d18d602cf77141b71dd1ccf82b854ddbe4b7f9f"/>
<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='6ef088f49beddcf4dca6f3376c0ea2b2'> </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%2F1362%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='6ef088f49beddcf4dca6f3376c0ea2b2'/>
<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/1362">Codeforces Round 647 (Div. 2) - Thanks, Algo Muse!</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='6ef088f49beddcf4dca6f3376c0ea2b2'/>
<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/1362/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="Сложность">
*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='6ef088f49beddcf4dca6f3376c0ea2b2'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640966"/>
<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='6ef088f49beddcf4dca6f3376c0ea2b2'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640966"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11023" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11031" resourceName="Codeforces Round #647 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/1362">Задачи</a></li>
<li><a
href="/contest/1362/submit">Отослать</a></li>
<li><a
href="/contest/1362/my">Мои посылки</a></li>
<li><a
href="/contest/1362/status">Статус</a></li>
<li><a
href="/contest/1362/hacks">Взломы</a></li>
<li><a
href="/contest/1362/room/1">Комната</a></li>
<li><a
href="/contest/1362/standings">Положение</a></li>
<li><a
href="/contest/1362/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_dbd16ccafd7133b09c1e491449e8685777f12672">
<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>Мальчик нашел онлайн архив с задачами, разделенными по темам. Он выбрал $$$p^{k_i}$$$ задач из $$$i$$$-й категории ($$$p$$$ — его любимое число). Он хочет решить все эти задачи за две недели (терпение еще слишком сложно для Джонни, поэтому он смотрит только на простые задачи, которые могут быть решены за такой период). Теперь наш будущий гроссмейстер должен решить, какие темы покрыть на первой неделе, а какие на второй. Помогите ему распределить темы таким образом, чтобы нагрузка была равномерной.</p><p>Формально, дано $$$n$$$ чисел $$$p^{k_i}$$$, мальчик хочет разделить их на два непересекающихся набора, минимизировав разность между суммами чисел в наборах. Найдите минимальное значение модуля такой разности. Выведите остаток от деления результата на $$$10^{9}+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из нескольких наборов входных данных. Первая строка содержит одно целое число $$$t$$$ $$$(1 \leq t \leq 10^5)$$$ — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$p$$$ $$$(1 \leq n, p \leq 10^6)$$$. Вторая строка содержит $$$n$$$ целых чисел $$$k_i$$$ $$$(0 \leq k_i \leq 10^6)$$$.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^6$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — остаток от деления ответа на $$$1\,000\,000\,007$$$.</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 2
2 3 4 4 3
3 1
2 10 1000
4 5
0 1 1 100
1 8
89
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
1
146981438
747093407
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Вы должны минимизировать модуль разности, а не остаток модуля разности. Например, если минимальная разность равна $$$2$$$, но существует также разбиение, при котором разность равна $$$10^9 + 8$$$, ответ равен $$$2$$$, а не $$$1$$$.</p><p>В первом наборе входных данных числа равны: $$$4$$$, $$$8$$$, $$$16$$$, $$$16$$$ и $$$8$$$. Мы можем разделить их на два набора: $$${4, 8, 16}$$$ и $$${8, 16}$$$. Тогда модуль разности между суммами чисел в наборах будет равен $$$4$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=E]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04:38</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a26d4d5f16f4',t:'MTY5NjY2NTg3OC42ODYwMDA='};_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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1900"] | ||
1362F | 1362 | 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>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У младшей сестры Джонни, Меган, недавно был день рождения. Её брат подарил ей коробочку, подписанную как: «Твое прекрасное ожерелье — сделай сама!». Коробочка содержит много частей ожерелья и магический клей.</p><p>Каждая часть ожерелья представляет собой цепочку, соединяющую две жемчужины. Цвет каждой из жемчужин может быть представлен целым неотрицательным числом. Магический клей позволяет Меган склеивать две жемчужины (возможно, из одной части ожерелья) в одну. Красота соединения двух жемчужин цветов $$$u$$$ и $$$v$$$ определяется следующим образом: пусть $$$2^k$$$ — максимальная степень двух, делящая $$$u \oplus v$$$ — <a href="https://en.wikipedia.org/wiki/Exclusive_or#Computer_science">исключающее или</a> $$$u$$$ и $$$v$$$. Тогда красота соединения равна $$$k$$$. Если $$$u = v$$$, вы можете считать, что красота равна $$$20$$$.</p><p>Каждая жемчужина может быть склеена с другой максимум один раз. Склеивание двух частей ожерелья объединяет их. Используя клей несколько раз, Меган может наконец получить свое ожерелье, которое является циклом, сделанным из соединенных последовательно частей ожерелья (так, что каждая жемчужина в ожерелье соединена с ровно одной другой жемчужиной). Красота такого ожерелья равна минимальной красоте соединений в нем. Девочка хочет использовать все доступные части ожерелья, чтобы получить <span class="tex-font-style-bf">ровно одно</span> ожерелье, содержащее <span class="tex-font-style-bf">все части</span>, с максимальной возможной красотой. Помогите ей!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ — количество частей ожерелья в коробочке.</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$a$$$ и $$$b$$$ $$$(0 \leq a, b < 2^{20})$$$, которые обозначают цвета жемчужин из этой части ожерелья. Жемчужины на $$$i$$$-й строке имеют индексы $$$2i - 1$$$ и $$$2i$$$, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Первая строка должна содержать одно целое число $$$b$$$, обозначающее максимальную возможную красоту ожерелья, собранного из всех данных частей.</p><p>Следующая строка должна содержать $$$2n$$$ различных целых чисел $$$p_i$$$ $$$(1 \leq p_i \leq 2n)$$$ — индексы исходных жемчужин в порядке, в котором они должны быть расположены в ожерелье. Индексы жемчужин, принадлежащих одной части, должны быть расположены на соседних позициях в перестановке (поэтому $$$1\,4\,3\,2$$$ не является корректным выводом, а $$$2\,1\,4\,3$$$ и $$$4\,3\,1\,2$$$ являются). Если существует несколько подходящих ответов, вы можете вывести любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
13 11
11 1
3 5
17 1
9 27
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
8 7 9 10 5 6 1 2 3 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
13 11
11 1
3 5
17 1
7 29
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
8 7 10 9 5 6 4 3 2 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
20
2 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере следующие пары жемчужин объединяются: $$$(7, 9)$$$, $$$(10, 5)$$$, $$$(6, 1)$$$, $$$(2, 3)$$$ и $$$(4, 8)$$$. Красота соединений равна: $$$3$$$, $$$3$$$, $$$3$$$, $$$20$$$, $$$20$$$, соответственно.</p><p>Иллюстрация показывает эту конструкцию:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/69d60d8bfa6bc79bd945ddb77b0979b45ae8d7f1.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="f066d76c7f4ced65418b35a78dc2532b"/>
<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="8d18d602cf77141b71dd1ccf82b854ddbe4b7f9f"/>
<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='f066d76c7f4ced65418b35a78dc2532b'> </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%2F1362%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='f066d76c7f4ced65418b35a78dc2532b'/>
<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/1362">Codeforces Round 647 (Div. 2) - Thanks, Algo Muse!</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='f066d76c7f4ced65418b35a78dc2532b'/>
<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/1362/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="Сложность">
*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='f066d76c7f4ced65418b35a78dc2532b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="640967"/>
<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='f066d76c7f4ced65418b35a78dc2532b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="640967"/>
<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/78276" title="Codeforces Round #647 — Thanks, Algo Muse!" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11023" resourceName="Codeforces Round #647 — Thanks, Algo Muse!"
resourceManual="true" src="//codeforces.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/78355" title="Codeforces Round #647 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11031" resourceName="Codeforces Round #647 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/1362">Задачи</a></li>
<li><a
href="/contest/1362/submit">Отослать</a></li>
<li><a
href="/contest/1362/my">Мои посылки</a></li>
<li><a
href="/contest/1362/status">Статус</a></li>
<li><a
href="/contest/1362/hacks">Взломы</a></li>
<li><a
href="/contest/1362/room/1">Комната</a></li>
<li><a
href="/contest/1362/standings">Положение</a></li>
<li><a
href="/contest/1362/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_ac2fc41693816bf081b5d79859fb6cf082fe3fe4">
<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>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У младшей сестры Джонни, Меган, недавно был день рождения. Её брат подарил ей коробочку, подписанную как: «Твое прекрасное ожерелье — сделай сама!». Коробочка содержит много частей ожерелья и магический клей.</p><p>Каждая часть ожерелья представляет собой цепочку, соединяющую две жемчужины. Цвет каждой из жемчужин может быть представлен целым неотрицательным числом. Магический клей позволяет Меган склеивать две жемчужины (возможно, из одной части ожерелья) в одну. Красота соединения двух жемчужин цветов $$$u$$$ и $$$v$$$ определяется следующим образом: пусть $$$2^k$$$ — максимальная степень двух, делящая $$$u \oplus v$$$ — <a href="https://en.wikipedia.org/wiki/Exclusive_or#Computer_science">исключающее или</a> $$$u$$$ и $$$v$$$. Тогда красота соединения равна $$$k$$$. Если $$$u = v$$$, вы можете считать, что красота равна $$$20$$$.</p><p>Каждая жемчужина может быть склеена с другой максимум один раз. Склеивание двух частей ожерелья объединяет их. Используя клей несколько раз, Меган может наконец получить свое ожерелье, которое является циклом, сделанным из соединенных последовательно частей ожерелья (так, что каждая жемчужина в ожерелье соединена с ровно одной другой жемчужиной). Красота такого ожерелья равна минимальной красоте соединений в нем. Девочка хочет использовать все доступные части ожерелья, чтобы получить <span class="tex-font-style-bf">ровно одно</span> ожерелье, содержащее <span class="tex-font-style-bf">все части</span>, с максимальной возможной красотой. Помогите ей!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n$$$ $$$(1 \leq n \leq 5 \cdot 10^5)$$$ — количество частей ожерелья в коробочке.</p><p>Каждая из следующих $$$n$$$ строк содержит два целых числа $$$a$$$ и $$$b$$$ $$$(0 \leq a, b < 2^{20})$$$, которые обозначают цвета жемчужин из этой части ожерелья. Жемчужины на $$$i$$$-й строке имеют индексы $$$2i - 1$$$ и $$$2i$$$, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Первая строка должна содержать одно целое число $$$b$$$, обозначающее максимальную возможную красоту ожерелья, собранного из всех данных частей.</p><p>Следующая строка должна содержать $$$2n$$$ различных целых чисел $$$p_i$$$ $$$(1 \leq p_i \leq 2n)$$$ — индексы исходных жемчужин в порядке, в котором они должны быть расположены в ожерелье. Индексы жемчужин, принадлежащих одной части, должны быть расположены на соседних позициях в перестановке (поэтому $$$1\,4\,3\,2$$$ не является корректным выводом, а $$$2\,1\,4\,3$$$ и $$$4\,3\,1\,2$$$ являются). Если существует несколько подходящих ответов, вы можете вывести любой.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
13 11
11 1
3 5
17 1
9 27
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
8 7 9 10 5 6 1 2 3 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
13 11
11 1
3 5
17 1
7 29
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
8 7 10 9 5 6 4 3 2 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
20
2 1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере следующие пары жемчужин объединяются: $$$(7, 9)$$$, $$$(10, 5)$$$, $$$(6, 1)$$$, $$$(2, 3)$$$ и $$$(4, 8)$$$. Красота соединений равна: $$$3$$$, $$$3$$$, $$$3$$$, $$$20$$$, $$$20$$$, соответственно.</p><p>Иллюстрация показывает эту конструкцию:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/69d60d8bfa6bc79bd945ddb77b0979b45ae8d7f1.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=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:04: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:'8124a275996016e3',t:'MTY5NjY2NTg3OS45OTkwMDA='};_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\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", "*2500"] | ||
1363A | 1363 | 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>У Shubham есть массив $$$a$$$ размера $$$n$$$, и он хочет выбрать из него ровно $$$x$$$ элементов так, чтобы их сумма была нечетной. Эти элементы не обязаны быть последовательными. Элементы массива не обязательно различны.</p><p>Скажите ему, может ли он сделать это.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных содержится одно целое число $$$t$$$ $$$(1\le t \le 100)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$x$$$ $$$(1 \le x \le n \le 1000)$$$ — длину массива и количество элементов, которые нужно выбрать соответственно.</p><p>Следующая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1000)$$$ — элементы массива.</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>» в зависимости от того, можно ли выбрать ровно $$$x$$$ элементов, чтобы их сумма была нечетной.</p><p>Вы можете выводить буквы в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
1 1
999
1 1
1000
2 1
51 50
2 2
51 50
3 3
101 102 103
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
No
Yes
Yes
No
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В $$$1$$$-м наборе входных данных: мы должны выбрать элемент $$$999$$$, и сумма будет нечетной.</p><p>В $$$2$$$-м наборе входных данных: мы должны выбрать элемент $$$1000$$$, поэтому сумма не будет нечетной.</p><p>В $$$3$$$-м наборе входных данных: мы можем выбрать элемент $$$51$$$.</p><p>В $$$4$$$-м наборе входных данных: мы должны выбрать оба элемента $$$50$$$ и $$$51$$$ — так что общая сумма нечетна.</p><p>В $$$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="1fdcf854ef7d5430363ceaabf450136e"/>
<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="4794e63b114ab55d104ae53925a0e99a85c6b6ee"/>
<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='1fdcf854ef7d5430363ceaabf450136e'> </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%2F1363%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='1fdcf854ef7d5430363ceaabf450136e'/>
<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/1363">Codeforces Round 646 (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='1fdcf854ef7d5430363ceaabf450136e'/>
<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/1363/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Перебор">
перебор
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1200
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1fdcf854ef7d5430363ceaabf450136e'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="636623"/>
<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='1fdcf854ef7d5430363ceaabf450136e'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="636623"/>
<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/78132" title="Codeforces Round #646 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10997" resourceName="Codeforces Round #646 (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/78202" title="78202" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12140" resourceName="78202"
resourceManual="true" src="//codeforces.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/1363">Задачи</a></li>
<li><a
href="/contest/1363/submit">Отослать</a></li>
<li><a
href="/contest/1363/my">Мои посылки</a></li>
<li><a
href="/contest/1363/status">Статус</a></li>
<li><a
href="/contest/1363/hacks">Взломы</a></li>
<li><a
href="/contest/1363/room/1">Комната</a></li>
<li><a
href="/contest/1363/standings">Положение</a></li>
<li><a
href="/contest/1363/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_aca33016b65b16cdaf9ef7c46510a66139737c67">
<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>У Shubham есть массив $$$a$$$ размера $$$n$$$, и он хочет выбрать из него ровно $$$x$$$ элементов так, чтобы их сумма была нечетной. Эти элементы не обязаны быть последовательными. Элементы массива не обязательно различны.</p><p>Скажите ему, может ли он сделать это.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных содержится одно целое число $$$t$$$ $$$(1\le t \le 100)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$x$$$ $$$(1 \le x \le n \le 1000)$$$ — длину массива и количество элементов, которые нужно выбрать соответственно.</p><p>Следующая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1000)$$$ — элементы массива.</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>» в зависимости от того, можно ли выбрать ровно $$$x$$$ элементов, чтобы их сумма была нечетной.</p><p>Вы можете выводить буквы в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
1 1
999
1 1
1000
2 1
51 50
2 2
51 50
3 3
101 102 103
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
No
Yes
Yes
No
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В $$$1$$$-м наборе входных данных: мы должны выбрать элемент $$$999$$$, и сумма будет нечетной.</p><p>В $$$2$$$-м наборе входных данных: мы должны выбрать элемент $$$1000$$$, поэтому сумма не будет нечетной.</p><p>В $$$3$$$-м наборе входных данных: мы можем выбрать элемент $$$51$$$.</p><p>В $$$4$$$-м наборе входных данных: мы должны выбрать оба элемента $$$50$$$ и $$$51$$$ — так что общая сумма нечетна.</p><p>В $$$5$$$-м наборе входных данных: мы должны выбрать все элементы — но общая сумма не является нечетной.</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:04: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:'8124a27dbcc57a79',t:'MTY5NjY2NTg4MS4zODAwMDA='};_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", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1200"] | ||
1363B | 1363 | 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>У Shubham есть бинарная строка $$$s$$$. Бинарная строка — это строка, содержащая только символы «<span class="tex-font-style-tt">0</span>» и «<span class="tex-font-style-tt">1</span>».</p><p>Он может выполнить следующую операцию над строкой любое количество раз: </p><ul> <li> Выбрать индекс строки, и поменять символ с этим индексом. Это означает, что если символ был «<span class="tex-font-style-tt">0</span>», он становится «<span class="tex-font-style-tt">1</span>», и наоборот. </li></ul><p>Строка называется хорошей, если она не содержит строк «<span class="tex-font-style-tt">010</span>» или «<span class="tex-font-style-tt">101</span>» в качестве подпоследовательностей — например, «<span class="tex-font-style-tt">1001</span>» содержит «<span class="tex-font-style-tt">101</span>» как подпоследовательность, следовательно, это не хорошая строка, а «<span class="tex-font-style-tt">1000</span>» не содержит ни «<span class="tex-font-style-tt">010</span>» ни «<span class="tex-font-style-tt">101</span>» как подпоследовательностей, поэтому это хорошая строка.</p><p>Какое минимальное количество операций ему придется выполнить, чтобы строка стала хорошей? Можно показать, что с помощью данных операций можно сделать любую строку хорошей.</p><p>Строка $$$a$$$ является подпоследовательностью строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных содержится одно целое число $$$t$$$ $$$(1\le t \le 100)$$$ — количество наборов входных данных.</p><p>Каждая из следующих $$$t$$$ строк содержит бинарную строку $$$s$$$ $$$(1 \le |s| \le 1000)$$$.</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>
7
001
100
101
010
0
1
001100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
1
1
0
0
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В наборах входных данных $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ строки уже являются хорошими — поэтому никаких операций не требуется.</p><p>Для набора $$$3$$$: «<span class="tex-font-style-tt">001</span>» можно получить, поменяв первый символ, и это один из возможных способов получить хорошую строку.</p><p>Для набора $$$4$$$: «<span class="tex-font-style-tt">000</span>» можно получить, поменяв второй символ, и это один из возможных способов получить хорошую строку.</p><p>Для набора $$$7$$$: «<span class="tex-font-style-tt">000000</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="aff19630e092ad53fd6355110aee6aa7"/>
<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="4794e63b114ab55d104ae53925a0e99a85c6b6ee"/>
<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='aff19630e092ad53fd6355110aee6aa7'> </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%2F1363%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='aff19630e092ad53fd6355110aee6aa7'/>
<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/1363">Codeforces Round 646 (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='aff19630e092ad53fd6355110aee6aa7'/>
<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/1363/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*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='aff19630e092ad53fd6355110aee6aa7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="636624"/>
<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='aff19630e092ad53fd6355110aee6aa7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="636624"/>
<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/78132" title="Codeforces Round #646 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10997" resourceName="Codeforces Round #646 (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/78202" title="78202" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12140" resourceName="78202"
resourceManual="true" src="//codeforces.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/1363">Задачи</a></li>
<li><a
href="/contest/1363/submit">Отослать</a></li>
<li><a
href="/contest/1363/my">Мои посылки</a></li>
<li><a
href="/contest/1363/status">Статус</a></li>
<li><a
href="/contest/1363/hacks">Взломы</a></li>
<li><a
href="/contest/1363/room/1">Комната</a></li>
<li><a
href="/contest/1363/standings">Положение</a></li>
<li><a
href="/contest/1363/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_b579861ebaf8f14730d4dac1e58c5edb598503f1">
<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>У Shubham есть бинарная строка $$$s$$$. Бинарная строка — это строка, содержащая только символы «<span class="tex-font-style-tt">0</span>» и «<span class="tex-font-style-tt">1</span>».</p><p>Он может выполнить следующую операцию над строкой любое количество раз: </p><ul> <li> Выбрать индекс строки, и поменять символ с этим индексом. Это означает, что если символ был «<span class="tex-font-style-tt">0</span>», он становится «<span class="tex-font-style-tt">1</span>», и наоборот. </li></ul><p>Строка называется хорошей, если она не содержит строк «<span class="tex-font-style-tt">010</span>» или «<span class="tex-font-style-tt">101</span>» в качестве подпоследовательностей — например, «<span class="tex-font-style-tt">1001</span>» содержит «<span class="tex-font-style-tt">101</span>» как подпоследовательность, следовательно, это не хорошая строка, а «<span class="tex-font-style-tt">1000</span>» не содержит ни «<span class="tex-font-style-tt">010</span>» ни «<span class="tex-font-style-tt">101</span>» как подпоследовательностей, поэтому это хорошая строка.</p><p>Какое минимальное количество операций ему придется выполнить, чтобы строка стала хорошей? Можно показать, что с помощью данных операций можно сделать любую строку хорошей.</p><p>Строка $$$a$$$ является подпоследовательностью строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных содержится одно целое число $$$t$$$ $$$(1\le t \le 100)$$$ — количество наборов входных данных.</p><p>Каждая из следующих $$$t$$$ строк содержит бинарную строку $$$s$$$ $$$(1 \le |s| \le 1000)$$$.</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>
7
001
100
101
010
0
1
001100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
1
1
0
0
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В наборах входных данных $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ строки уже являются хорошими — поэтому никаких операций не требуется.</p><p>Для набора $$$3$$$: «<span class="tex-font-style-tt">001</span>» можно получить, поменяв первый символ, и это один из возможных способов получить хорошую строку.</p><p>Для набора $$$4$$$: «<span class="tex-font-style-tt">000</span>» можно получить, поменяв второй символ, и это один из возможных способов получить хорошую строку.</p><p>Для набора $$$7$$$: «<span class="tex-font-style-tt">000000</span>» можно получить, поменяв третий и четвертый символы, и это один из возможных способов получить хорошую строку.</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:04:42</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a2865a6a16ab',t:'MTY5NjY2NTg4Mi43MTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1400"] | ||
1363C | 1363 | 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>Ayush и Ashish играют в игру на некорневом дереве, состоящем из $$$n$$$ вершин, пронумерованных от $$$1$$$ до $$$n$$$. Игроки делают следующий ход по очереди: </p><ul> <li> Выберите любой лист в дереве и удалите его вместе со всеми ребрами, для которых этот лист является одним из концов. Лист — это вершина со степенью, не превосходящей $$$1$$$. </li></ul><p>Дерево — это связный неориентированный граф без циклов.</p><p>Дана специальная вершина с номером $$$x$$$. Игрок, который удаляет эту вершину, выигрывает игру.</p><p>Ayush ходит первым. Определите победителя игры, если каждый игрок играет оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных содержится одно целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$x$$$ $$$(1\leq n \leq 1000, 1 \leq x \leq n)$$$ — количество вершин в дереве и специальную вершину, соответственно.</p><p>Каждая из следующих $$$n-1$$$ строк содержит два целых числа $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, что означает, что между вершинами $$$u$$$ и $$$v$$$ есть ребро.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если побеждает Ayush, выведите "<span class="tex-font-style-tt">Ayush</span>", иначе выведите "<span class="tex-font-style-tt">Ashish</span>" (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1
3 1
2 1
3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Ashish
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
3 2
1 2
1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Ayush
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Ayush может удалить только вершину $$$2$$$ или $$$3$$$, после чего вершина $$$1$$$ становится листом, и Ashish может удалить ее в свою очередь.</p><p>Во втором наборе входных данных Ayush может удалить вершину $$$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="fc88270beec70084dcbe53b8405c73a5"/>
<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="4794e63b114ab55d104ae53925a0e99a85c6b6ee"/>
<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='fc88270beec70084dcbe53b8405c73a5'> </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%2F1363%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='fc88270beec70084dcbe53b8405c73a5'/>
<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/1363">Codeforces Round 646 (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='fc88270beec70084dcbe53b8405c73a5'/>
<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/1363/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='fc88270beec70084dcbe53b8405c73a5'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="636625"/>
<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='fc88270beec70084dcbe53b8405c73a5'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="636625"/>
<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/78132" title="Codeforces Round #646 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10997" resourceName="Codeforces Round #646 (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/78202" title="78202" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12140" resourceName="78202"
resourceManual="true" src="//codeforces.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/1363">Задачи</a></li>
<li><a
href="/contest/1363/submit">Отослать</a></li>
<li><a
href="/contest/1363/my">Мои посылки</a></li>
<li><a
href="/contest/1363/status">Статус</a></li>
<li><a
href="/contest/1363/hacks">Взломы</a></li>
<li><a
href="/contest/1363/room/1">Комната</a></li>
<li><a
href="/contest/1363/standings">Положение</a></li>
<li><a
href="/contest/1363/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_df95f1eb5d4d296166f0fc73f4d3fde4cc9253f4">
<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>Ayush и Ashish играют в игру на некорневом дереве, состоящем из $$$n$$$ вершин, пронумерованных от $$$1$$$ до $$$n$$$. Игроки делают следующий ход по очереди: </p><ul> <li> Выберите любой лист в дереве и удалите его вместе со всеми ребрами, для которых этот лист является одним из концов. Лист — это вершина со степенью, не превосходящей $$$1$$$. </li></ul><p>Дерево — это связный неориентированный граф без циклов.</p><p>Дана специальная вершина с номером $$$x$$$. Игрок, который удаляет эту вершину, выигрывает игру.</p><p>Ayush ходит первым. Определите победителя игры, если каждый игрок играет оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных содержится одно целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$x$$$ $$$(1\leq n \leq 1000, 1 \leq x \leq n)$$$ — количество вершин в дереве и специальную вершину, соответственно.</p><p>Каждая из следующих $$$n-1$$$ строк содержит два целых числа $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, что означает, что между вершинами $$$u$$$ и $$$v$$$ есть ребро.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если побеждает Ayush, выведите "<span class="tex-font-style-tt">Ayush</span>", иначе выведите "<span class="tex-font-style-tt">Ashish</span>" (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1
3 1
2 1
3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Ashish
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
3 2
1 2
1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Ayush
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Ayush может удалить только вершину $$$2$$$ или $$$3$$$, после чего вершина $$$1$$$ становится листом, и Ashish может удалить ее в свою очередь.</p><p>Во втором наборе входных данных Ayush может удалить вершину $$$2$$$ на самом первом шаге.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04: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:'8124a28eaeb95ab2',t:'MTY5NjY2NTg4NC4xMjUwMDA='};_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", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0438\u0433\u0440\u044b", "*1600"] | ||
1363D | 1363 | 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><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Ayush устал запоминать пароль от своего замка и разработал новую схему для установки своего пароля. У замка есть $$$k$$$ позиций, где каждая позиция может содержать целые числа от $$$1$$$ до $$$n$$$. Пароль $$$P$$$ представляет собой последовательность из $$$k$$$ целых чисел, каждое из которых находится в диапазоне $$$[1, n]$$$, $$$i$$$-й элемент которой входит в $$$i$$$-ю позицию замка.</p><p>Чтобы установить пароль для своего замка, Ayush придумывает массив $$$A$$$ из $$$n$$$ целых чисел в диапазоне $$$[1, n]$$$ (не обязательно различных). Затем он выбирает $$$k$$$ <span class="tex-font-style-bf">непустых попарно непересекающихся</span> подмножеств индексов $$$S_1, S_2, ..., S_k$$$ $$$(S_i \underset{i \neq j} \cap S_j = \emptyset)$$$ и устанавливает свой пароль как $$$P_i = \max\limits_{j \notin S_i} A[j]$$$. Другими словами, $$$i$$$-я позиция пароля равна максимуму по всем элементам $$$A$$$, индексы которых не принадлежат $$$S_i$$$.</p><p>Вам даны подмножества индексов, выбранных Ayush. Вам нужно угадать пароль. Чтобы сделать запрос, вы можете выбрать непустое подмножество индексов массива и узнать максимум по всем элементам массива с индексами в этом подмножестве. <span class="tex-font-style-bf">Вы можете задать не более 12 запросов</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа: $$$n$$$ и $$$k$$$ $$$(2 \leq n \leq 1000, 1 \leq k \leq n)$$$ — размер массива и количество подмножеств соответственно. Далее следуют $$$k$$$ строк. $$$i$$$-я строка содержит целое число $$$c$$$ $$$(1 \leq c \lt n)$$$ — размер подмножества $$$S_i$$$, за которым следуют $$$c$$$ попарно различных целых чисел в диапазоне $$$[1, n]$$$ — индексы, принадлежащие подмножеству $$$S_i$$$.</p><p><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">? c</span>" (без кавычек), где $$$c$$$ $$$(1 \leq c \leq n)$$$ обозначает размер подмножества запрашиваемых индексов, после чего выведите через пробел $$$c$$$ <span class="tex-font-style-bf">различных</span> целых чисел в диапазоне $$$[1, n]$$$ — индексы, о которых вы хотите задать запрос. </li></ul><p>Для каждого запроса вы получите целое число $$$x$$$ — максимальное значение в массиве среди элементов с запрошенными индексами. Если подмножество запрашиваемых индексов недопустимо или вы превысили количество запросов (например, один из индексов больше, чем $$$n$$$), то вы получите $$$x = -1$$$. В этом случае вы должны немедленно прекратить программу.</p><p>Когда вы угадали пароль, выведите одну строку "<span class="tex-font-style-tt">!</span>" (Без кавычек), за которой через пробел следуют $$$k$$$ целых чисел — позиции пароля.</p><p>Угадывание пароля <span class="tex-font-style-bf">не</span> учитывается при подсчете количества запросов.</p><p>После этого вы должны прочитать строку. Если вы угадаете пароль правильно, вы получите строку "<span class="tex-font-style-tt">Correct</span>". В этом случае вам следует продолжить решение оставшихся наборов входных данных. Если предполагаемый пароль неверен, вы получите строку "<span class="tex-font-style-tt">Incorrect</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>В первой строке должно содержаться одно целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных должна содержать два целых числа: $$$n$$$ и $$$k$$$ $$$(2 \leq n \leq 1000, 1 \leq k \leq n)$$$ — размер массива и количество подмножеств соответственно. Следующая строка должна состоять из $$$n$$$ целых чисел в диапазоне $$$[1, n]$$$ — массива $$$A$$$. Далее должны следовать $$$k$$$ строк. $$$i$$$-я строка должна содержать целое число $$$c$$$ $$$(1 \leq c \lt n)$$$ — размер подмножества $$$S_i$$$, за которым должны следовать $$$c$$$ различных целых чисел в диапазоне $$$[1, n]$$$ — индексы, принадлежащие подмножеству $$$S_i$$$.</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>
1
4 2
2 1 3
2 2 4
1
2
3
4
Correct</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 1
? 1 2
? 1 3
? 1 4
! 4 3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Массив $$$A$$$ в примере равен $$$[1, 2, 3, 4]$$$. Длина пароля составляет $$$2$$$. Первый элемент пароля — это максимум из $$$A[2]$$$, $$$A[4]$$$ (поскольку первое подмножество содержит индексы $$$1$$$ и $$$3$$$, мы берем максимум по остальным индексам). Второй элемент пароля — это максимум из $$$A[1]$$$, $$$A[3]$$$ (поскольку второе подмножество содержит индексы $$$2$$$, $$$4$$$).</p><p><span class="tex-font-style-bf">Не забудьте</span> считать строку "<span class="tex-font-style-tt">Correct</span>" / "<span class="tex-font-style-tt">Incorrect</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="268fbc6f158534d1ed9c262fbefbba4f"/>
<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="4794e63b114ab55d104ae53925a0e99a85c6b6ee"/>
<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='268fbc6f158534d1ed9c262fbefbba4f'> </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%2F1363%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='268fbc6f158534d1ed9c262fbefbba4f'/>
<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/1363">Codeforces Round 646 (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='268fbc6f158534d1ed9c262fbefbba4f'/>
<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/1363/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='268fbc6f158534d1ed9c262fbefbba4f'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="636626"/>
<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='268fbc6f158534d1ed9c262fbefbba4f'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="636626"/>
<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/78132" title="Codeforces Round #646 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10997" resourceName="Codeforces Round #646 (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/78202" title="78202" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12140" resourceName="78202"
resourceManual="true" src="//codeforces.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/1363">Задачи</a></li>
<li><a
href="/contest/1363/submit">Отослать</a></li>
<li><a
href="/contest/1363/my">Мои посылки</a></li>
<li><a
href="/contest/1363/status">Статус</a></li>
<li><a
href="/contest/1363/hacks">Взломы</a></li>
<li><a
href="/contest/1363/room/1">Комната</a></li>
<li><a
href="/contest/1363/standings">Положение</a></li>
<li><a
href="/contest/1363/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_ee24f76247ef896580ce6814cbe49f9fb691b87f">
<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><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Ayush устал запоминать пароль от своего замка и разработал новую схему для установки своего пароля. У замка есть $$$k$$$ позиций, где каждая позиция может содержать целые числа от $$$1$$$ до $$$n$$$. Пароль $$$P$$$ представляет собой последовательность из $$$k$$$ целых чисел, каждое из которых находится в диапазоне $$$[1, n]$$$, $$$i$$$-й элемент которой входит в $$$i$$$-ю позицию замка.</p><p>Чтобы установить пароль для своего замка, Ayush придумывает массив $$$A$$$ из $$$n$$$ целых чисел в диапазоне $$$[1, n]$$$ (не обязательно различных). Затем он выбирает $$$k$$$ <span class="tex-font-style-bf">непустых попарно непересекающихся</span> подмножеств индексов $$$S_1, S_2, ..., S_k$$$ $$$(S_i \underset{i \neq j} \cap S_j = \emptyset)$$$ и устанавливает свой пароль как $$$P_i = \max\limits_{j \notin S_i} A[j]$$$. Другими словами, $$$i$$$-я позиция пароля равна максимуму по всем элементам $$$A$$$, индексы которых не принадлежат $$$S_i$$$.</p><p>Вам даны подмножества индексов, выбранных Ayush. Вам нужно угадать пароль. Чтобы сделать запрос, вы можете выбрать непустое подмножество индексов массива и узнать максимум по всем элементам массива с индексами в этом подмножестве. <span class="tex-font-style-bf">Вы можете задать не более 12 запросов</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке содержится одно целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит два целых числа: $$$n$$$ и $$$k$$$ $$$(2 \leq n \leq 1000, 1 \leq k \leq n)$$$ — размер массива и количество подмножеств соответственно. Далее следуют $$$k$$$ строк. $$$i$$$-я строка содержит целое число $$$c$$$ $$$(1 \leq c \lt n)$$$ — размер подмножества $$$S_i$$$, за которым следуют $$$c$$$ попарно различных целых чисел в диапазоне $$$[1, n]$$$ — индексы, принадлежащие подмножеству $$$S_i$$$.</p><p><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">? c</span>" (без кавычек), где $$$c$$$ $$$(1 \leq c \leq n)$$$ обозначает размер подмножества запрашиваемых индексов, после чего выведите через пробел $$$c$$$ <span class="tex-font-style-bf">различных</span> целых чисел в диапазоне $$$[1, n]$$$ — индексы, о которых вы хотите задать запрос. </li></ul><p>Для каждого запроса вы получите целое число $$$x$$$ — максимальное значение в массиве среди элементов с запрошенными индексами. Если подмножество запрашиваемых индексов недопустимо или вы превысили количество запросов (например, один из индексов больше, чем $$$n$$$), то вы получите $$$x = -1$$$. В этом случае вы должны немедленно прекратить программу.</p><p>Когда вы угадали пароль, выведите одну строку "<span class="tex-font-style-tt">!</span>" (Без кавычек), за которой через пробел следуют $$$k$$$ целых чисел — позиции пароля.</p><p>Угадывание пароля <span class="tex-font-style-bf">не</span> учитывается при подсчете количества запросов.</p><p>После этого вы должны прочитать строку. Если вы угадаете пароль правильно, вы получите строку "<span class="tex-font-style-tt">Correct</span>". В этом случае вам следует продолжить решение оставшихся наборов входных данных. Если предполагаемый пароль неверен, вы получите строку "<span class="tex-font-style-tt">Incorrect</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>В первой строке должно содержаться одно целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных.</p><p>Первая строка каждого набора входных данных должна содержать два целых числа: $$$n$$$ и $$$k$$$ $$$(2 \leq n \leq 1000, 1 \leq k \leq n)$$$ — размер массива и количество подмножеств соответственно. Следующая строка должна состоять из $$$n$$$ целых чисел в диапазоне $$$[1, n]$$$ — массива $$$A$$$. Далее должны следовать $$$k$$$ строк. $$$i$$$-я строка должна содержать целое число $$$c$$$ $$$(1 \leq c \lt n)$$$ — размер подмножества $$$S_i$$$, за которым должны следовать $$$c$$$ различных целых чисел в диапазоне $$$[1, n]$$$ — индексы, принадлежащие подмножеству $$$S_i$$$.</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>
1
4 2
2 1 3
2 2 4
1
2
3
4
Correct</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 1
? 1 2
? 1 3
? 1 4
! 4 3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Массив $$$A$$$ в примере равен $$$[1, 2, 3, 4]$$$. Длина пароля составляет $$$2$$$. Первый элемент пароля — это максимум из $$$A[2]$$$, $$$A[4]$$$ (поскольку первое подмножество содержит индексы $$$1$$$ и $$$3$$$, мы берем максимум по остальным индексам). Второй элемент пароля — это максимум из $$$A[1]$$$, $$$A[3]$$$ (поскольку второе подмножество содержит индексы $$$2$$$, $$$4$$$).</p><p><span class="tex-font-style-bf">Не забудьте</span> считать строку "<span class="tex-font-style-tt">Correct</span>" / "<span class="tex-font-style-tt">Incorrect</span>" после угадывания пароля.</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:04: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:'8124a2978b714985',t:'MTY5NjY2NTg4NS41NTAwMDA='};_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\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2100"] | ||
1363E | 1363 | 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>У Ashish есть дерево, состоящее из $$$n$$$ вершин, пронумерованных от $$$1$$$ до $$$n$$$, с корнем в вершине $$$1$$$. $$$i$$$-я вершина дерева имеет стоимость $$$a_i$$$, и в ней записана бинарная цифра $$$b_i$$$. Ashish хочет, чтобы в конце в $$$i$$$-й вершине была записана бинарная цифра $$$c_i$$$.</p><p>Для этого, он может выполнить следующую операцию любое количество раз: </p><ul> <li> Выберите любые $$$k$$$ вершин из поддерева любой вершины $$$u$$$ и переставьте цифры в этих вершинах так, как пожелаете, за стоимость $$$k \cdot a_u$$$. Здесь он может выбрать $$$k$$$ в диапазоне от $$$1$$$ до размера поддерева $$$u$$$. </li></ul><p>Он хочет выполнить операции так, чтобы у каждой вершины в итоге оказалась цифра, соответствующая желаемой цифре для этой вершины.</p><p>Помогите ему найти минимальную общую стоимость, за которую можно сделать так, чтобы после проведения всех операций для каждого $$$u$$$ в вершине $$$u$$$ была записана цифра $$$c_u$$$, или определить, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$, обозначающее количество вершин в дереве.</p><p>$$$i$$$-я из следующих $$$n$$$ строк содержит 3 разделенных пробелом целых числа $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — стоимость $$$i$$$-й вершины, ее начальная цифра и желаемая цифра.</p><p>Каждая из следующих строк $$$n - 1$$$ содержит два целых числа $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, что означает, что между вершинами $$$u$$$ и $$$v$$$ в дереве есть ребро.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальную общую стоимость, за которую можно сделать так, чтобы в каждой вершине была записана желаемая цифра для этой вершины, или $$$-1$$$, если сделать это невозможно.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
10000 0 1
2000 1 0
300 0 1
40 0 0
1 1 0
1 2
2 3
2 4
1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
24000</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
109 0 1
205 0 1
1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево, соответствующие примерам $$$1$$$ и $$$2$$$:</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/02ed56cecf6dea5880ad08c321cf503b04888bd7.png" style="max-width: 100.0%;max-height: 100.0%;"/></center><p>В примере $$$1$$$ мы можем выбрать вершину $$$1$$$ и $$$k = 4$$$ за стоимость $$$4 \times 1$$$ = $$$4$$$ и выбрать вершины $$${1, 2, 3, 5}$$$, переставить их цифры и получить желаемые цифры в каждой позиции.</p><p>В примере $$$2$$$ мы можем выбрать вершину $$$1$$$ и $$$k = 2$$$ за стоимость $$$10000 \times 2$$$, выбрать вершины $$${1, 5}$$$, обменять их цифры, после чего аналогичным образом выбрать вершину $$$2$$$ и $$$k = 2$$$ за стоимость $$$2000 \times 2$$$ и вершины $$${2, 3}$$$, обменять их цифры, чтобы получить нужные цифры в каждой позиции.</p><p>В примере $$$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="c262345f9198f965a842b135a54f0e35"/>
<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="4794e63b114ab55d104ae53925a0e99a85c6b6ee"/>
<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='c262345f9198f965a842b135a54f0e35'> </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%2F1363%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='c262345f9198f965a842b135a54f0e35'/>
<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/1363">Codeforces Round 646 (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='c262345f9198f965a842b135a54f0e35'/>
<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/1363/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='c262345f9198f965a842b135a54f0e35'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="636627"/>
<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='c262345f9198f965a842b135a54f0e35'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="636627"/>
<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/78132" title="Codeforces Round #646 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10997" resourceName="Codeforces Round #646 (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/78202" title="78202" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12140" resourceName="78202"
resourceManual="true" src="//codeforces.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/1363">Задачи</a></li>
<li><a
href="/contest/1363/submit">Отослать</a></li>
<li><a
href="/contest/1363/my">Мои посылки</a></li>
<li><a
href="/contest/1363/status">Статус</a></li>
<li><a
href="/contest/1363/hacks">Взломы</a></li>
<li><a
href="/contest/1363/room/1">Комната</a></li>
<li><a
href="/contest/1363/standings">Положение</a></li>
<li><a
href="/contest/1363/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_b2bcc395951ea70e0178e9d6ed543645957d65fa">
<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>У Ashish есть дерево, состоящее из $$$n$$$ вершин, пронумерованных от $$$1$$$ до $$$n$$$, с корнем в вершине $$$1$$$. $$$i$$$-я вершина дерева имеет стоимость $$$a_i$$$, и в ней записана бинарная цифра $$$b_i$$$. Ashish хочет, чтобы в конце в $$$i$$$-й вершине была записана бинарная цифра $$$c_i$$$.</p><p>Для этого, он может выполнить следующую операцию любое количество раз: </p><ul> <li> Выберите любые $$$k$$$ вершин из поддерева любой вершины $$$u$$$ и переставьте цифры в этих вершинах так, как пожелаете, за стоимость $$$k \cdot a_u$$$. Здесь он может выбрать $$$k$$$ в диапазоне от $$$1$$$ до размера поддерева $$$u$$$. </li></ul><p>Он хочет выполнить операции так, чтобы у каждой вершины в итоге оказалась цифра, соответствующая желаемой цифре для этой вершины.</p><p>Помогите ему найти минимальную общую стоимость, за которую можно сделать так, чтобы после проведения всех операций для каждого $$$u$$$ в вершине $$$u$$$ была записана цифра $$$c_u$$$, или определить, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$, обозначающее количество вершин в дереве.</p><p>$$$i$$$-я из следующих $$$n$$$ строк содержит 3 разделенных пробелом целых числа $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$ — стоимость $$$i$$$-й вершины, ее начальная цифра и желаемая цифра.</p><p>Каждая из следующих строк $$$n - 1$$$ содержит два целых числа $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, что означает, что между вершинами $$$u$$$ и $$$v$$$ в дереве есть ребро.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальную общую стоимость, за которую можно сделать так, чтобы в каждой вершине была записана желаемая цифра для этой вершины, или $$$-1$$$, если сделать это невозможно.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
1 0 1
20 1 0
300 0 1
4000 0 0
50000 1 0
1 2
2 3
2 4
1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
10000 0 1
2000 1 0
300 0 1
40 0 0
1 1 0
1 2
2 3
2 4
1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
24000</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
109 0 1
205 0 1
1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево, соответствующие примерам $$$1$$$ и $$$2$$$:</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/02ed56cecf6dea5880ad08c321cf503b04888bd7.png" style="max-width: 100.0%;max-height: 100.0%;" /></center><p>В примере $$$1$$$ мы можем выбрать вершину $$$1$$$ и $$$k = 4$$$ за стоимость $$$4 \times 1$$$ = $$$4$$$ и выбрать вершины $$${1, 2, 3, 5}$$$, переставить их цифры и получить желаемые цифры в каждой позиции.</p><p>В примере $$$2$$$ мы можем выбрать вершину $$$1$$$ и $$$k = 2$$$ за стоимость $$$10000 \times 2$$$, выбрать вершины $$${1, 5}$$$, обменять их цифры, после чего аналогичным образом выбрать вершину $$$2$$$ и $$$k = 2$$$ за стоимость $$$2000 \times 2$$$ и вершины $$${2, 3}$$$, обменять их цифры, чтобы получить нужные цифры в каждой позиции.</p><p>В примере $$$3$$$ невозможно получить нужные цифры, потому что среди начальных цифр нет цифры $$$1$$$.</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:04: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:'8124a2a0594c163a',t:'MTY5NjY2NTg4Ni44ODIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\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", "*2000"] | ||
1363F | 1363 | F | ru | F. Вращение подстрок | <div class="problem-statement"><div class="header"><div class="title">F. Вращение подстрок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны две строки $$$s$$$ и $$$t$$$, каждая из которых имеет длину $$$n$$$ и состоит из строчных букв латинского алфавита. Вы хотите сделать $$$s$$$ равной $$$t$$$.</p><p>Вы можете выполнить следующую операцию над $$$s$$$ любое количество раз, чтобы достичь этого — </p><ul> <li> Выберите любую подстроку $$$s$$$ и поверните ее по часовой стрелке один раз, то есть, если выбранная подстрока равна $$$s[l,l+1...r]$$$, то она становится равной $$$s[r,l,l + 1 ... r - 1]$$$. Все остальные символы $$$s$$$ остаются на своих местах.<p>Например, при вращении подстроки $$$[2,4]$$$ строка «<span class="tex-font-style-tt">abcde</span>» становится равной «<span class="tex-font-style-tt">adbce</span>». </p></li></ul><p>Строка $$$a$$$ является подстрокой $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p><p>Найдите минимальное количество операций, необходимых для преобразования $$$s$$$ в $$$t$$$, или определите, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ $$$(1\leq t \leq 2000)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ $$$(1\leq n \leq 2000)$$$ — длину строк.</p><p>Вторая и третья строки содержат строки $$$s$$$ и $$$t$$$ соответственно.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное количество операций для преобразования $$$s$$$ в $$$t$$$. Если невозможно преобразовать $$$s$$$ в $$$t$$$, вместо этого выведите $$$-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
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
1
2
1
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных, поскольку $$$s$$$ и $$$t$$$ равны, вам не нужно применять какие-либо операции.</p><p>Для второго набора входных данных вам нужно применить только одну операцию ко всей строке <span class="tex-font-style-tt">ab</span>, чтобы преобразовать ее в <span class="tex-font-style-tt">ba</span>.</p><p>Для третьего набора входных данных вам нужно только применить одну операцию ко всей строке <span class="tex-font-style-tt">abc</span>, чтобы преобразовать ее в <span class="tex-font-style-tt">cab</span>.</p><p>Для четвертого набора входных данных вам нужно применить операцию дважды: сначала для всей строки <span class="tex-font-style-tt">abc</span>, чтобы преобразовать ее в <span class="tex-font-style-tt">cab</span>, а затем для подстроки длины $$$2$$$, начинающейся со второго символа для преобразования ее в <span class="tex-font-style-tt">cba</span>.</p><p>Для пятого набора входных данных вам нужно применить только одну операцию ко всей строке <span class="tex-font-style-tt">abab</span>, чтобы преобразовать ее в <span class="tex-font-style-tt">baba</span>.</p><p>Для шестого набора входных данных превратить строку $$$s$$$ в строку $$$t$$$ не является возможным.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="367513406e19f932f7bf9bd1af323b5c"/>
<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="4794e63b114ab55d104ae53925a0e99a85c6b6ee"/>
<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='367513406e19f932f7bf9bd1af323b5c'> </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%2F1363%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='367513406e19f932f7bf9bd1af323b5c'/>
<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/1363">Codeforces Round 646 (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='367513406e19f932f7bf9bd1af323b5c'/>
<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/1363/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*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='367513406e19f932f7bf9bd1af323b5c'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="636628"/>
<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='367513406e19f932f7bf9bd1af323b5c'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="636628"/>
<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/78132" title="Codeforces Round #646 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="10997" resourceName="Codeforces Round #646 (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/78202" title="78202" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12140" resourceName="78202"
resourceManual="true" src="//codeforces.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/1363">Задачи</a></li>
<li><a
href="/contest/1363/submit">Отослать</a></li>
<li><a
href="/contest/1363/my">Мои посылки</a></li>
<li><a
href="/contest/1363/status">Статус</a></li>
<li><a
href="/contest/1363/hacks">Взломы</a></li>
<li><a
href="/contest/1363/room/1">Комната</a></li>
<li><a
href="/contest/1363/standings">Положение</a></li>
<li><a
href="/contest/1363/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_788c0710d8f7999318c0bbf2a6b4b4cde6036177">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Вращение подстрок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны две строки $$$s$$$ и $$$t$$$, каждая из которых имеет длину $$$n$$$ и состоит из строчных букв латинского алфавита. Вы хотите сделать $$$s$$$ равной $$$t$$$.</p><p>Вы можете выполнить следующую операцию над $$$s$$$ любое количество раз, чтобы достичь этого — </p><ul> <li> Выберите любую подстроку $$$s$$$ и поверните ее по часовой стрелке один раз, то есть, если выбранная подстрока равна $$$s[l,l+1...r]$$$, то она становится равной $$$s[r,l,l + 1 ... r - 1]$$$. Все остальные символы $$$s$$$ остаются на своих местах.<p>Например, при вращении подстроки $$$[2,4]$$$ строка «<span class="tex-font-style-tt">abcde</span>» становится равной «<span class="tex-font-style-tt">adbce</span>». </p></li></ul><p>Строка $$$a$$$ является подстрокой $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) символов из начала и нескольких (возможно, ни одного или всех) символов из конца.</p><p>Найдите минимальное количество операций, необходимых для преобразования $$$s$$$ в $$$t$$$, или определите, что это невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$t$$$ $$$(1\leq t \leq 2000)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит одно целое число $$$n$$$ $$$(1\leq n \leq 2000)$$$ — длину строк.</p><p>Вторая и третья строки содержат строки $$$s$$$ и $$$t$$$ соответственно.</p><p>Сумма $$$n$$$ по всем наборам входных данных не превышает $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите минимальное количество операций для преобразования $$$s$$$ в $$$t$$$. Если невозможно преобразовать $$$s$$$ в $$$t$$$, вместо этого выведите $$$-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
a
a
2
ab
ba
3
abc
cab
3
abc
cba
4
abab
baba
4
abcc
aabc
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
1
1
2
1
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Для первого набора входных данных, поскольку $$$s$$$ и $$$t$$$ равны, вам не нужно применять какие-либо операции.</p><p>Для второго набора входных данных вам нужно применить только одну операцию ко всей строке <span class="tex-font-style-tt">ab</span>, чтобы преобразовать ее в <span class="tex-font-style-tt">ba</span>.</p><p>Для третьего набора входных данных вам нужно только применить одну операцию ко всей строке <span class="tex-font-style-tt">abc</span>, чтобы преобразовать ее в <span class="tex-font-style-tt">cab</span>.</p><p>Для четвертого набора входных данных вам нужно применить операцию дважды: сначала для всей строки <span class="tex-font-style-tt">abc</span>, чтобы преобразовать ее в <span class="tex-font-style-tt">cab</span>, а затем для подстроки длины $$$2$$$, начинающейся со второго символа для преобразования ее в <span class="tex-font-style-tt">cba</span>.</p><p>Для пятого набора входных данных вам нужно применить только одну операцию ко всей строке <span class="tex-font-style-tt">abab</span>, чтобы преобразовать ее в <span class="tex-font-style-tt">baba</span>.</p><p>Для шестого набора входных данных превратить строку $$$s$$$ в строку $$$t$$$ не является возможным.</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:04: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:'8124a2a8ca3b1640',t:'MTY5NjY2NTg4OC4yNTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*2600"] | ||
1364A | 1364 | A | ru | A. XXXXX | <div class="problem-statement"><div class="header"><div class="title">A. XXXXX</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>Ехаб любит теорию чисел, но по какой-то причине он ненавидит число $$$x$$$. Для данного массива $$$a$$$ найдите длину самого длинного его подмассива, сумма элементов которого <span class="tex-font-style-bf">не</span> делится на $$$x$$$, или определите, что такого подмассива не существует.</p><p>Массив $$$a$$$ является подмассивом массива $$$b$$$, если $$$a$$$ может быть получен из $$$b$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ $$$(1 \le t \le 5)$$$ — количество наборов входных данных. Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^4$$$) — количество элементов в массиве $$$a$$$, и число, которое Ехаб ненавидит.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$0 \le a_i \le 10^4$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите длину самого длинного подмассива, сумма элементов которого не делится на $$$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>
3
3 3
1 2 3
3 4
1 2 3
2 2
0 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных подмассив $$$[2,3]$$$ имеет сумму элементов $$$5$$$, которая не делится на $$$3$$$.</p><p>Во втором наборе входных данных сумма всего элементов всего массива равна $$$6$$$, и не делится на $$$4$$$.</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="a1fd19fc68ac63bedc4ca209aa43b07c"/>
<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="9e9e2d8d76f01b0ef3e06718882f9a6db3228f28"/>
<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='a1fd19fc68ac63bedc4ca209aa43b07c'> </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%2F1364%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='a1fd19fc68ac63bedc4ca209aa43b07c'/>
<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/1364">Codeforces Round 649 (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='a1fd19fc68ac63bedc4ca209aa43b07c'/>
<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/1364/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="Сложность">
*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='a1fd19fc68ac63bedc4ca209aa43b07c'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="647817"/>
<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='a1fd19fc68ac63bedc4ca209aa43b07c'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="647817"/>
<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/78674" title="Codeforces Round #649 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11095" resourceName="Codeforces Round #649 (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/78781" title="Codeforces round #649 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11111" resourceName="Codeforces round #649 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/1364">Задачи</a></li>
<li><a
href="/contest/1364/submit">Отослать</a></li>
<li><a
href="/contest/1364/my">Мои посылки</a></li>
<li><a
href="/contest/1364/status">Статус</a></li>
<li><a
href="/contest/1364/hacks">Взломы</a></li>
<li><a
href="/contest/1364/room/1">Комната</a></li>
<li><a
href="/contest/1364/standings">Положение</a></li>
<li><a
href="/contest/1364/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_b9f1fd269e6c3749ba7c7d0f2807af65503951a5">
<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. XXXXX</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>Ехаб любит теорию чисел, но по какой-то причине он ненавидит число $$$x$$$. Для данного массива $$$a$$$ найдите длину самого длинного его подмассива, сумма элементов которого <span class="tex-font-style-bf">не</span> делится на $$$x$$$, или определите, что такого подмассива не существует.</p><p>Массив $$$a$$$ является подмассивом массива $$$b$$$, если $$$a$$$ может быть получен из $$$b$$$ удалением нескольких (возможно, ни одного или всех) элементов из начала и нескольких (возможно, ни одного или всех) элементов из конца.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$t$$$ $$$(1 \le t \le 5)$$$ — количество наборов входных данных. Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит два целых числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 10^5$$$, $$$1 \le x \le 10^4$$$) — количество элементов в массиве $$$a$$$, и число, которое Ехаб ненавидит.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$0 \le a_i \le 10^4$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите длину самого длинного подмассива, сумма элементов которого не делится на $$$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>
3
3 3
1 2 3
3 4
1 2 3
2 2
0 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
-1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных подмассив $$$[2,3]$$$ имеет сумму элементов $$$5$$$, которая не делится на $$$3$$$.</p><p>Во втором наборе входных данных сумма всего элементов всего массива равна $$$6$$$, и не делится на $$$4$$$.</p><p>В третьем наборе входных данных все подмассивы имеют четную сумму, поэтому ответ равен $$$-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:04:49</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a2b15ad87b83',t:'MTY5NjY2NTg4OS42MzUwMDA='};_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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1200"] | ||
1364B | 1364 | B | ru | B. Наиболее социально-дистанцированная подпоследовательность | <div class="problem-statement"><div class="header"><div class="title">B. Наиболее социально-дистанцированная подпоследовательность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для заданной перестановки $$$p$$$ длины $$$n$$$, найдите ее подпоследовательность $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ длины хотя бы $$$2$$$ такую, что:</p><ul> <li> $$$|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$$$ является максимально возможным среди всех подпоследовательностей $$$p$$$ длины хотя бы $$$2$$$. </li><li> среди всех таких подпоследовательностей выберите ту, длина которой $$$k$$$ как можно меньше. </li></ul><p>Если несколько подпоследовательностей удовлетворяют этим условиям, вы можете найти любую из них.</p><p>Последовательность $$$a$$$ является подпоследовательностью $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) элементов.</p><p>Перестановка длины $$$n$$$ — это массив длины $$$n$$$, в котором каждый элемент от $$$1$$$ до $$$n$$$ встречается ровно один раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов входных данных. Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — длину перестановки $$$p$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_{n}$$$ ($$$1 \le p_i \le n$$$, $$$p_i$$$ попарно различны) — элементы перестановки $$$p$$$.</p><p><span class="tex-font-style-bf">Сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных первая строка должна содержать длину найденной подпоследовательности, $$$k$$$. Вторая строка должна содержать $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ — ее элементы.</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
3
3 2 1
4
1 3 4 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3 1
3
1 4 2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере есть $$$4$$$ подпоследовательности длиной не менее $$$2$$$:</p><ul> <li> $$$[3,2]$$$, что дает нам $$$|3-2|=1$$$. </li><li> $$$[3,1]$$$, что дает нам $$$|3-1|=2$$$. </li><li> $$$[2,1]$$$, что дает нам $$$|2-1|=1$$$. </li><li> $$$[3,2,1]$$$, что дает нам $$$|3-2|+|2-1|=2$$$. </li></ul><p>Таким образом, ответ либо $$$[3,1]$$$, либо $$$[3,2,1]$$$. Поскольку мы хотим, чтобы подпоследовательность была как можно короче, ответ будет $$$[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="254495fa22940d438460a8ce2c44335a"/>
<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="9e9e2d8d76f01b0ef3e06718882f9a6db3228f28"/>
<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='254495fa22940d438460a8ce2c44335a'> </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%2F1364%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='254495fa22940d438460a8ce2c44335a'/>
<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/1364">Codeforces Round 649 (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='254495fa22940d438460a8ce2c44335a'/>
<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/1364/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='254495fa22940d438460a8ce2c44335a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="647243"/>
<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='254495fa22940d438460a8ce2c44335a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="647243"/>
<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/78674" title="Codeforces Round #649 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11095" resourceName="Codeforces Round #649 (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/78781" title="Codeforces round #649 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11111" resourceName="Codeforces round #649 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/1364">Задачи</a></li>
<li><a
href="/contest/1364/submit">Отослать</a></li>
<li><a
href="/contest/1364/my">Мои посылки</a></li>
<li><a
href="/contest/1364/status">Статус</a></li>
<li><a
href="/contest/1364/hacks">Взломы</a></li>
<li><a
href="/contest/1364/room/1">Комната</a></li>
<li><a
href="/contest/1364/standings">Положение</a></li>
<li><a
href="/contest/1364/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_237279b1889a48471a9d4e97c61a80afdc444b5e">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. Наиболее социально-дистанцированная подпоследовательность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для заданной перестановки $$$p$$$ длины $$$n$$$, найдите ее подпоследовательность $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ длины хотя бы $$$2$$$ такую, что:</p><ul> <li> $$$|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$$$ является максимально возможным среди всех подпоследовательностей $$$p$$$ длины хотя бы $$$2$$$. </li><li> среди всех таких подпоследовательностей выберите ту, длина которой $$$k$$$ как можно меньше. </li></ul><p>Если несколько подпоследовательностей удовлетворяют этим условиям, вы можете найти любую из них.</p><p>Последовательность $$$a$$$ является подпоследовательностью $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ удалением нескольких (возможно, ни одного или всех) элементов.</p><p>Перестановка длины $$$n$$$ — это массив длины $$$n$$$, в котором каждый элемент от $$$1$$$ до $$$n$$$ встречается ровно один раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — количество наборов входных данных. Описание наборов входных данных приведено ниже.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$2 \le n \le 10^5$$$) — длину перестановки $$$p$$$.</p><p>Вторая строка каждого набора входных данных содержит $$$n$$$ целых чисел $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_{n}$$$ ($$$1 \le p_i \le n$$$, $$$p_i$$$ попарно различны) — элементы перестановки $$$p$$$.</p><p><span class="tex-font-style-bf">Сумма $$$n$$$ по всем наборам входных данных не превышает $$$10^5$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных первая строка должна содержать длину найденной подпоследовательности, $$$k$$$. Вторая строка должна содержать $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ — ее элементы.</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
3
3 2 1
4
1 3 4 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3 1
3
1 4 2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере есть $$$4$$$ подпоследовательности длиной не менее $$$2$$$:</p><ul> <li> $$$[3,2]$$$, что дает нам $$$|3-2|=1$$$. </li><li> $$$[3,1]$$$, что дает нам $$$|3-1|=2$$$. </li><li> $$$[2,1]$$$, что дает нам $$$|2-1|=1$$$. </li><li> $$$[3,2,1]$$$, что дает нам $$$|3-2|+|2-1|=2$$$. </li></ul><p>Таким образом, ответ либо $$$[3,1]$$$, либо $$$[3,2,1]$$$. Поскольку мы хотим, чтобы подпоследовательность была как можно короче, ответ будет $$$[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:04: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:'8124a2b9da070c42',t:'MTY5NjY2NTg5MC45NjIwMDA='};_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", "\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", "*1300"] | ||
1364C | 1364 | C | ru | C. Ехаб и префиксные MEXы | <div class="problem-statement"><div class="header"><div class="title">C. Ехаб и префиксные MEXы</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$$$ найдите другой массив $$$b$$$ длины $$$n$$$ такой, что:</p><ul> <li> для каждого $$$i$$$ $$$(1 \le i \le n)$$$ $$$MEX(\{b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_i\})=a_i$$$. </li></ul><p>$$$MEX$$$ множества целых чисел равен наименьшему неотрицательному целому числу, которое не принадлежит этому множеству.</p><p>Если такого массива не существует, определите это.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — длина массива $$$a$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$0 \le a_i \le i$$$) — элементы массива $$$a$$$. <span class="tex-font-style-bf">Гарантируется, что $$$a_i \le a_{i+1}$$$ для $$$1\le i < n$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если такого массива нет, выведите одну строку, содержащую $$$-1$$$.</p><p>В противном случае выведите одну строку, содержащую $$$n$$$ целых чисел $$$b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_n$$$ ($$$0 \le b_i \le 10^6$$$).</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
1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
0 0 0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 3 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере допустимы другие ответы, например, $$$[1,1,1,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="f314e6ff9fc78aa6b6876eb60ce23bd8"/>
<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="9e9e2d8d76f01b0ef3e06718882f9a6db3228f28"/>
<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='f314e6ff9fc78aa6b6876eb60ce23bd8'> </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%2F1364%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='f314e6ff9fc78aa6b6876eb60ce23bd8'/>
<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/1364">Codeforces Round 649 (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='f314e6ff9fc78aa6b6876eb60ce23bd8'/>
<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/1364/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='f314e6ff9fc78aa6b6876eb60ce23bd8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="647244"/>
<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='f314e6ff9fc78aa6b6876eb60ce23bd8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="647244"/>
<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/78674" title="Codeforces Round #649 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11095" resourceName="Codeforces Round #649 (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/78781" title="Codeforces round #649 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11111" resourceName="Codeforces round #649 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/1364">Задачи</a></li>
<li><a
href="/contest/1364/submit">Отослать</a></li>
<li><a
href="/contest/1364/my">Мои посылки</a></li>
<li><a
href="/contest/1364/status">Статус</a></li>
<li><a
href="/contest/1364/hacks">Взломы</a></li>
<li><a
href="/contest/1364/room/1">Комната</a></li>
<li><a
href="/contest/1364/standings">Положение</a></li>
<li><a
href="/contest/1364/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_063dcb05d1030b29507289f60cd17d4db698781d">
<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. Ехаб и префиксные MEXы</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$$$ найдите другой массив $$$b$$$ длины $$$n$$$ такой, что:</p><ul> <li> для каждого $$$i$$$ $$$(1 \le i \le n)$$$ $$$MEX(\{b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_i\})=a_i$$$. </li></ul><p>$$$MEX$$$ множества целых чисел равен наименьшему неотрицательному целому числу, которое не принадлежит этому множеству.</p><p>Если такого массива не существует, определите это.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — длина массива $$$a$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$0 \le a_i \le i$$$) — элементы массива $$$a$$$. <span class="tex-font-style-bf">Гарантируется, что $$$a_i \le a_{i+1}$$$ для $$$1\le i < n$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если такого массива нет, выведите одну строку, содержащую $$$-1$$$.</p><p>В противном случае выведите одну строку, содержащую $$$n$$$ целых чисел $$$b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_n$$$ ($$$0 \le b_i \le 10^6$$$).</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
1 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
0 0 0 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 3 4 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Во втором примере допустимы другие ответы, например, $$$[1,1,1,0]$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04: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:'8124a2c23b999d73',t:'MTY5NjY2NTg5Mi4zMjEwMDA='};_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", "\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", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1600"] | ||
1364D | 1364 | D | ru | D. Последнее следствие Ехаба | <div class="problem-statement"><div class="header"><div class="title">D. Последнее следствие Ехаба</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для связного неориентированного графа с $$$n$$$ вершинами и целого числа $$$k$$$, вы должны, на ваш выбор:</p><ul> <li> или найти независимое множество с <span class="tex-font-style-bf">ровно</span> $$$\lceil\frac{k}{2}\rceil$$$ вершинами.</li><li> или найти <span class="tex-font-style-bf">простой</span> цикл длины <span class="tex-font-style-bf">не более</span> $$$k$$$. </li></ul><p>Независимое множество — это набор вершин такой, что никакие две из них не связаны ребром. Простой цикл — это цикл, который не содержит ни одной вершины дважды. </p><p>У меня есть доказательство, что для любых входных данных вы всегда можете решить по крайней мере одну из этих задач, но оно слишком тривиально, чтобы поместиться здесь.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$, $$$m$$$, and $$$k$$$ ($$$3 \le k \le n \le 10^5$$$, $$$n-1 \le m \le 2 \cdot 10^5$$$) — количество вершин и ребер в графе и параметр $$$k$$$ из условия.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), которые обозначают, что между вершинами $$$u$$$ и $$$v$$$ есть ребро. Гарантируется, что граф связен и не содержит петель или кратных ребер.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если вы решили решить первую задачу, то в первой строке выведите $$$1$$$, а затем строку, содержащую $$$\lceil\frac{k}{2}\rceil$$$ различных целых чисел, не превышающих $$$n$$$ — вершины в желаемом независимом наборе.</p><p>Если же вы решили решить вторую задачу, то в первой строке выведите $$$2$$$, затем строку, содержащую одно целое число, $$$c$$$, представляющее длину найденного цикла, а затем строку, содержащую $$$c$$$ различных целых чисел, не превышающих $$$n$$$ — вершины в нужном цикле, <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 3
1 2
2 3
3 4
4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 5 3
1 2
2 3
3 4
4 1
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
2 3 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
1 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 4 5
1 2
1 3
2 4
2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/30ec0d0b069debf55bfe3aba38c15fe035e200d6.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Обратите внимание, что вывод независимого множества $$$\{2,4\}$$$ тоже зачтется, но вывод цикла $$$1-2-3-4$$$ — нет, потому что его длина должна быть не более $$$3$$$.</p><p>Во втором примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/49b31d8a4b5e8512fbcdd368e5a4a34445a020be.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>Обратите внимание, что вывод независимого множества $$$\{1,3\}$$$ или цикла $$$2-1-4$$$ также зачтутся.</p><p>В третьем примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/45bb98eab0d3defca699e0516b015899cbd2225c.png" style="max-width: 100.0%;max-height: 100.0%;"/></p><p>В четвертом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/0b423c3ffbcf9f02621ccf7efc14e8c656d80c8b.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="0751b7688895a3f53da273580900d0a3"/>
<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="9e9e2d8d76f01b0ef3e06718882f9a6db3228f28"/>
<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='0751b7688895a3f53da273580900d0a3'> </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%2F1364%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='0751b7688895a3f53da273580900d0a3'/>
<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/1364">Codeforces Round 649 (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='0751b7688895a3f53da273580900d0a3'/>
<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/1364/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='0751b7688895a3f53da273580900d0a3'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="647245"/>
<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='0751b7688895a3f53da273580900d0a3'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="647245"/>
<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/78674" title="Codeforces Round #649 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11095" resourceName="Codeforces Round #649 (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/78781" title="Codeforces round #649 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11111" resourceName="Codeforces round #649 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/1364">Задачи</a></li>
<li><a
href="/contest/1364/submit">Отослать</a></li>
<li><a
href="/contest/1364/my">Мои посылки</a></li>
<li><a
href="/contest/1364/status">Статус</a></li>
<li><a
href="/contest/1364/hacks">Взломы</a></li>
<li><a
href="/contest/1364/room/1">Комната</a></li>
<li><a
href="/contest/1364/standings">Положение</a></li>
<li><a
href="/contest/1364/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_57c9022be9159260621e5af70a2e24c93d8bb2f5">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Последнее следствие Ехаба</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Для связного неориентированного графа с $$$n$$$ вершинами и целого числа $$$k$$$, вы должны, на ваш выбор:</p><ul> <li> или найти независимое множество с <span class="tex-font-style-bf">ровно</span> $$$\lceil\frac{k}{2}\rceil$$$ вершинами.</li><li> или найти <span class="tex-font-style-bf">простой</span> цикл длины <span class="tex-font-style-bf">не более</span> $$$k$$$. </li></ul><p>Независимое множество — это набор вершин такой, что никакие две из них не связаны ребром. Простой цикл — это цикл, который не содержит ни одной вершины дважды. </p><p>У меня есть доказательство, что для любых входных данных вы всегда можете решить по крайней мере одну из этих задач, но оно слишком тривиально, чтобы поместиться здесь.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит три целых числа $$$n$$$, $$$m$$$, and $$$k$$$ ($$$3 \le k \le n \le 10^5$$$, $$$n-1 \le m \le 2 \cdot 10^5$$$) — количество вершин и ребер в графе и параметр $$$k$$$ из условия.</p><p>Каждая из следующих $$$m$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), которые обозначают, что между вершинами $$$u$$$ и $$$v$$$ есть ребро. Гарантируется, что граф связен и не содержит петель или кратных ребер.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если вы решили решить первую задачу, то в первой строке выведите $$$1$$$, а затем строку, содержащую $$$\lceil\frac{k}{2}\rceil$$$ различных целых чисел, не превышающих $$$n$$$ — вершины в желаемом независимом наборе.</p><p>Если же вы решили решить вторую задачу, то в первой строке выведите $$$2$$$, затем строку, содержащую одно целое число, $$$c$$$, представляющее длину найденного цикла, а затем строку, содержащую $$$c$$$ различных целых чисел, не превышающих $$$n$$$ — вершины в нужном цикле, <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 3
1 2
2 3
3 4
4 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 5 3
1 2
2 3
3 4
4 1
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
2 3 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3
1 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 4 5
1 2
1 3
2 4
2 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
1 4 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/30ec0d0b069debf55bfe3aba38c15fe035e200d6.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Обратите внимание, что вывод независимого множества $$$\{2,4\}$$$ тоже зачтется, но вывод цикла $$$1-2-3-4$$$ — нет, потому что его длина должна быть не более $$$3$$$.</p><p>Во втором примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/49b31d8a4b5e8512fbcdd368e5a4a34445a020be.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>Обратите внимание, что вывод независимого множества $$$\{1,3\}$$$ или цикла $$$2-1-4$$$ также зачтутся.</p><p>В третьем примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/45bb98eab0d3defca699e0516b015899cbd2225c.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>В четвертом примере:</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/0b423c3ffbcf9f02621ccf7efc14e8c656d80c8b.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:04:53</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a2cac8c67a75',t:'MTY5NjY2NTg5My42NjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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", "*2100"] | ||
1364E | 1364 | E | ru | E. X-OR | <div class="problem-statement"><div class="header"><div class="title">E. X-OR</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача!</span></p><p>У Ехаба есть загаданная перестановка $$$p$$$ длины $$$n$$$, состоящая из элементов от $$$0$$$ до $$$n-1$$$. По какой-то причине вы хотите выяснить перестановку. Для этого вы можете спросить у Ехаба $$$2$$$ <span class="tex-font-style-bf">разных</span> индекса $$$i$$$ и $$$j$$$, и он ответит $$$(p_i|p_j)$$$, где $$$|$$$ обозначает операцию <a href="http://bitly.com/2JQkyd6">побитового ИЛИ</a>.</p><p>У Ехаба есть достаточно свободного времени, чтобы ответить на $$$4269$$$ вопросов, и, несмотря на то, что ему несложно отвечать на так много вопросов, ему лень играть в ваши глупые игры, поэтому он заранее зафиксирует перестановку и <span class="tex-font-style-bf">не</span> изменит ее в зависимости от ваших запросов. Можете ли вы угадать перестановку?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано целое число $$$n$$$ $$$(3 \le n \le 2048)$$$ — длина перестановки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы задать вопрос, выведите "<span class="tex-font-style-tt">? $$$i$$$ $$$j$$$</span>" (без кавычек, $$$i \neq j$$$) Затем вы должны считать ответ, который будет равен $$$(p_i|p_j)$$$.</p><p>Если мы ответим $$$-1$$$ вместо правильного ответа, это означает, что вы превысили количество запросов или сделали неверный запрос.</p><p>Завершите программу сразу после получения $$$-1$$$, и вы увидите вердикт <span class="tex-font-style-tt">Неправильный ответ</span>. В противном случае вы можете получить произвольный вердикт, потому что ваше решение будет продолжать читать из закрытого потока.</p><p>Чтобы дать ответ, выведите "<span class="tex-font-style-tt">! $$$p_1$$$ $$$p_2$$$ $$$\ldots$$$ $$$p_n$$$</span>" (без кавычек). <span class="tex-font-style-bf">Заметьте, что вывод ответа не считается одним из $$$4269$$$ запросов</span>.</p><p>После вывода запроса не забудьте вывести перевод строки, и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p><span class="tex-font-style-bf">Взломы:</span></p><p>Первая строка должна содержать целое число $$$n$$$ ($$$3 \le n \le 2^{11}$$$) — длину перестановки $$$p$$$.</p><p>Вторая строка должна содержать $$$n$$$ целых чисел, разделенных пробелами $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ ($$$0 \le p_i < n$$$) — элементы перестановки $$$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
3
2</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 2
? 1 3
? 2 3
! 1 0 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере перестановка равна $$$[1,0,2]$$$. Вы начинаете с вопроса $$$p_1|p_2$$$, а Ехаб отвечает $$$1$$$. Затем вы спрашиваете $$$p_1|p_3$$$, а Ехаб отвечает $$$3$$$. Наконец, вы спрашиваете о $$$p_2|p_3$$$, а Ехаб отвечает $$$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="afff28d4930942fea7e5ee2b90c9d9a0"/>
<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="9e9e2d8d76f01b0ef3e06718882f9a6db3228f28"/>
<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='afff28d4930942fea7e5ee2b90c9d9a0'> </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%2F1364%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='afff28d4930942fea7e5ee2b90c9d9a0'/>
<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/1364">Codeforces Round 649 (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='afff28d4930942fea7e5ee2b90c9d9a0'/>
<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/1364/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="Сложность">
*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='afff28d4930942fea7e5ee2b90c9d9a0'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="647246"/>
<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='afff28d4930942fea7e5ee2b90c9d9a0'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="647246"/>
<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/78674" title="Codeforces Round #649 (Div.2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11095" resourceName="Codeforces Round #649 (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/78781" title="Codeforces round #649 editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11111" resourceName="Codeforces round #649 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/1364">Задачи</a></li>
<li><a
href="/contest/1364/submit">Отослать</a></li>
<li><a
href="/contest/1364/my">Мои посылки</a></li>
<li><a
href="/contest/1364/status">Статус</a></li>
<li><a
href="/contest/1364/hacks">Взломы</a></li>
<li><a
href="/contest/1364/room/1">Комната</a></li>
<li><a
href="/contest/1364/standings">Положение</a></li>
<li><a
href="/contest/1364/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_3071813ff7f2b4a512f052af6f08431dff3a98a9">
<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. X-OR</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача!</span></p><p>У Ехаба есть загаданная перестановка $$$p$$$ длины $$$n$$$, состоящая из элементов от $$$0$$$ до $$$n-1$$$. По какой-то причине вы хотите выяснить перестановку. Для этого вы можете спросить у Ехаба $$$2$$$ <span class="tex-font-style-bf">разных</span> индекса $$$i$$$ и $$$j$$$, и он ответит $$$(p_i|p_j)$$$, где $$$|$$$ обозначает операцию <a href="http://bitly.com/2JQkyd6">побитового ИЛИ</a>.</p><p>У Ехаба есть достаточно свободного времени, чтобы ответить на $$$4269$$$ вопросов, и, несмотря на то, что ему несложно отвечать на так много вопросов, ему лень играть в ваши глупые игры, поэтому он заранее зафиксирует перестановку и <span class="tex-font-style-bf">не</span> изменит ее в зависимости от ваших запросов. Можете ли вы угадать перестановку?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано целое число $$$n$$$ $$$(3 \le n \le 2048)$$$ — длина перестановки.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы задать вопрос, выведите "<span class="tex-font-style-tt">? $$$i$$$ $$$j$$$</span>" (без кавычек, $$$i \neq j$$$) Затем вы должны считать ответ, который будет равен $$$(p_i|p_j)$$$.</p><p>Если мы ответим $$$-1$$$ вместо правильного ответа, это означает, что вы превысили количество запросов или сделали неверный запрос.</p><p>Завершите программу сразу после получения $$$-1$$$, и вы увидите вердикт <span class="tex-font-style-tt">Неправильный ответ</span>. В противном случае вы можете получить произвольный вердикт, потому что ваше решение будет продолжать читать из закрытого потока.</p><p>Чтобы дать ответ, выведите "<span class="tex-font-style-tt">! $$$p_1$$$ $$$p_2$$$ $$$\ldots$$$ $$$p_n$$$</span>" (без кавычек). <span class="tex-font-style-bf">Заметьте, что вывод ответа не считается одним из $$$4269$$$ запросов</span>.</p><p>После вывода запроса не забудьте вывести перевод строки, и сбросить буфер вывода. В противном случае вы получите вердикт <span class="tex-font-style-tt">Решение «зависло»</span>. Для сброса буфера используйте:</p><ul><li> <span class="tex-font-style-tt">fflush(stdout)</span> или <span class="tex-font-style-tt">cout.flush()</span> в C++;</li><li> <span class="tex-font-style-tt">System.out.flush()</span> в Java;</li><li> <span class="tex-font-style-tt">flush(output)</span> в Pascal;</li><li> <span class="tex-font-style-tt">stdout.flush()</span> в Python;</li><li> смотрите документацию для других языков.</li></ul><p><span class="tex-font-style-bf">Взломы:</span></p><p>Первая строка должна содержать целое число $$$n$$$ ($$$3 \le n \le 2^{11}$$$) — длину перестановки $$$p$$$.</p><p>Вторая строка должна содержать $$$n$$$ целых чисел, разделенных пробелами $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ ($$$0 \le p_i < n$$$) — элементы перестановки $$$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
3
2</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 2
? 1 3
? 2 3
! 1 0 2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере перестановка равна $$$[1,0,2]$$$. Вы начинаете с вопроса $$$p_1|p_2$$$, а Ехаб отвечает $$$1$$$. Затем вы спрашиваете $$$p_1|p_3$$$, а Ехаб отвечает $$$3$$$. Наконец, вы спрашиваете о $$$p_2|p_3$$$, а Ехаб отвечает $$$2$$$. После этого вы угадываете перестановку.</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:04: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:'8124a2d31b1a1498',t:'MTY5NjY2NTg5NS4wMTYwMDA='};_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", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\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", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*2700"] | ||
1365A | 1365 | 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>Ashish и Vivek играют в игру на таблице с $$$n$$$ строками и $$$m$$$ столбцами, захватывая клетки. Незахваченные клетки обозначены $$$0$$$, а захваченные клетки обозначены $$$1$$$. Вам дано исходное состояние таблицы.</p><p>На каждом ходу, игрок должен захватить одну клетку. Клетку можно захватить, если она еще не захвачена, и она не находится в одной строке или столбце с другой захваченной клеткой. Игра кончается, когда игрок не может сделать ход, в таком случае, он проигрывает.</p><p>Если Ashish и Vivek ходят по очереди и Ashish ходит первым, найдите победителя игры если они оба играют оптимально.</p><p>Оптимальная игра между двумя игроками означает, что оба игрока выбирают лучшую возможную стратегию, чтобы получить наиболее благоприятный для себя результат игры.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ $$$(1 \le t \le 50)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>В первой строке каждого набора входных данных записаны два целых числа $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — количество строк и столбцов в таблице.</p><p>В каждой из следующих $$$n$$$ строк записаны $$$m$$$ целых чисел, $$$j$$$-е число на $$$i$$$-й строке описывает $$$a_{i,j}$$$ $$$(a_{i,j} \in \{0, 1\})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если Ashish выиграет при правильной игре, выведите «<span class="tex-font-style-tt">Ashish</span>», иначе выведите «<span class="tex-font-style-tt">Vivek</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
2 2
0 0
0 0
2 2
0 0
0 1
2 3
1 0 1
1 1 0
3 3
1 0 0
0 0 0
1 0 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Vivek
Ashish
Vivek
Ashish
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных: Один из возможных исходов игры следующий: Ashish захватывает клетку $$$(1, 1)$$$, затем Vivek захватывает клетку $$$(2, 2)$$$. Ashish не может захватить ни клетку $$$(1, 2)$$$, ни клетку $$$(2, 1)$$$, так как клетки $$$(1, 1)$$$ и $$$(2, 2)$$$ уже захвачены. Таким образом, Ashish проигрывает. Можно показать, что вне зависимости от ходов Ashish, Vivek выиграет. Во втором наборе входных данных: Ashish захватывает клетку $$$(1, 1)$$$, единственная клетка, которую можно захватить. После этого у Vivek не будет возможных ходов.</p><p>В третьем наборе входных данных: Ashish не может сделать ход, поэтому Vivek выиграет.</p><p>В четвертом наборе входных данных: Ashish захватывает клетку $$$(2, 3)$$$, у Vivek не останется возможных ходов.</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="8aa2c34b71ba9927a2adc495035e64a7"/>
<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="d8c2a2171273b6908cd30c020410d21c6cf5711b"/>
<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='8aa2c34b71ba9927a2adc495035e64a7'> </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%2F1365%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='8aa2c34b71ba9927a2adc495035e64a7'/>
<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/1365">Codeforces Round 648 (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='8aa2c34b71ba9927a2adc495035e64a7'/>
<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/1365/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='8aa2c34b71ba9927a2adc495035e64a7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="643136"/>
<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='8aa2c34b71ba9927a2adc495035e64a7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="643136"/>
<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/78406" title="Codeforces Round #648 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11039" resourceName="Codeforces Round #648 (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/78504" title="Editorial — Codeforces Round #648" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11048" resourceName="Editorial — Codeforces Round #648"
resourceManual="true" src="//codeforces.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/1365">Задачи</a></li>
<li><a
href="/contest/1365/submit">Отослать</a></li>
<li><a
href="/contest/1365/my">Мои посылки</a></li>
<li><a
href="/contest/1365/status">Статус</a></li>
<li><a
href="/contest/1365/hacks">Взломы</a></li>
<li><a
href="/contest/1365/room/1">Комната</a></li>
<li><a
href="/contest/1365/standings">Положение</a></li>
<li><a
href="/contest/1365/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_a118730597104f590a9cf55b08d5c78f22da409d">
<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>Ashish и Vivek играют в игру на таблице с $$$n$$$ строками и $$$m$$$ столбцами, захватывая клетки. Незахваченные клетки обозначены $$$0$$$, а захваченные клетки обозначены $$$1$$$. Вам дано исходное состояние таблицы.</p><p>На каждом ходу, игрок должен захватить одну клетку. Клетку можно захватить, если она еще не захвачена, и она не находится в одной строке или столбце с другой захваченной клеткой. Игра кончается, когда игрок не может сделать ход, в таком случае, он проигрывает.</p><p>Если Ashish и Vivek ходят по очереди и Ashish ходит первым, найдите победителя игры если они оба играют оптимально.</p><p>Оптимальная игра между двумя игроками означает, что оба игрока выбирают лучшую возможную стратегию, чтобы получить наиболее благоприятный для себя результат игры.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ $$$(1 \le t \le 50)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>В первой строке каждого набора входных данных записаны два целых числа $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — количество строк и столбцов в таблице.</p><p>В каждой из следующих $$$n$$$ строк записаны $$$m$$$ целых чисел, $$$j$$$-е число на $$$i$$$-й строке описывает $$$a_{i,j}$$$ $$$(a_{i,j} \in \{0, 1\})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, если Ashish выиграет при правильной игре, выведите «<span class="tex-font-style-tt">Ashish</span>», иначе выведите «<span class="tex-font-style-tt">Vivek</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
2 2
0 0
0 0
2 2
0 0
0 1
2 3
1 0 1
1 1 0
3 3
1 0 0
0 0 0
1 0 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Vivek
Ashish
Vivek
Ashish
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных: Один из возможных исходов игры следующий: Ashish захватывает клетку $$$(1, 1)$$$, затем Vivek захватывает клетку $$$(2, 2)$$$. Ashish не может захватить ни клетку $$$(1, 2)$$$, ни клетку $$$(2, 1)$$$, так как клетки $$$(1, 1)$$$ и $$$(2, 2)$$$ уже захвачены. Таким образом, Ashish проигрывает. Можно показать, что вне зависимости от ходов Ashish, Vivek выиграет. Во втором наборе входных данных: Ashish захватывает клетку $$$(1, 1)$$$, единственная клетка, которую можно захватить. После этого у Vivek не будет возможных ходов.</p><p>В третьем наборе входных данных: Ashish не может сделать ход, поэтому Vivek выиграет.</p><p>В четвертом наборе входных данных: Ashish захватывает клетку $$$(2, 3)$$$, у Vivek не останется возможных ходов.</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:04: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:'8124a2db7f949d3d',t:'MTY5NjY2NTg5Ni4zOTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u0433\u0440\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1100"] | ||
1365B | 1365 | 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>У Ashish есть $$$n$$$ элементов, расположенных по порядку. </p><p>Каждый элемент задается двумя целыми числами $$$a_i$$$ — значение элемента и $$$b_i$$$ — тип элемента (есть только два возможных типа: $$$0$$$ и $$$1$$$). Он хочет отсортировать элементы в порядке неубывания $$$a_i$$$.</p><p>Он может совершать следующую операцию произвольное число раз: </p><ul><li> Выбрать любые два таких элемента $$$i$$$ и $$$j$$$, что $$$b_i \ne b_j$$$ и поменять их местами. Таким образом, он может за ход поменять местами два элемента разных типов. </li></ul><p>Скажите ему, может ли он отсортировать массив в порядке неубывания $$$a_i$$$, используя описанные операции.</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 500)$$$ — размеры массивов.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_i$$$ $$$(1 \le a_i \le 10^5)$$$ — значение $$$i$$$-го элемента.</p><p>В третьей строке записаны $$$n$$$ целых чисел $$$b_i$$$ $$$(b_i \in \{0, 1\})$$$ — тип $$$i$$$-го элемента.</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>
5
4
10 20 20 30
0 1 0 1
3
3 1 2
0 1 1
4
2 2 4 8
1 1 1 1
3
5 15 4
0 0 0
4
20 10 100 50
1 0 0 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
Yes
Yes
No
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных: элементы уже находятся в отсортированном порядке.</p><p>Во втором наборе входных данных: Ashish сначала может поменять местами элементы на позициях $$$1$$$ и $$$2$$$, затем поменять местами элементы на позициях $$$2$$$ и $$$3$$$.</p><p>В четвертом наборе входных данных: Нельзя поменять местами никакие два элемента, так как нет пары $$$i$$$ и $$$j$$$, что $$$b_i \ne b_j$$$. Таким образом, элементы не могут быть отсортированы.</p><p>В пятом наборе входных данных: Ashish может поменять местами элементы на позициях $$$3$$$ и $$$4$$$, а затем элементы на позициях $$$1$$$ и $$$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="74561ec6533ef51501b7260b2afdb837"/>
<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="d8c2a2171273b6908cd30c020410d21c6cf5711b"/>
<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='74561ec6533ef51501b7260b2afdb837'> </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%2F1365%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='74561ec6533ef51501b7260b2afdb837'/>
<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/1365">Codeforces Round 648 (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='74561ec6533ef51501b7260b2afdb837'/>
<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/1365/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='74561ec6533ef51501b7260b2afdb837'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="643137"/>
<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='74561ec6533ef51501b7260b2afdb837'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="643137"/>
<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/78406" title="Codeforces Round #648 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11039" resourceName="Codeforces Round #648 (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/78504" title="Editorial — Codeforces Round #648" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11048" resourceName="Editorial — Codeforces Round #648"
resourceManual="true" src="//codeforces.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/1365">Задачи</a></li>
<li><a
href="/contest/1365/submit">Отослать</a></li>
<li><a
href="/contest/1365/my">Мои посылки</a></li>
<li><a
href="/contest/1365/status">Статус</a></li>
<li><a
href="/contest/1365/hacks">Взломы</a></li>
<li><a
href="/contest/1365/room/1">Комната</a></li>
<li><a
href="/contest/1365/standings">Положение</a></li>
<li><a
href="/contest/1365/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_5fe012fbc18df52875f197a11a06138329f0ecd6">
<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>У Ashish есть $$$n$$$ элементов, расположенных по порядку. </p><p>Каждый элемент задается двумя целыми числами $$$a_i$$$ — значение элемента и $$$b_i$$$ — тип элемента (есть только два возможных типа: $$$0$$$ и $$$1$$$). Он хочет отсортировать элементы в порядке неубывания $$$a_i$$$.</p><p>Он может совершать следующую операцию произвольное число раз: </p><ul><li> Выбрать любые два таких элемента $$$i$$$ и $$$j$$$, что $$$b_i \ne b_j$$$ и поменять их местами. Таким образом, он может за ход поменять местами два элемента разных типов. </li></ul><p>Скажите ему, может ли он отсортировать массив в порядке неубывания $$$a_i$$$, используя описанные операции.</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 500)$$$ — размеры массивов.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_i$$$ $$$(1 \le a_i \le 10^5)$$$ — значение $$$i$$$-го элемента.</p><p>В третьей строке записаны $$$n$$$ целых чисел $$$b_i$$$ $$$(b_i \in \{0, 1\})$$$ — тип $$$i$$$-го элемента.</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>
5
4
10 20 20 30
0 1 0 1
3
3 1 2
0 1 1
4
2 2 4 8
1 1 1 1
3
5 15 4
0 0 0
4
20 10 100 50
1 0 0 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
Yes
Yes
No
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных: элементы уже находятся в отсортированном порядке.</p><p>Во втором наборе входных данных: Ashish сначала может поменять местами элементы на позициях $$$1$$$ и $$$2$$$, затем поменять местами элементы на позициях $$$2$$$ и $$$3$$$.</p><p>В четвертом наборе входных данных: Нельзя поменять местами никакие два элемента, так как нет пары $$$i$$$ и $$$j$$$, что $$$b_i \ne b_j$$$. Таким образом, элементы не могут быть отсортированы.</p><p>В пятом наборе входных данных: Ashish может поменять местами элементы на позициях $$$3$$$ и $$$4$$$, а затем элементы на позициях $$$1$$$ и $$$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:04: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:'8124a2e43b983a89',t:'MTY5NjY2NTg5Ny43NzcwMDA='};_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", "*1300"] | ||
1365C | 1365 | 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>После мистического исчезнования Ashish, каждый из его любимых учеников Ishika и Hriday, получил одну половину секретного сообщения. Эти сообщения могут быть описаны перестановками размера $$$n$$$. Назовем их $$$a$$$ и $$$b$$$.</p><p>Напомним, что перестановка из $$$n$$$ элементов это последовательность чисел $$$a_1, a_2, \ldots, a_n$$$, в которой каждое число от $$$1$$$ до $$$n$$$ встречается ровно один раз. </p><p>Сообщение может быть расшифровано из конфигурации перестановок $$$a$$$ и $$$b$$$, в котором количество совпадающих пар элементов максимально. Пара элементов $$$a_i$$$ и $$$b_j$$$ называется совпадающей, если: </p><ul> <li> $$$i = j$$$, таким образом, у них один и тот же индекс. </li><li> $$$a_i = b_j$$$ </li></ul><p>Его ученикам разрешается совершать следующую операцию произвольное число раз: </p><ul> <li> выбрать число $$$k$$$ и циклически сдвинуть одну из перестановок влево или вправо $$$k$$$ раз. </li></ul><p>Циклический сдвиг перестановки $$$c$$$ влево это операция, которая присваивает $$$c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$$$ одновременно. Аналогично, циклический сдвиг перестановки $$$c$$$ вправо это операция, которая присваивает $$$c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$$$ одновременно.</p><p>Помогите Ishika и Hriday найти наибольшее возможное число совпадающих пар в данных перестановках после применения описанных операций несколько (возможно, ноль) раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — размеры массивов.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le n)$$$ — элементы первой перестановки.</p><p>В третьей строке записаны $$$n$$$ целых чисел $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le n)$$$ — элементы второй перестановки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите наибольшее возможное число совпадающих пар в данных перестановках после применения описанных операций несколько (возможно, ноль) раз.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
1 2 3 4 5
2 3 4 5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
5 4 3 2 1
1 2 3 4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
1 3 2 4
4 2 3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно сдвинуть $$$b$$$ направо на $$$k = 1$$$. Получившиеся перестановки будут $$$\{1, 2, 3, 4, 5\}$$$ и $$$\{1, 2, 3, 4, 5\}$$$.</p><p>Во втором примере не требуется совершать никаких операций. По всем возможным сдвигам $$$a$$$ и $$$b$$$, число совпадающих пар не будет превышать $$$1$$$.</p><p>В третьем примере можно сдвинуть $$$b$$$ влево на $$$k = 1$$$. Получившиеся перестановки будут $$$\{1, 3, 2, 4\}$$$ и $$$\{2, 3, 1, 4\}$$$. Позиции $$$2$$$ и $$$4$$$ будут являться совпадающей парой. По всем возможным циклическим сдвигам $$$a$$$ и $$$b$$$, количество совпадающих пар не будет превышать $$$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="6c66ead092c38a7cfcea7b531e5d2cfc"/>
<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="d8c2a2171273b6908cd30c020410d21c6cf5711b"/>
<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='6c66ead092c38a7cfcea7b531e5d2cfc'> </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%2F1365%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='6c66ead092c38a7cfcea7b531e5d2cfc'/>
<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/1365">Codeforces Round 648 (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='6c66ead092c38a7cfcea7b531e5d2cfc'/>
<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/1365/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='6c66ead092c38a7cfcea7b531e5d2cfc'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="643138"/>
<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='6c66ead092c38a7cfcea7b531e5d2cfc'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="643138"/>
<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/78406" title="Codeforces Round #648 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11039" resourceName="Codeforces Round #648 (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/78504" title="Editorial — Codeforces Round #648" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11048" resourceName="Editorial — Codeforces Round #648"
resourceManual="true" src="//codeforces.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/1365">Задачи</a></li>
<li><a
href="/contest/1365/submit">Отослать</a></li>
<li><a
href="/contest/1365/my">Мои посылки</a></li>
<li><a
href="/contest/1365/status">Статус</a></li>
<li><a
href="/contest/1365/hacks">Взломы</a></li>
<li><a
href="/contest/1365/room/1">Комната</a></li>
<li><a
href="/contest/1365/standings">Положение</a></li>
<li><a
href="/contest/1365/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_e6c819960ba8205b350fdde49669d51bff0a787f">
<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>После мистического исчезнования Ashish, каждый из его любимых учеников Ishika и Hriday, получил одну половину секретного сообщения. Эти сообщения могут быть описаны перестановками размера $$$n$$$. Назовем их $$$a$$$ и $$$b$$$.</p><p>Напомним, что перестановка из $$$n$$$ элементов это последовательность чисел $$$a_1, a_2, \ldots, a_n$$$, в которой каждое число от $$$1$$$ до $$$n$$$ встречается ровно один раз. </p><p>Сообщение может быть расшифровано из конфигурации перестановок $$$a$$$ и $$$b$$$, в котором количество совпадающих пар элементов максимально. Пара элементов $$$a_i$$$ и $$$b_j$$$ называется совпадающей, если: </p><ul> <li> $$$i = j$$$, таким образом, у них один и тот же индекс. </li><li> $$$a_i = b_j$$$ </li></ul><p>Его ученикам разрешается совершать следующую операцию произвольное число раз: </p><ul> <li> выбрать число $$$k$$$ и циклически сдвинуть одну из перестановок влево или вправо $$$k$$$ раз. </li></ul><p>Циклический сдвиг перестановки $$$c$$$ влево это операция, которая присваивает $$$c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$$$ одновременно. Аналогично, циклический сдвиг перестановки $$$c$$$ вправо это операция, которая присваивает $$$c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$$$ одновременно.</p><p>Помогите Ishika и Hriday найти наибольшее возможное число совпадающих пар в данных перестановках после применения описанных операций несколько (возможно, ноль) раз.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — размеры массивов.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le n)$$$ — элементы первой перестановки.</p><p>В третьей строке записаны $$$n$$$ целых чисел $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le n)$$$ — элементы второй перестановки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите наибольшее возможное число совпадающих пар в данных перестановках после применения описанных операций несколько (возможно, ноль) раз.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
1 2 3 4 5
2 3 4 5 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5
5 4 3 2 1
1 2 3 4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
1 3 2 4
4 2 3 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно сдвинуть $$$b$$$ направо на $$$k = 1$$$. Получившиеся перестановки будут $$$\{1, 2, 3, 4, 5\}$$$ и $$$\{1, 2, 3, 4, 5\}$$$.</p><p>Во втором примере не требуется совершать никаких операций. По всем возможным сдвигам $$$a$$$ и $$$b$$$, число совпадающих пар не будет превышать $$$1$$$.</p><p>В третьем примере можно сдвинуть $$$b$$$ влево на $$$k = 1$$$. Получившиеся перестановки будут $$$\{1, 3, 2, 4\}$$$ и $$$\{2, 3, 1, 4\}$$$. Позиции $$$2$$$ и $$$4$$$ будут являться совпадающей парой. По всем возможным циклическим сдвигам $$$a$$$ и $$$b$$$, количество совпадающих пар не будет превышать $$$2$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:04: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:'8124a2eccd779d99',t:'MTY5NjY2NTg5OS4xMDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1400"] | ||
1365D | 1365 | 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>Vivek столкнулся с интересной задачей. У него есть лабиринт, который можно описать таблицей $$$n \times m$$$. Каждая клетка может быть одного из следующих типов:</p><ul> <li> Пустая — '<span class="tex-font-style-tt">.</span>' </li><li> Стена — '<span class="tex-font-style-tt">#</span>' </li><li> Хороший человек — '<span class="tex-font-style-tt">G</span>' </li><li> Плохой человек — '<span class="tex-font-style-tt">B</span>' </li></ul><p>Единственный выход из лабиринта находится в клетке $$$(n, m)$$$.</p><p>Человек может перейти в клетку если она не содержит стену и она имеет общую сторону с его текущей клеткой. Vivek хочет заблокировать (заменить на стены) некоторые пустые клетки, чтобы все хорошие люди могли дойти до выхода из лабиринта, но чтобы все плохие люди не могли. Клетку которая исходно содержит '<span class="tex-font-style-tt">G</span>' или '<span class="tex-font-style-tt">B</span>' нельзя блокировать, но через нее можно проходить.</p><p>Ваша задача — определить, можно ли заменить несколько (ноль или более) пустых клеток на стены, чтобы удовлетворить описанным ограничениям.</p><p>Гарантируется, что клетка $$$(n,m)$$$ пустая. Vivek <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 50)$$$ — количество строк и столбцов в лабиринте.</p><p>В каждой из следующих $$$n$$$ строк записаны $$$m$$$ символов. Они описывают исходный лабиринт. Если символ в строке равен '<span class="tex-font-style-tt">.</span>', тогда соответствующая клетка пустая, если символ равен '<span class="tex-font-style-tt">#</span>', тогда клетка содержит стену, а '<span class="tex-font-style-tt">G</span>' и '<span class="tex-font-style-tt">B</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><p>Вы можете выводить каждую букву в любом регистре (верхнем или нижнем).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
Yes
No
No
Yes
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и во втором наборах входных данных все условия уже выполнены.</p><p>В третьем наборе входных данных есть только одна свободная клетка $$$(2,2)$$$, и если мы заменим ее на стену, то хороший человек в клетке $$$(1,2)$$$ не сможет выйти.</p><p>В четвертом наборе входных данных хороший человек в клетке $$$(1,1)$$$ не может сбежать с самого начала, поэтому ответ «<span class="tex-font-style-tt">No</span>».</p><p>В пятом наборе входных данных можно заблокировать клетки $$$(2,3)$$$ и $$$(2,2)$$$.</p><p>В последнем наборе входных данных можно заблокировать выход $$$(2, 2)$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="3d8cf86c718fda5324fc8453fad7c4cf"/>
<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="d8c2a2171273b6908cd30c020410d21c6cf5711b"/>
<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='3d8cf86c718fda5324fc8453fad7c4cf'> </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%2F1365%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='3d8cf86c718fda5324fc8453fad7c4cf'/>
<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/1365">Codeforces Round 648 (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='3d8cf86c718fda5324fc8453fad7c4cf'/>
<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/1365/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="Сложность">
*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='3d8cf86c718fda5324fc8453fad7c4cf'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="643139"/>
<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='3d8cf86c718fda5324fc8453fad7c4cf'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="643139"/>
<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/78406" title="Codeforces Round #648 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11039" resourceName="Codeforces Round #648 (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/78504" title="Editorial — Codeforces Round #648" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11048" resourceName="Editorial — Codeforces Round #648"
resourceManual="true" src="//codeforces.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/1365">Задачи</a></li>
<li><a
href="/contest/1365/submit">Отослать</a></li>
<li><a
href="/contest/1365/my">Мои посылки</a></li>
<li><a
href="/contest/1365/status">Статус</a></li>
<li><a
href="/contest/1365/hacks">Взломы</a></li>
<li><a
href="/contest/1365/room/1">Комната</a></li>
<li><a
href="/contest/1365/standings">Положение</a></li>
<li><a
href="/contest/1365/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_852205e46b0cd88254aff6c15e7631e4038a4730">
<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>Vivek столкнулся с интересной задачей. У него есть лабиринт, который можно описать таблицей $$$n \times m$$$. Каждая клетка может быть одного из следующих типов:</p><ul> <li> Пустая — '<span class="tex-font-style-tt">.</span>' </li><li> Стена — '<span class="tex-font-style-tt">#</span>' </li><li> Хороший человек — '<span class="tex-font-style-tt">G</span>' </li><li> Плохой человек — '<span class="tex-font-style-tt">B</span>' </li></ul><p>Единственный выход из лабиринта находится в клетке $$$(n, m)$$$.</p><p>Человек может перейти в клетку если она не содержит стену и она имеет общую сторону с его текущей клеткой. Vivek хочет заблокировать (заменить на стены) некоторые пустые клетки, чтобы все хорошие люди могли дойти до выхода из лабиринта, но чтобы все плохие люди не могли. Клетку которая исходно содержит '<span class="tex-font-style-tt">G</span>' или '<span class="tex-font-style-tt">B</span>' нельзя блокировать, но через нее можно проходить.</p><p>Ваша задача — определить, можно ли заменить несколько (ноль или более) пустых клеток на стены, чтобы удовлетворить описанным ограничениям.</p><p>Гарантируется, что клетка $$$(n,m)$$$ пустая. Vivek <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 50)$$$ — количество строк и столбцов в лабиринте.</p><p>В каждой из следующих $$$n$$$ строк записаны $$$m$$$ символов. Они описывают исходный лабиринт. Если символ в строке равен '<span class="tex-font-style-tt">.</span>', тогда соответствующая клетка пустая, если символ равен '<span class="tex-font-style-tt">#</span>', тогда клетка содержит стену, а '<span class="tex-font-style-tt">G</span>' и '<span class="tex-font-style-tt">B</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><p>Вы можете выводить каждую букву в любом регистре (верхнем или нижнем).</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
1 1
.
1 2
G.
2 2
#B
G.
2 3
G.#
B#.
3 3
#B.
#..
GG.
2 2
#B
B.
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
Yes
Yes
No
No
Yes
Yes
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом и во втором наборах входных данных все условия уже выполнены.</p><p>В третьем наборе входных данных есть только одна свободная клетка $$$(2,2)$$$, и если мы заменим ее на стену, то хороший человек в клетке $$$(1,2)$$$ не сможет выйти.</p><p>В четвертом наборе входных данных хороший человек в клетке $$$(1,1)$$$ не может сбежать с самого начала, поэтому ответ «<span class="tex-font-style-tt">No</span>».</p><p>В пятом наборе входных данных можно заблокировать клетки $$$(2,3)$$$ и $$$(2,2)$$$.</p><p>В последнем наборе входных данных можно заблокировать выход $$$(2, 2)$$$.</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:05: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:'8124a2f51c029d4c',t:'MTY5NjY2NTkwMC40NTUwMDA='};_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\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", "\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\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", "\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043d\u043c", "*1700"] | ||
1365E | 1365 | 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>У Ashish есть массив $$$a$$$ длины $$$n$$$ состоящий из положительных целых чисел.</p><p>Определим значение непустой подпоследовательности массива $$$a$$$, состоящией из $$$k$$$ чисел, как $$$\sum 2^i$$$ по всем целым $$$i \ge 0$$$ таким, что хотя бы $$$\max(1, k - 2)$$$ чисел в этом подмножестве имеют $$$i$$$-й бит в своей двоичной записи (число $$$x$$$ имеет $$$i$$$-й бит в двоичной записи если $$$\lfloor \frac{x}{2^i} \rfloor \mod 2$$$ равно $$$1$$$). </p><p>Напомним, что $$$b$$$ является подпоследовательностью $$$a$$$, если $$$b$$$ может быть получена удалением нескольких (возможно, нуля) элементов из $$$a$$$.</p><p>Помогите ему найти наибольшее значение, которое он может получить, выбрав некоторую подпоследовательность $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 500)$$$ — размер массива $$$a$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел — элементы массива $$$(1 \le a_i \le 10^{18})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — наибольшее значение, которое Ashish может получить, выбрав некоторую подпоследовательность $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
2 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
3 1 4
</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>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
7 7 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Ashish может выбрать подпоследовательность $$$\{{2, 3}\}$$$ размера $$$2$$$. Двоичная запись $$$2$$$ это <span class="tex-font-style-tt">10</span> а двоичная запись $$$3$$$ это <span class="tex-font-style-tt">11</span>. Так как $$$\max(k - 2, 1)$$$ равно $$$1$$$, значение подпоследовательности равно $$$2^0 + 2^1$$$ (и у $$$2$$$ и у $$$3$$$ есть $$$1$$$-й бит в двоичной записи, а у $$$3$$$ также есть $$$0$$$-й бит в двоичной записи). Обратите внимание, что он также мог выбрать подпоследовательность $$$\{{3\}}$$$ или $$$\{{1, 2, 3\}}$$$.</p><p>Во втором примере Ashish может выбрать подпоследовательность $$$\{{3, 4\}}$$$ со значением $$$7$$$.</p><p>В третьем примере Ashish может выбрать подпоследовательность $$$\{{1\}}$$$ со значением $$$1$$$.</p><p>В четвертом примере Ashish может выбрать подпоследовательность $$$\{{7, 7\}}$$$ со значением $$$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="15bcc4d6779ec9421650ef3d3b07481c"/>
<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="d8c2a2171273b6908cd30c020410d21c6cf5711b"/>
<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='15bcc4d6779ec9421650ef3d3b07481c'> </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%2F1365%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='15bcc4d6779ec9421650ef3d3b07481c'/>
<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/1365">Codeforces Round 648 (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='15bcc4d6779ec9421650ef3d3b07481c'/>
<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/1365/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="Сложность">
*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='15bcc4d6779ec9421650ef3d3b07481c'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="643140"/>
<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='15bcc4d6779ec9421650ef3d3b07481c'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="643140"/>
<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/78406" title="Codeforces Round #648 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11039" resourceName="Codeforces Round #648 (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/78504" title="Editorial — Codeforces Round #648" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11048" resourceName="Editorial — Codeforces Round #648"
resourceManual="true" src="//codeforces.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/1365">Задачи</a></li>
<li><a
href="/contest/1365/submit">Отослать</a></li>
<li><a
href="/contest/1365/my">Мои посылки</a></li>
<li><a
href="/contest/1365/status">Статус</a></li>
<li><a
href="/contest/1365/hacks">Взломы</a></li>
<li><a
href="/contest/1365/room/1">Комната</a></li>
<li><a
href="/contest/1365/standings">Положение</a></li>
<li><a
href="/contest/1365/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_8c32aa862b4b30edaf2bd207fddfca4d56fc7d80">
<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>У Ashish есть массив $$$a$$$ длины $$$n$$$ состоящий из положительных целых чисел.</p><p>Определим значение непустой подпоследовательности массива $$$a$$$, состоящией из $$$k$$$ чисел, как $$$\sum 2^i$$$ по всем целым $$$i \ge 0$$$ таким, что хотя бы $$$\max(1, k - 2)$$$ чисел в этом подмножестве имеют $$$i$$$-й бит в своей двоичной записи (число $$$x$$$ имеет $$$i$$$-й бит в двоичной записи если $$$\lfloor \frac{x}{2^i} \rfloor \mod 2$$$ равно $$$1$$$). </p><p>Напомним, что $$$b$$$ является подпоследовательностью $$$a$$$, если $$$b$$$ может быть получена удалением нескольких (возможно, нуля) элементов из $$$a$$$.</p><p>Помогите ему найти наибольшее значение, которое он может получить, выбрав некоторую подпоследовательность $$$a$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(1 \le n \le 500)$$$ — размер массива $$$a$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел — элементы массива $$$(1 \le a_i \le 10^{18})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — наибольшее значение, которое Ashish может получить, выбрав некоторую подпоследовательность $$$a$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
2 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
3 1 4
</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>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
7 7 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Ashish может выбрать подпоследовательность $$$\{{2, 3}\}$$$ размера $$$2$$$. Двоичная запись $$$2$$$ это <span class="tex-font-style-tt">10</span> а двоичная запись $$$3$$$ это <span class="tex-font-style-tt">11</span>. Так как $$$\max(k - 2, 1)$$$ равно $$$1$$$, значение подпоследовательности равно $$$2^0 + 2^1$$$ (и у $$$2$$$ и у $$$3$$$ есть $$$1$$$-й бит в двоичной записи, а у $$$3$$$ также есть $$$0$$$-й бит в двоичной записи). Обратите внимание, что он также мог выбрать подпоследовательность $$$\{{3\}}$$$ или $$$\{{1, 2, 3\}}$$$.</p><p>Во втором примере Ashish может выбрать подпоследовательность $$$\{{3, 4\}}$$$ со значением $$$7$$$.</p><p>В третьем примере Ashish может выбрать подпоследовательность $$$\{{1\}}$$$ со значением $$$1$$$.</p><p>В четвертом примере Ashish может выбрать подпоследовательность $$$\{{7, 7\}}$$$ со значением $$$7$$$.</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:05: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:'8124a2fd8dae9d99',t:'MTY5NjY2NTkwMS45MDAwMDA='};_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\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1900"] | ||
1365F | 1365 | 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>Ayush, Ashish и Vivek заняты подготовкой задачи для следующего Codeforces раунда и им нужно помочь проверить тесты на корректность.</p><p>Каждый набор входных данных состоит из $$$n$$$ и двух массивов $$$a$$$ и $$$b$$$, длины $$$n$$$. Если после скольки-то (возможно, нуля) операций описанных ниже, массив $$$a$$$ может стать равен массиву $$$b$$$, тест считается <span class="tex-font-style-tt">корректным</span>. Иначе, он <span class="tex-font-style-tt">некорректный</span>.</p><p>Возможные операции на массиве $$$a$$$ следующие: </p><ul> <li> выберите целое число $$$k$$$ $$$(1 \le k \le \lfloor\frac{n}{2}\rfloor)$$$ </li><li> поменяйте местами префикс длины $$$k$$$ с суффиксом длины $$$k$$$ </li></ul><p>Например, если массив $$$a$$$ исходно равен $$$\{1, 2, 3, 4, 5, 6\}$$$, после выполнения операции с $$$k = 2$$$, он превратится в $$$\{5, 6, 3, 4, 1, 2\}$$$.</p><p>Вам дано несколько наборов входных данных, помогите определить про каждый из них, <span class="tex-font-style-tt">корректный</span> он или <span class="tex-font-style-tt">некорректный</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ $$$(1 \le t \le 500)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ $$$(1 \le n \le 500)$$$ — размеры массивов.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — элементы массива $$$a$$$.</p><p>В третьей строке записаны $$$n$$$ целых чисел $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le 10^9)$$$ — элементы массива $$$b$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите «<span class="tex-font-style-tt">Yes</span>», если данный ввод <span class="tex-font-style-tt">корректный</span>. Иначе, выведите «<span class="tex-font-style-tt">No</span>».</p><p>Вы можете выводить все символы в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2
1 2
2 1
3
1 2 3
1 2 3
3
1 2 4
1 3 4
4
1 2 3 2
3 1 2 2
3
1 2 3
1 3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
yes
yes
No
yes
No
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно поменять местами префикс $$$a[1:1]$$$ с суффиксом $$$a[2:2]$$$, чтобы получить $$$a=[2, 1]$$$.</p><p>Во втором наборе входных данных $$$a$$$ уже равен $$$b$$$.</p><p>В третьем наборе входных данных невозможно получить $$$3$$$ в $$$a$$$.</p><p>В четвертом наборе входных данных сначала можно поменять местами префикс $$$a[1:1]$$$ с суффиксом $$$a[4:4]$$$, чтобы получить $$$a=[2, 2, 3, 1]$$$. После этого можно поменять местами префикс $$$a[1:2]$$$ с суффиксом $$$a[3:4]$$$, чтобы получить $$$a=[3, 1, 2, 2]$$$.</p><p>В пятом наборе входных данных невозможно превратить $$$a$$$ в $$$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="41bf9af9943b901416a4a11a813e3638"/>
<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="d8c2a2171273b6908cd30c020410d21c6cf5711b"/>
<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='41bf9af9943b901416a4a11a813e3638'> </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%2F1365%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='41bf9af9943b901416a4a11a813e3638'/>
<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/1365">Codeforces Round 648 (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='41bf9af9943b901416a4a11a813e3638'/>
<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/1365/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="Сложность">
*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='41bf9af9943b901416a4a11a813e3638'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="643141"/>
<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='41bf9af9943b901416a4a11a813e3638'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="643141"/>
<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/78406" title="Codeforces Round #648 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11039" resourceName="Codeforces Round #648 (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/78504" title="Editorial — Codeforces Round #648" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11048" resourceName="Editorial — Codeforces Round #648"
resourceManual="true" src="//codeforces.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/1365">Задачи</a></li>
<li><a
href="/contest/1365/submit">Отослать</a></li>
<li><a
href="/contest/1365/my">Мои посылки</a></li>
<li><a
href="/contest/1365/status">Статус</a></li>
<li><a
href="/contest/1365/hacks">Взломы</a></li>
<li><a
href="/contest/1365/room/1">Комната</a></li>
<li><a
href="/contest/1365/standings">Положение</a></li>
<li><a
href="/contest/1365/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_a991a4e5531a68c144d37758e7e970229ae79c42">
<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>Ayush, Ashish и Vivek заняты подготовкой задачи для следующего Codeforces раунда и им нужно помочь проверить тесты на корректность.</p><p>Каждый набор входных данных состоит из $$$n$$$ и двух массивов $$$a$$$ и $$$b$$$, длины $$$n$$$. Если после скольки-то (возможно, нуля) операций описанных ниже, массив $$$a$$$ может стать равен массиву $$$b$$$, тест считается <span class="tex-font-style-tt">корректным</span>. Иначе, он <span class="tex-font-style-tt">некорректный</span>.</p><p>Возможные операции на массиве $$$a$$$ следующие: </p><ul> <li> выберите целое число $$$k$$$ $$$(1 \le k \le \lfloor\frac{n}{2}\rfloor)$$$ </li><li> поменяйте местами префикс длины $$$k$$$ с суффиксом длины $$$k$$$ </li></ul><p>Например, если массив $$$a$$$ исходно равен $$$\{1, 2, 3, 4, 5, 6\}$$$, после выполнения операции с $$$k = 2$$$, он превратится в $$$\{5, 6, 3, 4, 1, 2\}$$$.</p><p>Вам дано несколько наборов входных данных, помогите определить про каждый из них, <span class="tex-font-style-tt">корректный</span> он или <span class="tex-font-style-tt">некорректный</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ $$$(1 \le t \le 500)$$$ — количество наборов входных данных. Далее следуют описания наборов входных данных.</p><p>В первой строке каждого набора входных данных записано одно целое число $$$n$$$ $$$(1 \le n \le 500)$$$ — размеры массивов.</p><p>Во второй строке записаны $$$n$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — элементы массива $$$a$$$.</p><p>В третьей строке записаны $$$n$$$ целых чисел $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le 10^9)$$$ — элементы массива $$$b$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите «<span class="tex-font-style-tt">Yes</span>», если данный ввод <span class="tex-font-style-tt">корректный</span>. Иначе, выведите «<span class="tex-font-style-tt">No</span>».</p><p>Вы можете выводить все символы в любом регистре.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
2
1 2
2 1
3
1 2 3
1 2 3
3
1 2 4
1 3 4
4
1 2 3 2
3 1 2 2
3
1 2 3
1 3 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
yes
yes
No
yes
No
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно поменять местами префикс $$$a[1:1]$$$ с суффиксом $$$a[2:2]$$$, чтобы получить $$$a=[2, 1]$$$.</p><p>Во втором наборе входных данных $$$a$$$ уже равен $$$b$$$.</p><p>В третьем наборе входных данных невозможно получить $$$3$$$ в $$$a$$$.</p><p>В четвертом наборе входных данных сначала можно поменять местами префикс $$$a[1:1]$$$ с суффиксом $$$a[4:4]$$$, чтобы получить $$$a=[2, 2, 3, 1]$$$. После этого можно поменять местами префикс $$$a[1:2]$$$ с суффиксом $$$a[3:4]$$$, чтобы получить $$$a=[3, 1, 2, 2]$$$.</p><p>В пятом наборе входных данных невозможно превратить $$$a$$$ в $$$b$$$.</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:05: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:'8124a3075d0116f7',t:'MTY5NjY2NTkwMy4zMzMwMDA='};_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\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2100"] | ||
1365G | 1365 | 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><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Ayush придумал еще один способ задать пароль для своего замка. В замке есть $$$n$$$ слотов, в каждом слоте может находится любое неотрицательное целое число. Пароль $$$P$$$ это последовательность из $$$n$$$ целых чисел, $$$i$$$-й из которых соответствует $$$i$$$-му слоту замка.</p><p>Чтобы задать пароль, Ayush придумал последовательность $$$A$$$ из $$$n$$$ целых чисел из отрезка $$$[0, 2^{63}-1]$$$. Затем, он определил $$$i$$$-й элемент $$$P$$$ как <a href="https://en.wikipedia.org/wiki/Bitwise_operation#OR">побитовое ИЛИ</a> всех чисел в массиве кроме $$$A_i$$$.</p><p>Вам нужно отгадать пароль. Чтобы задать запрос, вы можете выбрать непустое подмножество индексов массива и спросить <span class="tex-font-style-bf">побитовое ИЛИ</span> всех элементов массива с индексами в этом подмножестве. <span class="tex-font-style-bf">Вы можете задать не более 13 запросов</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(2 \le n \le 1000)$$$ — количество слотов в замке.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы задать вопрос, в отдельной строке: </p><ul> <li> Сначала выведите «<span class="tex-font-style-tt">? c</span>» (без кавычек), где $$$c$$$ $$$(1 \leq c \leq n)$$$ обозначает размер подмножества запроса, после чего выведите $$$c$$$ <span class="tex-font-style-bf">различных</span> целых чисел из отрезка $$$[1, n]$$$, разделенных пробелами. </li></ul><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$$$ $$$(2 \le n \le 1000)$$$ — количество слотов в замке. Во второй строке выведите $$$n$$$ целых чисел из отрезка $$$[0, 2^{63} - 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>
3
1
2
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 1
? 1 2
? 1 3
! 6 5 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Массив $$$A$$$ в примере это $$$\{{1, 2, 4\}}$$$. Первый элемент пароля это побитовое ИЛИ элементов $$$A_2$$$ и $$$A_3$$$, второй элемент это побитовое ИЛИ элементов $$$A_1$$$ и $$$A_3$$$, а третий элемент это побитовое ИЛИ элементов $$$A_1$$$ и $$$A_2$$$. Таким образом, пароль равен $$$\{{6, 5, 3\}}$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="ba17e4e0a9e0e98c5358899acc584792"/>
<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="d8c2a2171273b6908cd30c020410d21c6cf5711b"/>
<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='ba17e4e0a9e0e98c5358899acc584792'> </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%2F1365%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='ba17e4e0a9e0e98c5358899acc584792'/>
<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/1365">Codeforces Round 648 (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='ba17e4e0a9e0e98c5358899acc584792'/>
<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/1365/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Битовые маски">
битмаски
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика">
комбинаторика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ba17e4e0a9e0e98c5358899acc584792'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="643142"/>
<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='ba17e4e0a9e0e98c5358899acc584792'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="643142"/>
<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/78406" title="Codeforces Round #648 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11039" resourceName="Codeforces Round #648 (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/78504" title="Editorial — Codeforces Round #648" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11048" resourceName="Editorial — Codeforces Round #648"
resourceManual="true" src="//codeforces.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/1365">Задачи</a></li>
<li><a
href="/contest/1365/submit">Отослать</a></li>
<li><a
href="/contest/1365/my">Мои посылки</a></li>
<li><a
href="/contest/1365/status">Статус</a></li>
<li><a
href="/contest/1365/hacks">Взломы</a></li>
<li><a
href="/contest/1365/room/1">Комната</a></li>
<li><a
href="/contest/1365/standings">Положение</a></li>
<li><a
href="/contest/1365/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_ef89c02b574fc251090f8126e47b5be083f76d56">
<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><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Ayush придумал еще один способ задать пароль для своего замка. В замке есть $$$n$$$ слотов, в каждом слоте может находится любое неотрицательное целое число. Пароль $$$P$$$ это последовательность из $$$n$$$ целых чисел, $$$i$$$-й из которых соответствует $$$i$$$-му слоту замка.</p><p>Чтобы задать пароль, Ayush придумал последовательность $$$A$$$ из $$$n$$$ целых чисел из отрезка $$$[0, 2^{63}-1]$$$. Затем, он определил $$$i$$$-й элемент $$$P$$$ как <a href="https://en.wikipedia.org/wiki/Bitwise_operation#OR">побитовое ИЛИ</a> всех чисел в массиве кроме $$$A_i$$$.</p><p>Вам нужно отгадать пароль. Чтобы задать запрос, вы можете выбрать непустое подмножество индексов массива и спросить <span class="tex-font-style-bf">побитовое ИЛИ</span> всех элементов массива с индексами в этом подмножестве. <span class="tex-font-style-bf">Вы можете задать не более 13 запросов</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ $$$(2 \le n \le 1000)$$$ — количество слотов в замке.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Чтобы задать вопрос, в отдельной строке: </p><ul> <li> Сначала выведите «<span class="tex-font-style-tt">? c</span>» (без кавычек), где $$$c$$$ $$$(1 \leq c \leq n)$$$ обозначает размер подмножества запроса, после чего выведите $$$c$$$ <span class="tex-font-style-bf">различных</span> целых чисел из отрезка $$$[1, n]$$$, разделенных пробелами. </li></ul><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$$$ $$$(2 \le n \le 1000)$$$ — количество слотов в замке. Во второй строке выведите $$$n$$$ целых чисел из отрезка $$$[0, 2^{63} - 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>
3
1
2
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 1
? 1 2
? 1 3
! 6 5 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Массив $$$A$$$ в примере это $$$\{{1, 2, 4\}}$$$. Первый элемент пароля это побитовое ИЛИ элементов $$$A_2$$$ и $$$A_3$$$, второй элемент это побитовое ИЛИ элементов $$$A_1$$$ и $$$A_3$$$, а третий элемент это побитовое ИЛИ элементов $$$A_1$$$ и $$$A_2$$$. Таким образом, пароль равен $$$\{{6, 5, 3\}}$$$.</p></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:05: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:'8124a30fad3675b7',t:'MTY5NjY2NTkwNC42NzUwMDA='};_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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\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\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2800"] | ||
1366A | 1366 | A | ru | A. Лопаты и мечи | <div class="problem-statement"><div class="header"><div class="title">A. Лопаты и мечи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в известную компьютерную игру (мы не хотим упоминать ее название). В этой игре он может создавать инструменты двух видов — лопаты и мечи. На создание лопаты Поликарп тратит две палки и один алмаз; на создание меча Поликарп тратит два алмаза и одну палку.</p><p>Каждый инструмент может быть продан за один изумруд. Как много изумрудов может заработать Поликарп, если у него есть $$$a$$$ палок и $$$b$$$ алмазов?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Единственная строка каждого набора входных данных содержит два числа $$$a$$$ и $$$b$$$ ($$$0 \le a, b \le 10^9$$$) — количество палок и алмазов соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите число — максимальное количество изумрудов, которое может заработать Поликарп.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4 4
1000000000 0
7 15
8 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
0
7
5
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Поликарп может заработать два изумруда следующим образом: создать один меч и одну лопату.</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="475c90970eed7197b9bf51c3440bf409"/>
<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="f96a2e386da9fe6b986fc55c7cdbe1e5d8fabcb3"/>
<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='475c90970eed7197b9bf51c3440bf409'> </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%2F1366%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='475c90970eed7197b9bf51c3440bf409'/>
<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/1366">Educational Codeforces Round 89 (рейтинговый для Див. 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='475c90970eed7197b9bf51c3440bf409'/>
<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/1366/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='475c90970eed7197b9bf51c3440bf409'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="646799"/>
<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='475c90970eed7197b9bf51c3440bf409'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="646799"/>
<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/78633" title="Educational Codeforces Round 89 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11307:11308" 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/78735" title="Разбор Educational Codeforces Round 89" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11305:11306" 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/1366">Задачи</a></li>
<li><a
href="/contest/1366/submit">Отослать</a></li>
<li><a
href="/contest/1366/my">Мои посылки</a></li>
<li><a
href="/contest/1366/status">Статус</a></li>
<li><a
href="/contest/1366/hacks">Взломы</a></li>
<li><a
href="/contest/1366/standings">Положение</a></li>
<li><a
href="/contest/1366/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_6f8a469719b229f732de6020036970d9224d890a">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Лопаты и мечи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп играет в известную компьютерную игру (мы не хотим упоминать ее название). В этой игре он может создавать инструменты двух видов — лопаты и мечи. На создание лопаты Поликарп тратит две палки и один алмаз; на создание меча Поликарп тратит два алмаза и одну палку.</p><p>Каждый инструмент может быть продан за один изумруд. Как много изумрудов может заработать Поликарп, если у него есть $$$a$$$ палок и $$$b$$$ алмазов?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов входных данных.</p><p>Единственная строка каждого набора входных данных содержит два числа $$$a$$$ и $$$b$$$ ($$$0 \le a, b \le 10^9$$$) — количество палок и алмазов соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите число — максимальное количество изумрудов, которое может заработать Поликарп.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4 4
1000000000 0
7 15
8 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
0
7
5
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных Поликарп может заработать два изумруда следующим образом: создать один меч и одну лопату.</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:05: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:'8124a31819979d3a',t:'MTY5NjY2NTkwNi4xMzEwMDA='};_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\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", "*1100"] | ||
1366B | 1366 | 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$$$ чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Изначально $$$a_x = 1$$$, а остальные элементы равны $$$0$$$.</p><p>Вы выполняете $$$m$$$ операций. Во время $$$i$$$-й операции вы выбираете два индекса $$$c$$$ и $$$d$$$ таких, что $$$l_i \le c, d \le r_i$$$, и меняете местами $$$a_c$$$ и $$$a_d$$$.</p><p>Посчитайте количество индексов $$$k$$$ таких, что существуют возможность выбрать операции так, что в конце $$$a_k = 1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных. Затем следует описание каждого из $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит три целых числа $$$n$$$, $$$x$$$ и $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$).</p><p>Каждая из следующих $$$m$$$ строк содержит описание операций; а именно — в $$$i$$$-й строке содержится два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно число — количество индексов $$$k$$$ таких, что существуют возможность выбрать операции так, что в конце $$$a_k = 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
6 4 3
1 6
2 3
5 5
4 1 2
2 4
1 2
3 3 2
2 3
1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
2
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных условие $$$a_k = 1$$$ выполняется для любого $$$k$$$. Для этого, можно выполнить следующие операции:</p><ol> <li> поменять местами $$$a_k$$$ и $$$a_4$$$; </li><li> поменять местами $$$a_2$$$ и $$$a_2$$$; </li><li> поменять местами $$$a_5$$$ и $$$a_5$$$. </li></ol><p>Во втором наборе входных данных подходят только индексы $$$k = 1$$$ и $$$k = 2$$$. Для выполнения $$$a_1 = 1$$$, нужно поменять местами $$$a_1$$$ и $$$a_1$$$ во второй операции. Для выполнения $$$a_2 = 1$$$, нужно поменять местами $$$a_1$$$ и $$$a_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="0d8c3a975b05b5c2a046586c33d983ef"/>
<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="f96a2e386da9fe6b986fc55c7cdbe1e5d8fabcb3"/>
<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='0d8c3a975b05b5c2a046586c33d983ef'> </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%2F1366%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='0d8c3a975b05b5c2a046586c33d983ef'/>
<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/1366">Educational Codeforces Round 89 (рейтинговый для Див. 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='0d8c3a975b05b5c2a046586c33d983ef'/>
<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/1366/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='0d8c3a975b05b5c2a046586c33d983ef'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="646800"/>
<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='0d8c3a975b05b5c2a046586c33d983ef'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="646800"/>
<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/78633" title="Educational Codeforces Round 89 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11307:11308" 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/78735" title="Разбор Educational Codeforces Round 89" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11305:11306" 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/1366">Задачи</a></li>
<li><a
href="/contest/1366/submit">Отослать</a></li>
<li><a
href="/contest/1366/my">Мои посылки</a></li>
<li><a
href="/contest/1366/status">Статус</a></li>
<li><a
href="/contest/1366/hacks">Взломы</a></li>
<li><a
href="/contest/1366/standings">Положение</a></li>
<li><a
href="/contest/1366/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_2696b8f7e821d1b8ab5e5f5a761790d33c2405d4">
<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$$$ чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Изначально $$$a_x = 1$$$, а остальные элементы равны $$$0$$$.</p><p>Вы выполняете $$$m$$$ операций. Во время $$$i$$$-й операции вы выбираете два индекса $$$c$$$ и $$$d$$$ таких, что $$$l_i \le c, d \le r_i$$$, и меняете местами $$$a_c$$$ и $$$a_d$$$.</p><p>Посчитайте количество индексов $$$k$$$ таких, что существуют возможность выбрать операции так, что в конце $$$a_k = 1$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов входных данных. Затем следует описание каждого из $$$t$$$ наборов входных данных.</p><p>Первая строка каждого набора входных данных содержит три целых числа $$$n$$$, $$$x$$$ и $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$).</p><p>Каждая из следующих $$$m$$$ строк содержит описание операций; а именно — в $$$i$$$-й строке содержится два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый набор входных данных выведите одно число — количество индексов $$$k$$$ таких, что существуют возможность выбрать операции так, что в конце $$$a_k = 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
6 4 3
1 6
2 3
5 5
4 1 2
2 4
1 2
3 3 2
2 3
1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
2
3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных условие $$$a_k = 1$$$ выполняется для любого $$$k$$$. Для этого, можно выполнить следующие операции:</p><ol> <li> поменять местами $$$a_k$$$ и $$$a_4$$$; </li><li> поменять местами $$$a_2$$$ и $$$a_2$$$; </li><li> поменять местами $$$a_5$$$ и $$$a_5$$$. </li></ol><p>Во втором наборе входных данных подходят только индексы $$$k = 1$$$ и $$$k = 2$$$. Для выполнения $$$a_1 = 1$$$, нужно поменять местами $$$a_1$$$ и $$$a_1$$$ во второй операции. Для выполнения $$$a_2 = 1$$$, нужно поменять местами $$$a_1$$$ и $$$a_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:05: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:'8124a3210fbb16ec',t:'MTY5NjY2NTkwNy41NTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1300"] | ||
1366C | 1366 | 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.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>Вам задана матрица из $$$n$$$ строк (пронумерованных от $$$1$$$ до $$$n$$$) и $$$m$$$ столбцов (пронумерованных от $$$1$$$ до $$$m$$$). Обозначим за $$$a_{i, j}$$$ число в клетке на пересечении $$$i$$$-й строки и $$$j$$$-го столбца, каждое число либо $$$0$$$, либо $$$1$$$.</p><p>Изначально в ячейке $$$(1, 1)$$$ находится фишка, которая будет перемещена в ячейку $$$(n, m)$$$ при помощи последовательности шагов. На каждом шаге фишка перемещается либо в ячейку справа от текущей, либо в ячейку снизу (если фишка сейчас в ячейке $$$(x, y)$$$, ее можно переместить либо в $$$(x + 1, y)$$$, либо в $$$(x, y + 1)$$$). Фишка не может покидать матрицу.</p><p>Рассмотрим все пути фишки из ячейки $$$(1, 1)$$$ в ячейку $$$(n, m)$$$. Назовем путь <span class="tex-font-style-it">палиндромным</span>, если число в первой ячейке пути равно числу в последней ячейке пути, число во второй ячейке равно числу в предпоследней ячейке, и так далее.</p><p>Ваша цель — заменить минимальное количество элементов матрицы так, чтобы <span class="tex-font-style-bf">все</span> пути стали <span class="tex-font-style-it">палиндромными</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 200$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора заданы два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n, m \le 30$$$) — размеры матрицы.</p><p>Затем следуют $$$n$$$ строк, $$$i$$$-я из которых содержит $$$m$$$ целых чисел $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).</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 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
3
4
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Итоговые матрицы в первых трех примерах:</p><center> $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ </center><center> $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ </center><center> $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ </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="ebce4337ba06e5aa276e3cb637423739"/>
<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="f96a2e386da9fe6b986fc55c7cdbe1e5d8fabcb3"/>
<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='ebce4337ba06e5aa276e3cb637423739'> </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%2F1366%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='ebce4337ba06e5aa276e3cb637423739'/>
<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/1366">Educational Codeforces Round 89 (рейтинговый для Див. 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='ebce4337ba06e5aa276e3cb637423739'/>
<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/1366/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ebce4337ba06e5aa276e3cb637423739'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="646801"/>
<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='ebce4337ba06e5aa276e3cb637423739'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="646801"/>
<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/78633" title="Educational Codeforces Round 89 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11307:11308" 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/78735" title="Разбор Educational Codeforces Round 89" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11305:11306" 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/1366">Задачи</a></li>
<li><a
href="/contest/1366/submit">Отослать</a></li>
<li><a
href="/contest/1366/my">Мои посылки</a></li>
<li><a
href="/contest/1366/status">Статус</a></li>
<li><a
href="/contest/1366/hacks">Взломы</a></li>
<li><a
href="/contest/1366/standings">Положение</a></li>
<li><a
href="/contest/1366/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_3b775ed7abbfacb264bfe5ef65f8f48e7b0aab0f">
<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.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>Вам задана матрица из $$$n$$$ строк (пронумерованных от $$$1$$$ до $$$n$$$) и $$$m$$$ столбцов (пронумерованных от $$$1$$$ до $$$m$$$). Обозначим за $$$a_{i, j}$$$ число в клетке на пересечении $$$i$$$-й строки и $$$j$$$-го столбца, каждое число либо $$$0$$$, либо $$$1$$$.</p><p>Изначально в ячейке $$$(1, 1)$$$ находится фишка, которая будет перемещена в ячейку $$$(n, m)$$$ при помощи последовательности шагов. На каждом шаге фишка перемещается либо в ячейку справа от текущей, либо в ячейку снизу (если фишка сейчас в ячейке $$$(x, y)$$$, ее можно переместить либо в $$$(x + 1, y)$$$, либо в $$$(x, y + 1)$$$). Фишка не может покидать матрицу.</p><p>Рассмотрим все пути фишки из ячейки $$$(1, 1)$$$ в ячейку $$$(n, m)$$$. Назовем путь <span class="tex-font-style-it">палиндромным</span>, если число в первой ячейке пути равно числу в последней ячейке пути, число во второй ячейке равно числу в предпоследней ячейке, и так далее.</p><p>Ваша цель — заменить минимальное количество элементов матрицы так, чтобы <span class="tex-font-style-bf">все</span> пути стали <span class="tex-font-style-it">палиндромными</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 200$$$) — количество наборов входных данных.</p><p>В первой строке каждого набора заданы два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n, m \le 30$$$) — размеры матрицы.</p><p>Затем следуют $$$n$$$ строк, $$$i$$$-я из которых содержит $$$m$$$ целых чисел $$$a_{i, 1}$$$, $$$a_{i, 2}$$$, ..., $$$a_{i, m}$$$ ($$$0 \le a_{i, j} \le 1$$$).</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 2
1 1
0 1
2 3
1 1 0
1 0 0
3 7
1 0 1 1 1 1 1
0 0 0 0 0 0 0
1 1 1 1 1 0 1
3 5
1 0 1 0 0
1 1 1 1 0
0 0 1 0 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
3
4
4
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Итоговые матрицы в первых трех примерах:</p><center> $$$\begin{pmatrix} 1 & 1\\ 0 & 1 \end{pmatrix}$$$ </center><center> $$$\begin{pmatrix} 0 & 0 & 0\\ 0 & 0 & 0 \end{pmatrix}$$$ </center><center> $$$\begin{pmatrix} 1 & 0 & 1 & 1 & 1 & 1 & 1\\ 0 & 1 & 1 & 0 & 1 & 1 & 0\\ 1 & 1 & 1 & 1 & 1 & 0 & 1 \end{pmatrix}$$$ </center></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:05: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:'8124a329ec46160a',t:'MTY5NjY2NTkwOC44ODYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1500"] | ||
1366D | 1366 | D | ru | D. Два делителя | <div class="problem-statement"><div class="header"><div class="title">D. Два делителя</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$.</p><p>Для каждого $$$a_i$$$ найдите <span class="tex-font-style-bf">два его делителя</span> $$$d_1 > 1$$$ и $$$d_2 > 1$$$ такие, что $$$\gcd(d_1 + d_2, a_i) = 1$$$ (где $$$\gcd(a, b)$$$ — наибольший общий делитель $$$a$$$ и $$$b$$$) или скажите, что такой пары нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — размер массива $$$a$$$.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 10^7$$$) — массив $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Ради ускорения вывода, выведите ответы в две строки по $$$n$$$ чисел в каждой.</p><p>В первой и второй строках $$$i$$$-ми по счету числами выведите соответствующие делители $$$d_1 > 1$$$ и $$$d_2 > 1$$$ такие, что $$$\gcd(d_1 + d_2, a_i) = 1$$$ или $$$-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>
10
2 3 4 5 6 7 8 9 10 24
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1 -1 -1 -1 3 -1 -1 -1 2 2
-1 -1 -1 -1 2 -1 -1 -1 5 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим $$$a_7 = 8$$$. У него есть $$$3$$$ делителя больших, чем $$$1$$$: $$$2$$$, $$$4$$$, $$$8$$$. Не сложно заметить, что сумма любой пары делителей делится на $$$2$$$, также как и $$$a_7$$$.</p><p>Существуют и другие подходящие пары делителей $$$d_1$$$ и $$$d_2$$$ для $$$a_{10}=24$$$, например, $$$(3, 4)$$$ или $$$(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="1d534bf683eb76b39ca3ac37061378eb"/>
<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="f96a2e386da9fe6b986fc55c7cdbe1e5d8fabcb3"/>
<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='1d534bf683eb76b39ca3ac37061378eb'> </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%2F1366%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='1d534bf683eb76b39ca3ac37061378eb'/>
<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/1366">Educational Codeforces Round 89 (рейтинговый для Див. 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='1d534bf683eb76b39ca3ac37061378eb'/>
<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/1366/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='1d534bf683eb76b39ca3ac37061378eb'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="646802"/>
<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='1d534bf683eb76b39ca3ac37061378eb'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="646802"/>
<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/78633" title="Educational Codeforces Round 89 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11307:11308" 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/78735" title="Разбор Educational Codeforces Round 89" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11305:11306" 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/1366">Задачи</a></li>
<li><a
href="/contest/1366/submit">Отослать</a></li>
<li><a
href="/contest/1366/my">Мои посылки</a></li>
<li><a
href="/contest/1366/status">Статус</a></li>
<li><a
href="/contest/1366/hacks">Взломы</a></li>
<li><a
href="/contest/1366/standings">Положение</a></li>
<li><a
href="/contest/1366/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_d877482267be7c3770087d571900ee8bb27a9bee">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Два делителя</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$.</p><p>Для каждого $$$a_i$$$ найдите <span class="tex-font-style-bf">два его делителя</span> $$$d_1 > 1$$$ и $$$d_2 > 1$$$ такие, что $$$\gcd(d_1 + d_2, a_i) = 1$$$ (где $$$\gcd(a, b)$$$ — наибольший общий делитель $$$a$$$ и $$$b$$$) или скажите, что такой пары нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — размер массива $$$a$$$.</p><p>Во второй строке заданы $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$2 \le a_i \le 10^7$$$) — массив $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Ради ускорения вывода, выведите ответы в две строки по $$$n$$$ чисел в каждой.</p><p>В первой и второй строках $$$i$$$-ми по счету числами выведите соответствующие делители $$$d_1 > 1$$$ и $$$d_2 > 1$$$ такие, что $$$\gcd(d_1 + d_2, a_i) = 1$$$ или $$$-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>
10
2 3 4 5 6 7 8 9 10 24
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1 -1 -1 -1 3 -1 -1 -1 2 2
-1 -1 -1 -1 2 -1 -1 -1 5 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим $$$a_7 = 8$$$. У него есть $$$3$$$ делителя больших, чем $$$1$$$: $$$2$$$, $$$4$$$, $$$8$$$. Не сложно заметить, что сумма любой пары делителей делится на $$$2$$$, также как и $$$a_7$$$.</p><p>Существуют и другие подходящие пары делителей $$$d_1$$$ и $$$d_2$$$ для $$$a_{10}=24$$$, например, $$$(3, 4)$$$ или $$$(8, 3)$$$. Вы можете вывести любую из них.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:05: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:'8124a3325c6f164e',t:'MTY5NjY2NTkxMC4yMDcwMDA='};_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", "*2000"] | ||
1366E | 1366 | E | ru | E. Два массива | <div class="problem-statement"><div class="header"><div class="title">E. Два массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два массива $$$a_1, a_2, \dots , a_n$$$ и $$$b_1, b_2, \dots , b_m$$$. Массив $$$b$$$ отсортирован в порядке возрастания ($$$b_i < b_{i + 1}$$$ верно для любого $$$i$$$ от $$$1$$$ до $$$m - 1$$$).</p><p>Вам нужно разбить массив $$$a$$$ на $$$m$$$ непрерывных подмассивов так, чтобы для всех $$$i$$$ от $$$1$$$ до $$$m$$$ минимум в $$$i$$$-м подмассиве был равен $$$b_i$$$. Обратите внимание, что каждый элемент должен принадлежать ровно одному подмассиву, и они формируются следующим образом: первые несколько элементов массива $$$a$$$ принадлежат первому подмассиву, следующие несколько элементов массива $$$a$$$ принадлежат второму подмассиву, и так далее.</p><p>Например, если $$$a = [12, 10, 20, 20, 25, 30]$$$, а $$$b = [10, 20, 30]$$$, то существует два подходящих разбиения массива $$$a$$$: </p><ol> <li> $$$[12, 10, 20], [20, 25], [30]$$$; </li><li> $$$[12, 10], [20, 20, 25], [30]$$$. </li></ol><p>Вам нужно посчитать количество хороших разбиений массива $$$a$$$. Так как это значение может быть слишком велико — выведите его по модулю <span class="tex-font-style-tt">998244353</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — длины массивов $$$a$$$ и $$$b$$$ соответственно.</p><p>Вторая строка содержит $$$n$$$ чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$) — массив $$$a$$$.</p><p>Третья строка содержит $$$m$$$ чисел $$$b_1, b_2, \dots , b_m$$$ ($$$1 \le b_i \le 10^9; b_i < b_{i+1}$$$) — массив $$$b$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите число — количество хороших разбиений массива $$$a$$$ по модулю <span class="tex-font-style-tt">998244353</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 3
12 10 20 20 25 30
10 20 30
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 2
1 3 3 7
3 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8 2
1 2 2 2 2 2 2 2
1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="81e0f993d1fad8714da38e2a7585b1d8"/>
<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="f96a2e386da9fe6b986fc55c7cdbe1e5d8fabcb3"/>
<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='81e0f993d1fad8714da38e2a7585b1d8'> </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%2F1366%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='81e0f993d1fad8714da38e2a7585b1d8'/>
<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/1366">Educational Codeforces Round 89 (рейтинговый для Див. 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='81e0f993d1fad8714da38e2a7585b1d8'/>
<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/1366/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='81e0f993d1fad8714da38e2a7585b1d8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="646803"/>
<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='81e0f993d1fad8714da38e2a7585b1d8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="646803"/>
<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/78633" title="Educational Codeforces Round 89 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11307:11308" 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/78735" title="Разбор Educational Codeforces Round 89" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11305:11306" 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/1366">Задачи</a></li>
<li><a
href="/contest/1366/submit">Отослать</a></li>
<li><a
href="/contest/1366/my">Мои посылки</a></li>
<li><a
href="/contest/1366/status">Статус</a></li>
<li><a
href="/contest/1366/hacks">Взломы</a></li>
<li><a
href="/contest/1366/standings">Положение</a></li>
<li><a
href="/contest/1366/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_e54ad91914e2bc974db50350c458eeb5d094b804">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">E. Два массива</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам даны два массива $$$a_1, a_2, \dots , a_n$$$ и $$$b_1, b_2, \dots , b_m$$$. Массив $$$b$$$ отсортирован в порядке возрастания ($$$b_i < b_{i + 1}$$$ верно для любого $$$i$$$ от $$$1$$$ до $$$m - 1$$$).</p><p>Вам нужно разбить массив $$$a$$$ на $$$m$$$ непрерывных подмассивов так, чтобы для всех $$$i$$$ от $$$1$$$ до $$$m$$$ минимум в $$$i$$$-м подмассиве был равен $$$b_i$$$. Обратите внимание, что каждый элемент должен принадлежать ровно одному подмассиву, и они формируются следующим образом: первые несколько элементов массива $$$a$$$ принадлежат первому подмассиву, следующие несколько элементов массива $$$a$$$ принадлежат второму подмассиву, и так далее.</p><p>Например, если $$$a = [12, 10, 20, 20, 25, 30]$$$, а $$$b = [10, 20, 30]$$$, то существует два подходящих разбиения массива $$$a$$$: </p><ol> <li> $$$[12, 10, 20], [20, 25], [30]$$$; </li><li> $$$[12, 10], [20, 20, 25], [30]$$$. </li></ol><p>Вам нужно посчитать количество хороших разбиений массива $$$a$$$. Так как это значение может быть слишком велико — выведите его по модулю <span class="tex-font-style-tt">998244353</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два числа $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — длины массивов $$$a$$$ и $$$b$$$ соответственно.</p><p>Вторая строка содержит $$$n$$$ чисел $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$) — массив $$$a$$$.</p><p>Третья строка содержит $$$m$$$ чисел $$$b_1, b_2, \dots , b_m$$$ ($$$1 \le b_i \le 10^9; b_i < b_{i+1}$$$) — массив $$$b$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите число — количество хороших разбиений массива $$$a$$$ по модулю <span class="tex-font-style-tt">998244353</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 3
12 10 20 20 25 30
10 20 30
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 2
1 3 3 7
3 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8 2
1 2 2 2 2 2 2 2
1 2
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
</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:05: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:'8124a33a6fda9d55',t:'MTY5NjY2NTkxMS41NjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\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"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2100"] | ||
1366F | 1366 | F | ru | F. Прогулка по графу | <div class="problem-statement"><div class="header"><div class="title">F. Прогулка по графу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Задан простой взвешенный связный неориентированный граф, состоящий из $$$n$$$ вершин и $$$m$$$ ребер.</p><p>Путем длины $$$k$$$ в графе назовем последовательность из $$$k+1$$$ вершины $$$v_1, v_2, \dots, v_{k+1}$$$ такую, что для каждого $$$i$$$ $$$(1 \le i \le k)$$$ ребро $$$(v_i, v_{i+1})$$$ присутствует в графе. У пути из вершины $$$v$$$ вершина $$$v_1=v$$$. Обратите внимание, что вершины и ребра могут входить в путь по несколько раз.</p><p>Вес пути — это сумма весов ребер в нем.</p><p>Для каждого $$$i$$$ от $$$1$$$ до $$$q$$$ рассмотрим путь из вершины $$$1$$$ длины $$$i$$$ максимального веса. Чему равна сумма весов этих $$$q$$$ путей?</p><p>Ответ может быть довольно большим, поэтому выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$m$$$, $$$q$$$ ($$$2 \le n \le 2000$$$; $$$n - 1 \le m \le 2000$$$; $$$m \le q \le 10^9$$$) — количество вершин в графе, количество ребер в графе и количество длин, которые надо учесть в ответе.</p><p>В каждой из следующих $$$m$$$ строк задано описание ребра: три целых числа $$$v$$$, $$$u$$$, $$$w$$$ ($$$1 \le v, u \le n$$$; $$$1 \le w \le 10^6$$$) — две вершины $$$v$$$ и $$$u$$$ соединены неориентированным ребром веса $$$w$$$. Граф не содержит петель и кратных ребер. Гарантируется, что данные ребра задают связный граф.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — сумма весов путей максимального веса из вершины $$$1$$$ длин $$$1, 2, \dots, q$$$ по модулю $$$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>
7 8 25
1 2 1
2 3 10
3 4 2
1 5 2
5 6 7
6 4 15
5 3 1
1 7 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4361
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 1 5
1 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
60
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
15 15 23
13 10 12
11 14 12
2 15 5
4 10 8
10 2 4
10 7 5
3 10 1
5 6 11
1 13 8
9 15 4
4 2 9
11 15 1
11 12 14
10 8 12
3 6 11
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3250
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 10 10000000
2 4 798
1 5 824
5 2 558
4 1 288
3 4 1890
3 1 134
2 3 1485
4 5 284
3 5 1025
1 2 649
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
768500592
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Граф из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0ce6768b978fc39d22fac54ee93fa405336ccdf7.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Некоторые максимальные пути: </p><ul> <li> длина $$$1$$$: ребра $$$(1, 7)$$$ — вес $$$3$$$; </li><li> длина $$$2$$$: ребра $$$(1, 2), (2, 3)$$$ — вес $$$1+10=11$$$; </li><li> длина $$$3$$$: ребра $$$(1, 5), (5, 6), (6, 4)$$$ — вес $$$2+7+15=24$$$; </li><li> длина $$$4$$$: ребра $$$(1, 5), (5, 6), (6, 4), (6, 4)$$$ — вес $$$2+7+15+15=39$$$; </li><li> $$$\dots$$$ </li></ul><p>Поэтому ответ — это сумма $$$25$$$ слагаемых: $$$3+11+24+39+\dots$$$</p><p>Во втором примере веса у путей максимального веса равны $$$4$$$, $$$8$$$, $$$12$$$, $$$16$$$ and $$$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="2a5956b6dc0bbf48ccfd1845c95928bb"/>
<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="f96a2e386da9fe6b986fc55c7cdbe1e5d8fabcb3"/>
<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='2a5956b6dc0bbf48ccfd1845c95928bb'> </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%2F1366%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='2a5956b6dc0bbf48ccfd1845c95928bb'/>
<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/1366">Educational Codeforces Round 89 (рейтинговый для Див. 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='2a5956b6dc0bbf48ccfd1845c95928bb'/>
<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/1366/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='2a5956b6dc0bbf48ccfd1845c95928bb'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="646804"/>
<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='2a5956b6dc0bbf48ccfd1845c95928bb'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="646804"/>
<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/78633" title="Educational Codeforces Round 89 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11307:11308" 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/78735" title="Разбор Educational Codeforces Round 89" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11305:11306" 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/1366">Задачи</a></li>
<li><a
href="/contest/1366/submit">Отослать</a></li>
<li><a
href="/contest/1366/my">Мои посылки</a></li>
<li><a
href="/contest/1366/status">Статус</a></li>
<li><a
href="/contest/1366/hacks">Взломы</a></li>
<li><a
href="/contest/1366/standings">Положение</a></li>
<li><a
href="/contest/1366/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_c197c407f9e2f951f0f365b5a568c94b0c13e319">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">F. Прогулка по графу</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Задан простой взвешенный связный неориентированный граф, состоящий из $$$n$$$ вершин и $$$m$$$ ребер.</p><p>Путем длины $$$k$$$ в графе назовем последовательность из $$$k+1$$$ вершины $$$v_1, v_2, \dots, v_{k+1}$$$ такую, что для каждого $$$i$$$ $$$(1 \le i \le k)$$$ ребро $$$(v_i, v_{i+1})$$$ присутствует в графе. У пути из вершины $$$v$$$ вершина $$$v_1=v$$$. Обратите внимание, что вершины и ребра могут входить в путь по несколько раз.</p><p>Вес пути — это сумма весов ребер в нем.</p><p>Для каждого $$$i$$$ от $$$1$$$ до $$$q$$$ рассмотрим путь из вершины $$$1$$$ длины $$$i$$$ максимального веса. Чему равна сумма весов этих $$$q$$$ путей?</p><p>Ответ может быть довольно большим, поэтому выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны три целых числа $$$n$$$, $$$m$$$, $$$q$$$ ($$$2 \le n \le 2000$$$; $$$n - 1 \le m \le 2000$$$; $$$m \le q \le 10^9$$$) — количество вершин в графе, количество ребер в графе и количество длин, которые надо учесть в ответе.</p><p>В каждой из следующих $$$m$$$ строк задано описание ребра: три целых числа $$$v$$$, $$$u$$$, $$$w$$$ ($$$1 \le v, u \le n$$$; $$$1 \le w \le 10^6$$$) — две вершины $$$v$$$ и $$$u$$$ соединены неориентированным ребром веса $$$w$$$. Граф не содержит петель и кратных ребер. Гарантируется, что данные ребра задают связный граф.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — сумма весов путей максимального веса из вершины $$$1$$$ длин $$$1, 2, \dots, q$$$ по модулю $$$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>
7 8 25
1 2 1
2 3 10
3 4 2
1 5 2
5 6 7
6 4 15
5 3 1
1 7 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4361
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 1 5
1 2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
60
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
15 15 23
13 10 12
11 14 12
2 15 5
4 10 8
10 2 4
10 7 5
3 10 1
5 6 11
1 13 8
9 15 4
4 2 9
11 15 1
11 12 14
10 8 12
3 6 11
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3250
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 10 10000000
2 4 798
1 5 824
5 2 558
4 1 288
3 4 1890
3 1 134
2 3 1485
4 5 284
3 5 1025
1 2 649
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
768500592
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Граф из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0ce6768b978fc39d22fac54ee93fa405336ccdf7.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Некоторые максимальные пути: </p><ul> <li> длина $$$1$$$: ребра $$$(1, 7)$$$ — вес $$$3$$$; </li><li> длина $$$2$$$: ребра $$$(1, 2), (2, 3)$$$ — вес $$$1+10=11$$$; </li><li> длина $$$3$$$: ребра $$$(1, 5), (5, 6), (6, 4)$$$ — вес $$$2+7+15=24$$$; </li><li> длина $$$4$$$: ребра $$$(1, 5), (5, 6), (6, 4), (6, 4)$$$ — вес $$$2+7+15+15=39$$$; </li><li> $$$\dots$$$ </li></ul><p>Поэтому ответ — это сумма $$$25$$$ слагаемых: $$$3+11+24+39+\dots$$$</p><p>Во втором примере веса у путей максимального веса равны $$$4$$$, $$$8$$$, $$$12$$$, $$$16$$$ and $$$20$$$.</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:05: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:'8124a34309750c48',t:'MTY5NjY2NTkxMi45MTcwMDA='};_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", "\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\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", "\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "*2700"] | ||
1366G | 1366 | G | ru | G. Построй строку | <div class="problem-statement"><div class="header"><div class="title">G. Построй строку</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Определим функцию $$$f(s)$$$, которая принимает строку $$$s$$$, состоящую из строчных латинских букв и точек, и возвращает строку, состоящую из строчных латинских букв следующим образом:</p><ol> <li> пусть $$$r$$$ пустая строка; </li><li> будем обрабатывать символы $$$s$$$ слева направо. Для каждого символа $$$c$$$ выполним следующее: если $$$c$$$ является строчной латинской буквой, то добавим $$$c$$$ в конец строки $$$r$$$; в противном случае удалим последний символ из $$$r$$$ (если $$$r$$$ пустая — функция аварийно завершает работу); </li><li> вернуть $$$r$$$ как результат функции. </li></ol><p>Вам заданы две строки $$$s$$$ и $$$t$$$. Вы должны удалить минимально возможное количество символов из $$$s$$$, чтобы $$$f(s) = t$$$ (и функция не завершалась аварийно). Обратите внимание, что вам не разрешается вставлять новые символы в $$$s$$$ или менять порядок существующих.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из двух строк: первая содержит $$$s$$$ — строку, состоящую из строчных латинских букв и точек, вторая содержит $$$t$$$ — строку, состоящую из строчных латинских букв ($$$1 \le |t| \le |s| \le 10000$$$).</p><p>Дополнительное ограничение на входные данные: можно удалить некоторое количество символов из $$$s$$$ так, чтобы $$$f(s) = t$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимально возможное количество символов, которое необходимо удалить из $$$s$$$, чтобы $$$f(s)$$$ не завершалась аварийно и вернула $$$t$$$ в качестве результата выполнения.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
a.ba.b.
abb
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
.bbac..a.c.cd
bacd
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
c..code..c...o.d.de
code
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="598a5455a7248673b7acceb3e5f30b22"/>
<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="f96a2e386da9fe6b986fc55c7cdbe1e5d8fabcb3"/>
<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='598a5455a7248673b7acceb3e5f30b22'> </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%2F1366%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='598a5455a7248673b7acceb3e5f30b22'/>
<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/1366">Educational Codeforces Round 89 (рейтинговый для Див. 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='598a5455a7248673b7acceb3e5f30b22'/>
<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/1366/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound 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='598a5455a7248673b7acceb3e5f30b22'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="646805"/>
<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='598a5455a7248673b7acceb3e5f30b22'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="646805"/>
<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/78633" title="Educational Codeforces Round 89 [рейтинговый для Div. 2]" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11307:11308" 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/78735" title="Разбор Educational Codeforces Round 89" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11305:11306" 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/1366">Задачи</a></li>
<li><a
href="/contest/1366/submit">Отослать</a></li>
<li><a
href="/contest/1366/my">Мои посылки</a></li>
<li><a
href="/contest/1366/status">Статус</a></li>
<li><a
href="/contest/1366/hacks">Взломы</a></li>
<li><a
href="/contest/1366/standings">Положение</a></li>
<li><a
href="/contest/1366/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_5258864907683c599e0e9e9a8a082eeacb78902d">
<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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Определим функцию $$$f(s)$$$, которая принимает строку $$$s$$$, состоящую из строчных латинских букв и точек, и возвращает строку, состоящую из строчных латинских букв следующим образом:</p><ol> <li> пусть $$$r$$$ пустая строка; </li><li> будем обрабатывать символы $$$s$$$ слева направо. Для каждого символа $$$c$$$ выполним следующее: если $$$c$$$ является строчной латинской буквой, то добавим $$$c$$$ в конец строки $$$r$$$; в противном случае удалим последний символ из $$$r$$$ (если $$$r$$$ пустая — функция аварийно завершает работу); </li><li> вернуть $$$r$$$ как результат функции. </li></ol><p>Вам заданы две строки $$$s$$$ и $$$t$$$. Вы должны удалить минимально возможное количество символов из $$$s$$$, чтобы $$$f(s) = t$$$ (и функция не завершалась аварийно). Обратите внимание, что вам не разрешается вставлять новые символы в $$$s$$$ или менять порядок существующих.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из двух строк: первая содержит $$$s$$$ — строку, состоящую из строчных латинских букв и точек, вторая содержит $$$t$$$ — строку, состоящую из строчных латинских букв ($$$1 \le |t| \le |s| \le 10000$$$).</p><p>Дополнительное ограничение на входные данные: можно удалить некоторое количество символов из $$$s$$$ так, чтобы $$$f(s) = t$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимально возможное количество символов, которое необходимо удалить из $$$s$$$, чтобы $$$f(s)$$$ не завершалась аварийно и вернула $$$t$$$ в качестве результата выполнения.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
a.ba.b.
abb
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
.bbac..a.c.cd
bacd
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
c..code..c...o.d.de
code
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3
</pre></div></div></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=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:05: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:'8124a34b7a0b7b47',t:'MTY5NjY2NTkxNC4yMzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\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\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2700"] | ||
1367A | 1367 | A | ru | A. Короткие подстроки | <div class="problem-statement"><div class="header"><div class="title">A. Короткие подстроки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса отгадывает строки, которые загадал ей Боб.</p><p>Сначала Боб придумал придумал секретную строку $$$a$$$, состоящую из строчных букв латинского алфавита. Строка $$$a$$$ имеет длину $$$2$$$ или более символов. Затем по строке $$$a$$$ он строит новую строку $$$b$$$ и даёт Алисе строку $$$b$$$, чтобы она могла угадать строку $$$a$$$.</p><p>Боб строит $$$b$$$ по $$$a$$$ следующим образом: он выписывает все подстроки длины $$$2$$$ строки $$$a$$$ в порядке слева направо, а потом соединяет их в том же порядке в строку $$$b$$$.</p><p>Например, если Боб загадал строку $$$a$$$=«<span class="tex-font-style-tt">abac</span>», то все подстроки длины $$$2$$$ строки $$$a$$$ таковы: «<span class="tex-font-style-tt">ab</span>», «<span class="tex-font-style-tt">ba</span>», «<span class="tex-font-style-tt">ac</span>». Следовательно, строка $$$b$$$=«<span class="tex-font-style-tt">abbaac</span>».</p><p>Вам задана строка $$$b$$$. Помогите Алисе определить строку $$$a$$$, которую загадал Боб. Гарантируется, что $$$b$$$ была построена по алгоритму, приведенному выше. Можно доказать, что ответ на задачу единственный.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое положительное число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор тестовых данных состоит из одной строки, в которой записана строка $$$b$$$, состоящая из строчных букв латинского алфавита ($$$2 \le |b| \le 100$$$) — строка, которую загадал Боб, где $$$|b|$$$ — длина строки $$$b$$$. Гарантируется, что $$$b$$$ была построена по алгоритму, приведенному выше.</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>
4
abbaac
ac
bccddaaf
zzzzzzzzzz
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
abac
ac
bcdaf
zzzzzz
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных разобран в условии.</p><p>Во втором наборе тестовых данных Боб загадал строку $$$a$$$=«<span class="tex-font-style-tt">ac</span>», строка $$$a$$$ имеет длину $$$2$$$, поэтому строка $$$b$$$ совпадает со строкой $$$a$$$.</p><p>В третьем наборе тестовых данных Боб загадал строку $$$a$$$=«<span class="tex-font-style-tt">bcdaf</span>», подстроки длины $$$2$$$ строки $$$a$$$ таковы: «<span class="tex-font-style-tt">bc</span>», «<span class="tex-font-style-tt">cd</span>», «<span class="tex-font-style-tt">da</span>», «<span class="tex-font-style-tt">af</span>», поэтому строка $$$b$$$=«<span class="tex-font-style-tt">bccddaaf</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="1951f37256217dd6c97f27746390876e"/>
<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="8f7602bf344c182e8f9d0af45516f9735d5540b7"/>
<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='1951f37256217dd6c97f27746390876e'> </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%2F1367%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='1951f37256217dd6c97f27746390876e'/>
<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/1367">Codeforces Round 650 (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='1951f37256217dd6c97f27746390876e'/>
<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/1367/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1951f37256217dd6c97f27746390876e'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="650993"/>
<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='1951f37256217dd6c97f27746390876e'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="650993"/>
<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/78866" title="Codeforces Round #650 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11161:11162" 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/78864" title="Codeforces Round #650 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11159:11160" 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/1367">Задачи</a></li>
<li><a
href="/contest/1367/submit">Отослать</a></li>
<li><a
href="/contest/1367/my">Мои посылки</a></li>
<li><a
href="/contest/1367/status">Статус</a></li>
<li><a
href="/contest/1367/hacks">Взломы</a></li>
<li><a
href="/contest/1367/standings">Положение</a></li>
<li><a
href="/contest/1367/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_4b9c118eb62b7cd1392ce0d9394f6cba0c7f1678">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. Короткие подстроки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса отгадывает строки, которые загадал ей Боб.</p><p>Сначала Боб придумал придумал секретную строку $$$a$$$, состоящую из строчных букв латинского алфавита. Строка $$$a$$$ имеет длину $$$2$$$ или более символов. Затем по строке $$$a$$$ он строит новую строку $$$b$$$ и даёт Алисе строку $$$b$$$, чтобы она могла угадать строку $$$a$$$.</p><p>Боб строит $$$b$$$ по $$$a$$$ следующим образом: он выписывает все подстроки длины $$$2$$$ строки $$$a$$$ в порядке слева направо, а потом соединяет их в том же порядке в строку $$$b$$$.</p><p>Например, если Боб загадал строку $$$a$$$=«<span class="tex-font-style-tt">abac</span>», то все подстроки длины $$$2$$$ строки $$$a$$$ таковы: «<span class="tex-font-style-tt">ab</span>», «<span class="tex-font-style-tt">ba</span>», «<span class="tex-font-style-tt">ac</span>». Следовательно, строка $$$b$$$=«<span class="tex-font-style-tt">abbaac</span>».</p><p>Вам задана строка $$$b$$$. Помогите Алисе определить строку $$$a$$$, которую загадал Боб. Гарантируется, что $$$b$$$ была построена по алгоритму, приведенному выше. Можно доказать, что ответ на задачу единственный.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится одно целое положительное число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор тестовых данных состоит из одной строки, в которой записана строка $$$b$$$, состоящая из строчных букв латинского алфавита ($$$2 \le |b| \le 100$$$) — строка, которую загадал Боб, где $$$|b|$$$ — длина строки $$$b$$$. Гарантируется, что $$$b$$$ была построена по алгоритму, приведенному выше.</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>
4
abbaac
ac
bccddaaf
zzzzzzzzzz
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
abac
ac
bcdaf
zzzzzz
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных разобран в условии.</p><p>Во втором наборе тестовых данных Боб загадал строку $$$a$$$=«<span class="tex-font-style-tt">ac</span>», строка $$$a$$$ имеет длину $$$2$$$, поэтому строка $$$b$$$ совпадает со строкой $$$a$$$.</p><p>В третьем наборе тестовых данных Боб загадал строку $$$a$$$=«<span class="tex-font-style-tt">bcdaf</span>», подстроки длины $$$2$$$ строки $$$a$$$ таковы: «<span class="tex-font-style-tt">bc</span>», «<span class="tex-font-style-tt">cd</span>», «<span class="tex-font-style-tt">da</span>», «<span class="tex-font-style-tt">af</span>», поэтому строка $$$b$$$=«<span class="tex-font-style-tt">bccddaaf</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:05: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:'8124a3541ca316e8',t:'MTY5NjY2NTkxNS44NTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*800"] | ||
1367B | 1367 | 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[0 \ldots n-1]$$$ длины $$$n$$$, который состоит из неотрицательных целых чисел. <span class="tex-font-style-bf">Обратите внимание: массив нумеруется с нуля.</span></p><p>Назовём массив <span class="tex-font-style-it">хорошим</span>, если четность каждой позиции совпадает с четностью элемента в ней. Более формально, массив является хорошим, если для всех $$$i$$$ ($$$0 \le i \le n - 1$$$) выполнено равенство $$$i \bmod 2 = a[i] \bmod 2$$$, где $$$x \bmod 2$$$ — остаток от деления $$$x$$$ на 2.</p><p>Например, массивы [$$$0, 5, 2, 1$$$] и [$$$0, 17, 0, 3$$$] — хорошие, а массив [$$$2, 4, 6, 7$$$] — плохой, потому что для $$$i=1$$$ четность $$$i$$$ и $$$a[i]$$$ различна: $$$i \bmod 2 = 1 \bmod 2 = 1$$$, но $$$a[i] \bmod 2 = 4 \bmod 2 = 0$$$.</p><p>За один ход вы можете взять <span class="tex-font-style-bf">любые</span> два элемента массива и поменять их местами (эти элементы не обязательно соседние).</p><p>Найдите минимальное количество ходов, за которое можно сделать массив $$$a$$$ хорошим, либо укажите, что это сделать невозможно. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано целое число $$$n$$$ ($$$1 \le n \le 40$$$) — размер массива $$$a$$$.</p><p>Далее следует строка, содержащая $$$n$$$ целых чисел $$$a_0, a_1, \ldots, a_{n-1}$$$ ($$$0 \le a_i \le 1000$$$) — исходный массив.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число — минимальное количество ходов, за которое можно сделать заданный массив $$$a$$$ хорошим, или <span class="tex-font-style-tt">-1</span>, если это сделать невозможно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
1
-1
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных в первый ход можно поменять местами элементы на позициях $$$0$$$ и $$$1$$$, а во второй ход поменять местами элементы на позициях $$$2$$$ и $$$3$$$.</p><p>Во втором наборе тестовых данных в первый ход надо поменять местами элементы на позициях $$$0$$$ и $$$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="532f9c09509c938af5cd8189072b4754"/>
<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="8f7602bf344c182e8f9d0af45516f9735d5540b7"/>
<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='532f9c09509c938af5cd8189072b4754'> </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%2F1367%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='532f9c09509c938af5cd8189072b4754'/>
<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/1367">Codeforces Round 650 (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='532f9c09509c938af5cd8189072b4754'/>
<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/1367/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='532f9c09509c938af5cd8189072b4754'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="650994"/>
<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='532f9c09509c938af5cd8189072b4754'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="650994"/>
<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/78866" title="Codeforces Round #650 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11161:11162" 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/78864" title="Codeforces Round #650 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11159:11160" 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/1367">Задачи</a></li>
<li><a
href="/contest/1367/submit">Отослать</a></li>
<li><a
href="/contest/1367/my">Мои посылки</a></li>
<li><a
href="/contest/1367/status">Статус</a></li>
<li><a
href="/contest/1367/hacks">Взломы</a></li>
<li><a
href="/contest/1367/standings">Положение</a></li>
<li><a
href="/contest/1367/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_2a45ec593ae1c1a10946884cddfc3baf749438d4">
<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[0 \ldots n-1]$$$ длины $$$n$$$, который состоит из неотрицательных целых чисел. <span class="tex-font-style-bf">Обратите внимание: массив нумеруется с нуля.</span></p><p>Назовём массив <span class="tex-font-style-it">хорошим</span>, если четность каждой позиции совпадает с четностью элемента в ней. Более формально, массив является хорошим, если для всех $$$i$$$ ($$$0 \le i \le n - 1$$$) выполнено равенство $$$i \bmod 2 = a[i] \bmod 2$$$, где $$$x \bmod 2$$$ — остаток от деления $$$x$$$ на 2.</p><p>Например, массивы [$$$0, 5, 2, 1$$$] и [$$$0, 17, 0, 3$$$] — хорошие, а массив [$$$2, 4, 6, 7$$$] — плохой, потому что для $$$i=1$$$ четность $$$i$$$ и $$$a[i]$$$ различна: $$$i \bmod 2 = 1 \bmod 2 = 1$$$, но $$$a[i] \bmod 2 = 4 \bmod 2 = 0$$$.</p><p>За один ход вы можете взять <span class="tex-font-style-bf">любые</span> два элемента массива и поменять их местами (эти элементы не обязательно соседние).</p><p>Найдите минимальное количество ходов, за которое можно сделать массив $$$a$$$ хорошим, либо укажите, что это сделать невозможно. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано целое число $$$n$$$ ($$$1 \le n \le 40$$$) — размер массива $$$a$$$.</p><p>Далее следует строка, содержащая $$$n$$$ целых чисел $$$a_0, a_1, \ldots, a_{n-1}$$$ ($$$0 \le a_i \le 1000$$$) — исходный массив.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число — минимальное количество ходов, за которое можно сделать заданный массив $$$a$$$ хорошим, или <span class="tex-font-style-tt">-1</span>, если это сделать невозможно.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
4
3 2 7 6
3
3 2 6
1
7
7
4 9 2 1 18 3 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
1
-1
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе тестовых данных в первый ход можно поменять местами элементы на позициях $$$0$$$ и $$$1$$$, а во второй ход поменять местами элементы на позициях $$$2$$$ и $$$3$$$.</p><p>Во втором наборе тестовых данных в первый ход надо поменять местами элементы на позициях $$$0$$$ и $$$1$$$.</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:05: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:'8124a35dfe2c2de4',t:'MTY5NjY2NTkxNy4zMjgwMDA='};_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"] | ||
1367C | 1367 | 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$$$ в порядке слева направо. Состояние ресторана описывается строкой длины $$$n$$$, которая содержит символы '<span class="tex-font-style-tt">1</span>' (столик занят) и '<span class="tex-font-style-tt">0</span>' (столик свободен).</p><p>Правила ресторана запрещают людям садиться на расстоянии $$$k$$$ или меньше друг от друга. То есть, если человек сидит за столиком номер $$$i$$$, то все столики с номерами от $$$i-k$$$ до $$$i+k$$$ (кроме $$$i$$$-го) должны быть свободны. Иными словами, разница (то есть модуль разности) номеров между любыми двумя занятыми столиками должна быть строго больше $$$k$$$.</p><p>Например, если $$$n=8$$$ и $$$k=2$$$, то:</p><ul> <li> строки «<span class="tex-font-style-tt">10010001</span>», «<span class="tex-font-style-tt">10000010</span>», «<span class="tex-font-style-tt">00000000</span>», «<span class="tex-font-style-tt">00100000</span>» соответствуют правилам ресторана; </li><li> строки «<span class="tex-font-style-tt">10100100</span>», «<span class="tex-font-style-tt">10011001</span>», «<span class="tex-font-style-tt">11111111</span>» не соответствуют правилам ресторана, так как в каждой из них есть пара единиц на расстоянии меньшем или равном $$$k=2$$$. </li></ul><p>В частности, если состояние ресторана описывается строкой без единиц или строкой с одной единицей, то требование ресторана выполнено.</p><p>Вам задана бинарная строка $$$s$$$, которая описывает текущее состояние ресторана. Гарантируется, что для строки $$$s$$$ правила ресторана выполнены.</p><p>Найдите максимальное количество свободных столиков, которые можно занять, чтобы не нарушить правила ресторана. Формально, какое максимальное количество нулей можно заменить на единицы так, что требование все еще будет выполняться?</p><p>Например, если $$$n=6$$$, $$$k=1$$$, $$$s=$$$ «<span class="tex-font-style-tt">100010</span>», то ответ на задачу будет $$$1$$$, так как есть только один свободный столик на позиции $$$3$$$, который можно занять в соответствии с правилами ресторана.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — количество столиков в ресторане и минимальное разрешенное расстояние между двумя людьми.</p><p>Во второй строке каждого набора записана строка $$$s$$$ длины $$$n$$$, состоящая из нулей и единиц — описание свободных и занятых столиков в ресторане. Заданная строка соответствует правилам ресторана — разница индексов между любыми двумя единицами строго больше $$$k$$$.</p><p>Сумма $$$n$$$ по всем наборам тестовых данных в одном тесте не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового набора выведите одно целое число — количество столиков, которые можно дополнительно занять, чтобы не нарушить правила ресторана. Если дополнительных столиков занять нельзя, то, очевидно, надо вывести $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
6 1
100010
6 2
000000
5 1
10101
3 1
001
2 2
00
1 1
0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
0
1
1
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных разобран в условии.</p><p>Во втором наборе тестовых данных ответ $$$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="d53b21f4566c59387678632189e60502"/>
<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="8f7602bf344c182e8f9d0af45516f9735d5540b7"/>
<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='d53b21f4566c59387678632189e60502'> </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%2F1367%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='d53b21f4566c59387678632189e60502'/>
<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/1367">Codeforces Round 650 (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='d53b21f4566c59387678632189e60502'/>
<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/1367/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='d53b21f4566c59387678632189e60502'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="650995"/>
<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='d53b21f4566c59387678632189e60502'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="650995"/>
<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/78866" title="Codeforces Round #650 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11161:11162" 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/78864" title="Codeforces Round #650 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11159:11160" 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/1367">Задачи</a></li>
<li><a
href="/contest/1367/submit">Отослать</a></li>
<li><a
href="/contest/1367/my">Мои посылки</a></li>
<li><a
href="/contest/1367/status">Статус</a></li>
<li><a
href="/contest/1367/hacks">Взломы</a></li>
<li><a
href="/contest/1367/standings">Положение</a></li>
<li><a
href="/contest/1367/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_b85265f6b11edf536a92cc28caf28849e746bbf2">
<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$$$ в порядке слева направо. Состояние ресторана описывается строкой длины $$$n$$$, которая содержит символы '<span class="tex-font-style-tt">1</span>' (столик занят) и '<span class="tex-font-style-tt">0</span>' (столик свободен).</p><p>Правила ресторана запрещают людям садиться на расстоянии $$$k$$$ или меньше друг от друга. То есть, если человек сидит за столиком номер $$$i$$$, то все столики с номерами от $$$i-k$$$ до $$$i+k$$$ (кроме $$$i$$$-го) должны быть свободны. Иными словами, разница (то есть модуль разности) номеров между любыми двумя занятыми столиками должна быть строго больше $$$k$$$.</p><p>Например, если $$$n=8$$$ и $$$k=2$$$, то:</p><ul> <li> строки «<span class="tex-font-style-tt">10010001</span>», «<span class="tex-font-style-tt">10000010</span>», «<span class="tex-font-style-tt">00000000</span>», «<span class="tex-font-style-tt">00100000</span>» соответствуют правилам ресторана; </li><li> строки «<span class="tex-font-style-tt">10100100</span>», «<span class="tex-font-style-tt">10011001</span>», «<span class="tex-font-style-tt">11111111</span>» не соответствуют правилам ресторана, так как в каждой из них есть пара единиц на расстоянии меньшем или равном $$$k=2$$$. </li></ul><p>В частности, если состояние ресторана описывается строкой без единиц или строкой с одной единицей, то требование ресторана выполнено.</p><p>Вам задана бинарная строка $$$s$$$, которая описывает текущее состояние ресторана. Гарантируется, что для строки $$$s$$$ правила ресторана выполнены.</p><p>Найдите максимальное количество свободных столиков, которые можно занять, чтобы не нарушить правила ресторана. Формально, какое максимальное количество нулей можно заменить на единицы так, что требование все еще будет выполняться?</p><p>Например, если $$$n=6$$$, $$$k=1$$$, $$$s=$$$ «<span class="tex-font-style-tt">100010</span>», то ответ на задачу будет $$$1$$$, так как есть только один свободный столик на позиции $$$3$$$, который можно занять в соответствии с правилами ресторана.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 2\cdot 10^5$$$) — количество столиков в ресторане и минимальное разрешенное расстояние между двумя людьми.</p><p>Во второй строке каждого набора записана строка $$$s$$$ длины $$$n$$$, состоящая из нулей и единиц — описание свободных и занятых столиков в ресторане. Заданная строка соответствует правилам ресторана — разница индексов между любыми двумя единицами строго больше $$$k$$$.</p><p>Сумма $$$n$$$ по всем наборам тестовых данных в одном тесте не превосходит $$$2\cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого тестового набора выведите одно целое число — количество столиков, которые можно дополнительно занять, чтобы не нарушить правила ресторана. Если дополнительных столиков занять нельзя, то, очевидно, надо вывести $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
6 1
100010
6 2
000000
5 1
10101
3 1
001
2 2
00
1 1
0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
0
1
1
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных разобран в условии.</p><p>Во втором наборе тестовых данных ответ $$$2$$$, так как можно выбрать первый и шестой столики.</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:05: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:'8124a3670d972de6',t:'MTY5NjY2NTkxOC44MDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1300"] | ||
1367D | 1367 | D | ru | D. Задача на доске | <div class="problem-statement"><div class="header"><div class="title">D. Задача на доске</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп написал на доске некоторую строку $$$s$$$ из строчных букв латинского алфавита ('<span class="tex-font-style-tt">a</span>'-'<span class="tex-font-style-tt">z</span>'). Эта строка вам известна и задана во входных данных.</p><p>После этого он стёр какие-то буквы из строки $$$s$$$, а оставшиеся буквы он переписал в <span class="tex-font-style-bf">произвольном</span> порядке. В результате он получил некоторую новую строку $$$t$$$. Её вам и предстоит найти по некоторой дополнительной информации.</p><p>Предположим, что длина строки $$$t$$$ равна $$$m$$$, а символы пронумерованы слева направо от $$$1$$$ до $$$m$$$. В таком случае вам задана последовательность из $$$m$$$ целых чисел: $$$b_1, b_2, \ldots, b_m$$$, где $$$b_i$$$ равно сумме расстояний $$$|i-j|$$$ от индекса $$$i$$$ до всех таких индексов $$$j$$$, что $$$t_j > t_i$$$ (считайте, что '<span class="tex-font-style-tt">a</span>'<'<span class="tex-font-style-tt">b</span>'<...<'<span class="tex-font-style-tt">z</span>'). Иными словами, для вычисления $$$b_i$$$ Поликарп находит все такие индексы $$$j$$$, что в индексе $$$j$$$ находится буква, которая стоит позже в алфавите чем $$$t_i$$$, и суммирует все значения $$$|i-j|$$$.</p><p>Например, если $$$t$$$=«<span class="tex-font-style-tt">abzb</span>», то:</p><ul> <li> так как $$$t_1$$$='<span class="tex-font-style-tt">a</span>', то все остальные индексы содержат буквы, которые позже в алфавите, то есть: $$$b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$$$; </li><li> так как $$$t_2$$$='<span class="tex-font-style-tt">b</span>', то только индекс $$$j=3$$$ содержит букву, которая позже в алфавите, то есть: $$$b_2=|2-3|=1$$$; </li><li> так как $$$t_3$$$='<span class="tex-font-style-tt">z</span>', то индексов $$$j$$$, что $$$t_j>t_i$$$ не существует: $$$b_3=0$$$; </li><li> так как $$$t_4$$$='<span class="tex-font-style-tt">b</span>', то только индекс $$$j=3$$$ содержит букву, которая позже в алфавите, то есть: $$$b_4=|4-3|=1$$$. </li></ul><p>Таким образом, если $$$t$$$=«<span class="tex-font-style-tt">abzb</span>», то $$$b=[6,1,0,1]$$$.</p><p>По заданной строке $$$s$$$ и массиву $$$b$$$ найдите любую возможную строку $$$t$$$, для которой выполняются следующие два требования одновременно:</p><ul> <li> $$$t$$$ получается из $$$s$$$ путём стирания некоторых букв (возможно, нуля) и потом записи оставшихся в <span class="tex-font-style-bf">произвольном</span> порядке; </li><li> по строке $$$t$$$ получается заданный во входных данных массив $$$b$$$, если его построить по правилам, которые описаны выше. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество наборов входных данных в тесте. Далее следуют $$$q$$$ наборов входных данных.</p><p>Каждый набор входных данных состоит из трех строк:</p><ul> <li> строки $$$s$$$, которая имеет длину от $$$1$$$ до $$$50$$$ и состоит из строчных букв латинского алфавита; </li><li> строки, которая содержит целое число $$$m$$$ ($$$1 \le m \le |s|$$$), где $$$|s|$$$ — длина строки $$$s$$$, а $$$m$$$ — длина массива $$$b$$$; </li><li> строки, которая содержит целые числа $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_i \le 1225$$$). </li></ul><p>Гарантируется, что в каждом наборе данных входные данные таковы, что ответ существует.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк: $$$k$$$-я из них должна содержать ответ (строку $$$t$$$) на $$$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
abac
3
2 1 0
abc
1
0
abba
3
1 0 1
ecoosdcefr
10
38 13 24 14 11 5 3 24 17 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
aac
b
aba
codeforces
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных подходят такие строки $$$t$$$: «<span class="tex-font-style-tt">aac</span>», «<span class="tex-font-style-tt">aab</span>».</p><p>Во втором наборе входных данных подходят такие строки $$$t$$$: «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">c</span>».</p><p>В третьем наборе входных данных подходит только строка $$$t$$$ равная «<span class="tex-font-style-tt">aba</span>», но символ '<span class="tex-font-style-tt">b</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="22e9451b6266853e90bae1b04d47cfc3"/>
<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="8f7602bf344c182e8f9d0af45516f9735d5540b7"/>
<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='22e9451b6266853e90bae1b04d47cfc3'> </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%2F1367%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='22e9451b6266853e90bae1b04d47cfc3'/>
<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/1367">Codeforces Round 650 (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='22e9451b6266853e90bae1b04d47cfc3'/>
<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/1367/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Конструктивные алгоритмы">
конструктив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1800
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='22e9451b6266853e90bae1b04d47cfc3'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="650996"/>
<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='22e9451b6266853e90bae1b04d47cfc3'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="650996"/>
<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/78866" title="Codeforces Round #650 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11161:11162" 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/78864" title="Codeforces Round #650 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11159:11160" 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/1367">Задачи</a></li>
<li><a
href="/contest/1367/submit">Отослать</a></li>
<li><a
href="/contest/1367/my">Мои посылки</a></li>
<li><a
href="/contest/1367/status">Статус</a></li>
<li><a
href="/contest/1367/hacks">Взломы</a></li>
<li><a
href="/contest/1367/standings">Положение</a></li>
<li><a
href="/contest/1367/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_0405d6c529c4d6c7b6ea8420c674858adb77aa95">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">D. Задача на доске</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Поликарп написал на доске некоторую строку $$$s$$$ из строчных букв латинского алфавита ('<span class="tex-font-style-tt">a</span>'-'<span class="tex-font-style-tt">z</span>'). Эта строка вам известна и задана во входных данных.</p><p>После этого он стёр какие-то буквы из строки $$$s$$$, а оставшиеся буквы он переписал в <span class="tex-font-style-bf">произвольном</span> порядке. В результате он получил некоторую новую строку $$$t$$$. Её вам и предстоит найти по некоторой дополнительной информации.</p><p>Предположим, что длина строки $$$t$$$ равна $$$m$$$, а символы пронумерованы слева направо от $$$1$$$ до $$$m$$$. В таком случае вам задана последовательность из $$$m$$$ целых чисел: $$$b_1, b_2, \ldots, b_m$$$, где $$$b_i$$$ равно сумме расстояний $$$|i-j|$$$ от индекса $$$i$$$ до всех таких индексов $$$j$$$, что $$$t_j > t_i$$$ (считайте, что '<span class="tex-font-style-tt">a</span>'<'<span class="tex-font-style-tt">b</span>'<...<'<span class="tex-font-style-tt">z</span>'). Иными словами, для вычисления $$$b_i$$$ Поликарп находит все такие индексы $$$j$$$, что в индексе $$$j$$$ находится буква, которая стоит позже в алфавите чем $$$t_i$$$, и суммирует все значения $$$|i-j|$$$.</p><p>Например, если $$$t$$$=«<span class="tex-font-style-tt">abzb</span>», то:</p><ul> <li> так как $$$t_1$$$='<span class="tex-font-style-tt">a</span>', то все остальные индексы содержат буквы, которые позже в алфавите, то есть: $$$b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$$$; </li><li> так как $$$t_2$$$='<span class="tex-font-style-tt">b</span>', то только индекс $$$j=3$$$ содержит букву, которая позже в алфавите, то есть: $$$b_2=|2-3|=1$$$; </li><li> так как $$$t_3$$$='<span class="tex-font-style-tt">z</span>', то индексов $$$j$$$, что $$$t_j>t_i$$$ не существует: $$$b_3=0$$$; </li><li> так как $$$t_4$$$='<span class="tex-font-style-tt">b</span>', то только индекс $$$j=3$$$ содержит букву, которая позже в алфавите, то есть: $$$b_4=|4-3|=1$$$. </li></ul><p>Таким образом, если $$$t$$$=«<span class="tex-font-style-tt">abzb</span>», то $$$b=[6,1,0,1]$$$.</p><p>По заданной строке $$$s$$$ и массиву $$$b$$$ найдите любую возможную строку $$$t$$$, для которой выполняются следующие два требования одновременно:</p><ul> <li> $$$t$$$ получается из $$$s$$$ путём стирания некоторых букв (возможно, нуля) и потом записи оставшихся в <span class="tex-font-style-bf">произвольном</span> порядке; </li><li> по строке $$$t$$$ получается заданный во входных данных массив $$$b$$$, если его построить по правилам, которые описаны выше. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$q$$$ ($$$1 \le q \le 100$$$) — количество наборов входных данных в тесте. Далее следуют $$$q$$$ наборов входных данных.</p><p>Каждый набор входных данных состоит из трех строк:</p><ul> <li> строки $$$s$$$, которая имеет длину от $$$1$$$ до $$$50$$$ и состоит из строчных букв латинского алфавита; </li><li> строки, которая содержит целое число $$$m$$$ ($$$1 \le m \le |s|$$$), где $$$|s|$$$ — длина строки $$$s$$$, а $$$m$$$ — длина массива $$$b$$$; </li><li> строки, которая содержит целые числа $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_i \le 1225$$$). </li></ul><p>Гарантируется, что в каждом наборе данных входные данные таковы, что ответ существует.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк: $$$k$$$-я из них должна содержать ответ (строку $$$t$$$) на $$$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
abac
3
2 1 0
abc
1
0
abba
3
1 0 1
ecoosdcefr
10
38 13 24 14 11 5 3 24 17 0
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
aac
b
aba
codeforces
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных подходят такие строки $$$t$$$: «<span class="tex-font-style-tt">aac</span>», «<span class="tex-font-style-tt">aab</span>».</p><p>Во втором наборе входных данных подходят такие строки $$$t$$$: «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">c</span>».</p><p>В третьем наборе входных данных подходит только строка $$$t$$$ равная «<span class="tex-font-style-tt">aba</span>», но символ '<span class="tex-font-style-tt">b</span>' может быть со второй или с третьей позиции.</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:05: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:'8124a3703eb27b47',t:'MTY5NjY2NTkyMC4yMDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"] | ||
1367E | 1367 | 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$$$ бусинок. Цвет каждой бусинки описывается строчной буквой латинского алфавита («<span class="tex-font-style-tt">a</span>»–«<span class="tex-font-style-tt">z</span>»). Вы хотите купить какие-то бусинки, чтобы собрать из них ожерелье.</p><p>Ожерелье — набор бусинок, соединенных по кругу. </p><p>Например, если в магазине продаются бусинки «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">c</span>», «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">c</span>», «<span class="tex-font-style-tt">c</span>», то вы можете собрать следующие ожерелья (это не все возможные варианты):</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/489ef8e534a70fc3e0e5051863a91dd875fce89a.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>А следующие ожерелья нельзя собрать из бусинок, которые продаются в магазине:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/35fbf7bd3f4923b6d7a03918403df2c496864799.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Первое ожерелье собрать не получится, потому что в нем есть три бусинки «<span class="tex-font-style-tt">a</span>» (из двух доступных). Второе ожерелье собрать не получится, потому что в нем есть бусинка «<span class="tex-font-style-tt">d</span>», которой нет в магазине.</span> </center><p>Назовем ожерелье $$$k$$$-красивым, если при его повороте по часовой стрелке на $$$k$$$ бусинок ожерелье остается неизменным. Например, вот последовательность из трех поворотов некоторого ожерелья. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d00132704b1299bdef457071855b4150205c2447.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Так как после трех поворотов по часовой стрелке ожерелье не изменилось, то оно является $$$3$$$-красивым. Как можно заметить, это ожерелье также является $$$6$$$-красивым, $$$9$$$-красивым и так далее, но не является $$$1$$$-красивым или $$$2$$$-красивым.</p><p>В частности, ожерелье длины $$$1$$$ является $$$k$$$-красивым для любого целого $$$k$$$. Ожерелье, которое состоит из бусинок одинакового цвета, тоже является красивым для любого $$$k$$$.</p><p>Вам даны числа $$$n$$$ и $$$k$$$, а также строка $$$s$$$, содержащая $$$n$$$ строчных букв латинского алфавита — каждая буква задает бусинку в магазине. Вы можете купить любое подмножество бусинок и соединить их в произвольном порядке. Найдите максимальную длину $$$k$$$-красивого ожерелья, которое вы можете собрать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка каждого набора содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 2000$$$).</p><p>Вторая строка каждого набора содержит строку $$$s$$$, содержащую $$$n$$$ строчных букв латинского алфавита — набор бусинок в магазине.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам тестовых данных в тесте не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы тестовых данных. Каждый ответ является целым положительным числом — максимальной длиной $$$k$$$-красивого ожерелья, которое вы можете собрать.</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 3
abcbac
3 6
aaa
7 1000
abczgyo
5 4
ababa
20 10
aaebdbabdbbddaadaadc
20 5
ecbedececacbcbccbdec
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
3
5
4
15
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных разобран в условии.</p><p>Во втором наборе тестовых данных $$$6$$$-красивое ожерелье можно собрать из всех букв.</p><p>В третьем наборе тестовых данных $$$1000$$$-красивое ожерельем можно собрать, например, из бусинок «<span class="tex-font-style-tt">abzyo</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="eee0bb598c1b8747fa01946fe63a02b9"/>
<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="8f7602bf344c182e8f9d0af45516f9735d5540b7"/>
<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='eee0bb598c1b8747fa01946fe63a02b9'> </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%2F1367%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='eee0bb598c1b8747fa01946fe63a02b9'/>
<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/1367">Codeforces Round 650 (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='eee0bb598c1b8747fa01946fe63a02b9'/>
<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/1367/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="Сложность">
*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='eee0bb598c1b8747fa01946fe63a02b9'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="650997"/>
<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='eee0bb598c1b8747fa01946fe63a02b9'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="650997"/>
<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/78866" title="Codeforces Round #650 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11161:11162" 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/78864" title="Codeforces Round #650 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11159:11160" 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/1367">Задачи</a></li>
<li><a
href="/contest/1367/submit">Отослать</a></li>
<li><a
href="/contest/1367/my">Мои посылки</a></li>
<li><a
href="/contest/1367/status">Статус</a></li>
<li><a
href="/contest/1367/hacks">Взломы</a></li>
<li><a
href="/contest/1367/standings">Положение</a></li>
<li><a
href="/contest/1367/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_1732137920abf9044d8bb749201008dd10246c38">
<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$$$ бусинок. Цвет каждой бусинки описывается строчной буквой латинского алфавита («<span class="tex-font-style-tt">a</span>»–«<span class="tex-font-style-tt">z</span>»). Вы хотите купить какие-то бусинки, чтобы собрать из них ожерелье.</p><p>Ожерелье — набор бусинок, соединенных по кругу. </p><p>Например, если в магазине продаются бусинки «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">b</span>», «<span class="tex-font-style-tt">c</span>», «<span class="tex-font-style-tt">a</span>», «<span class="tex-font-style-tt">c</span>», «<span class="tex-font-style-tt">c</span>», то вы можете собрать следующие ожерелья (это не все возможные варианты):</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/489ef8e534a70fc3e0e5051863a91dd875fce89a.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>А следующие ожерелья нельзя собрать из бусинок, которые продаются в магазине:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/35fbf7bd3f4923b6d7a03918403df2c496864799.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Первое ожерелье собрать не получится, потому что в нем есть три бусинки «<span class="tex-font-style-tt">a</span>» (из двух доступных). Второе ожерелье собрать не получится, потому что в нем есть бусинка «<span class="tex-font-style-tt">d</span>», которой нет в магазине.</span> </center><p>Назовем ожерелье $$$k$$$-красивым, если при его повороте по часовой стрелке на $$$k$$$ бусинок ожерелье остается неизменным. Например, вот последовательность из трех поворотов некоторого ожерелья. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/d00132704b1299bdef457071855b4150205c2447.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Так как после трех поворотов по часовой стрелке ожерелье не изменилось, то оно является $$$3$$$-красивым. Как можно заметить, это ожерелье также является $$$6$$$-красивым, $$$9$$$-красивым и так далее, но не является $$$1$$$-красивым или $$$2$$$-красивым.</p><p>В частности, ожерелье длины $$$1$$$ является $$$k$$$-красивым для любого целого $$$k$$$. Ожерелье, которое состоит из бусинок одинакового цвета, тоже является красивым для любого $$$k$$$.</p><p>Вам даны числа $$$n$$$ и $$$k$$$, а также строка $$$s$$$, содержащая $$$n$$$ строчных букв латинского алфавита — каждая буква задает бусинку в магазине. Вы можете купить любое подмножество бусинок и соединить их в произвольном порядке. Найдите максимальную длину $$$k$$$-красивого ожерелья, которое вы можете собрать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Первая строка каждого набора содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 2000$$$).</p><p>Вторая строка каждого набора содержит строку $$$s$$$, содержащую $$$n$$$ строчных букв латинского алфавита — набор бусинок в магазине.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам тестовых данных в тесте не превосходит $$$2000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов на наборы тестовых данных. Каждый ответ является целым положительным числом — максимальной длиной $$$k$$$-красивого ожерелья, которое вы можете собрать.</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 3
abcbac
3 6
aaa
7 1000
abczgyo
5 4
ababa
20 10
aaebdbabdbbddaadaadc
20 5
ecbedececacbcbccbdec
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
3
5
4
15
10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Первый набор тестовых данных разобран в условии.</p><p>Во втором наборе тестовых данных $$$6$$$-красивое ожерелье можно собрать из всех букв.</p><p>В третьем наборе тестовых данных $$$1000$$$-красивое ожерельем можно собрать, например, из бусинок «<span class="tex-font-style-tt">abzyo</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:05: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:'8124a378ff1e9d6a',t:'MTY5NjY2NTkyMS41NTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1900"] | ||
1367F1 | 1367 | 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">Это простая версия задачи. В этой версии все числа в заданном массиве различны и ограничения на $$$n$$$ меньше, чем в сложной версии задачи.</span></p><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел <span class="tex-font-style-bf">(в массиве нет одинаковых элементов)</span>. Вы можете производить над элементами массива следующие операции:</p><ol> <li> выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$) и переместить элемент $$$a[i]$$$ в <span class="tex-font-style-bf">начало</span> массива; </li><li> выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$) и переместить элемент $$$a[i]$$$ в <span class="tex-font-style-bf">конец</span> массива. </li></ol><p>Например, если $$$n = 5$$$, $$$a = [4, 7, 2, 3, 9]$$$, то можно применить следующую последовательность операций: </p><ul> <li> после применения операции первого типа ко второму элементу массив $$$a$$$ станет равным $$$[7, 4, 2, 3, 9]$$$; </li><li> после применения операции второго типа ко второму элементу массив $$$a$$$ станет равным $$$[7, 2, 3, 9, 4]$$$. </li></ul><p>Вы можете проводить операции любого типа произвольное количество раз в любом порядке.</p><p>Найдите минимальное суммарное количество операций первого и второго типа, которые сделают массив $$$a$$$ отсортированным по неубыванию. Иными словами, сколько минимум операций надо применить, чтобы массив удовлетворял неравенствам $$$a[1] \le a[2] \le \ldots \le a[n]$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано целое число $$$n$$$ ($$$1 \le n \le 3000$$$) — размер массива $$$a$$$.</p><p>Далее следуют $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — массив, который требуется отсортировать заданными операциями. <span class="tex-font-style-bf">Все числа в заданном массиве различны</span>.</p><p>Сумма $$$n$$$ по всем наборам тестовых данных в одном тесте не превосходит $$$3000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число — минимальное суммарное количество операций первого и второго типа, которые сделают массив отсортированным по неубыванию.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
2
0
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе нужно переместить сначала тройку, а потом двойку в начало массива. Следовательно, искомая последовательность операций может иметь вид: $$$[4, 7, 2, 3, 9] \rightarrow [3, 4, 7, 2, 9] \rightarrow [2, 3, 4, 7, 9]$$$.</p><p>Во втором тестовом наборе нужно переместить единицу в начало массива, а восьмерку — в конец. Искомая последовательность операций имеет вид: $$$[3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8]$$$.</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="c0cdf0c20508170139041ac52b7602f9"/>
<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="8f7602bf344c182e8f9d0af45516f9735d5540b7"/>
<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='c0cdf0c20508170139041ac52b7602f9'> </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%2F1367%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='c0cdf0c20508170139041ac52b7602f9'/>
<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/1367">Codeforces Round 650 (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='c0cdf0c20508170139041ac52b7602f9'/>
<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/1367/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="Сложность">
*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='c0cdf0c20508170139041ac52b7602f9'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="650998"/>
<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='c0cdf0c20508170139041ac52b7602f9'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="650998"/>
<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/78866" title="Codeforces Round #650 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11161:11162" 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/78864" title="Codeforces Round #650 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11159:11160" 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/1367">Задачи</a></li>
<li><a
href="/contest/1367/submit">Отослать</a></li>
<li><a
href="/contest/1367/my">Мои посылки</a></li>
<li><a
href="/contest/1367/status">Статус</a></li>
<li><a
href="/contest/1367/hacks">Взломы</a></li>
<li><a
href="/contest/1367/standings">Положение</a></li>
<li><a
href="/contest/1367/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_a02aad80a3e552c3df9071bc8aa0f51fd60c5cab">
<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">Это простая версия задачи. В этой версии все числа в заданном массиве различны и ограничения на $$$n$$$ меньше, чем в сложной версии задачи.</span></p><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел <span class="tex-font-style-bf">(в массиве нет одинаковых элементов)</span>. Вы можете производить над элементами массива следующие операции:</p><ol> <li> выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$) и переместить элемент $$$a[i]$$$ в <span class="tex-font-style-bf">начало</span> массива; </li><li> выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$) и переместить элемент $$$a[i]$$$ в <span class="tex-font-style-bf">конец</span> массива. </li></ol><p>Например, если $$$n = 5$$$, $$$a = [4, 7, 2, 3, 9]$$$, то можно применить следующую последовательность операций: </p><ul> <li> после применения операции первого типа ко второму элементу массив $$$a$$$ станет равным $$$[7, 4, 2, 3, 9]$$$; </li><li> после применения операции второго типа ко второму элементу массив $$$a$$$ станет равным $$$[7, 2, 3, 9, 4]$$$. </li></ul><p>Вы можете проводить операции любого типа произвольное количество раз в любом порядке.</p><p>Найдите минимальное суммарное количество операций первого и второго типа, которые сделают массив $$$a$$$ отсортированным по неубыванию. Иными словами, сколько минимум операций надо применить, чтобы массив удовлетворял неравенствам $$$a[1] \le a[2] \le \ldots \le a[n]$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 100$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано целое число $$$n$$$ ($$$1 \le n \le 3000$$$) — размер массива $$$a$$$.</p><p>Далее следуют $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — массив, который требуется отсортировать заданными операциями. <span class="tex-font-style-bf">Все числа в заданном массиве различны</span>.</p><p>Сумма $$$n$$$ по всем наборам тестовых данных в одном тесте не превосходит $$$3000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора тестовых данных выведите одно целое число — минимальное суммарное количество операций первого и второго типа, которые сделают массив отсортированным по неубыванию.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
5
4 7 2 3 9
5
3 5 8 1 7
5
1 4 5 7 12
4
0 2 1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
2
0
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе нужно переместить сначала тройку, а потом двойку в начало массива. Следовательно, искомая последовательность операций может иметь вид: $$$[4, 7, 2, 3, 9] \rightarrow [3, 4, 7, 2, 9] \rightarrow [2, 3, 4, 7, 9]$$$.</p><p>Во втором тестовом наборе нужно переместить единицу в начало массива, а восьмерку — в конец. Искомая последовательность операций имеет вид: $$$[3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8]$$$.</p><p>В третьем тестовом наборе массив уже отсортирован.</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:05: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:'8124a3815add166c',t:'MTY5NjY2NTkyMi44NzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\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", "*2100"] | ||
1367F2 | 1367 | 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">Это сложная версия задачи. В этой версии в заданном массиве могут встречаться одинаковые числа и ограничения на $$$n$$$ больше, чем в простой версии задачи.</span></p><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел <span class="tex-font-style-bf">(в массиве могут быть одинаковые элементы)</span>. Вы можете производить над элементами массива следующие операции:</p><ol> <li> выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$) и переместить элемент $$$a[i]$$$ в <span class="tex-font-style-bf">начало</span> массива; </li><li> выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$) и переместить элемент $$$a[i]$$$ в <span class="tex-font-style-bf">конец</span> массива. </li></ol><p>Например, если $$$n = 5$$$, $$$a = [4, 7, 2, 2, 9]$$$, то можно применить следующую последовательность операций: </p><ul> <li> После применения операции первого типа ко второму элементу массив $$$a$$$ станет равным $$$[7, 4, 2, 2, 9]$$$; </li><li> После применения операции второго типа ко второму элементу массив $$$a$$$ станет равным $$$[7, 2, 2, 9, 4]$$$. </li></ul><p>Вы можете проводить операции любого типа произвольное количество раз в любом порядке.</p><p>Найдите минимальное суммарное количество операций первого и второго типа, которые сделают массив $$$a$$$ отсортированным по неубыванию. Иными словами, сколько минимум операций надо применить, чтобы массив удовлетворял неравенствам $$$a[1] \le a[2] \le \ldots \le a[n]$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — размер массива $$$a$$$.</p><p>Далее следуют $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — массив, который требуется отсортировать заданными операциями. <span class="tex-font-style-bf">(В массиве могут быть одинаковые элементы)</span>.</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>
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
2
0
0
1
1
1
1
16
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе нужно переместить две двойки в начало массива. Следовательно, искомая последовательность операций может иметь вид: $$$[4, 7, 2, 2, 9] \rightarrow [2, 4, 7, 2, 9] \rightarrow [2, 2, 4, 7, 9]$$$.</p><p>Во втором тестовом наборе нужно переместить единицу в начало массива, а восьмерку — в конец. Искомая последовательность операций имеет вид: $$$[3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8]$$$.</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="098bbb2106a1ca84bdb7a69d562bed46"/>
<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="8f7602bf344c182e8f9d0af45516f9735d5540b7"/>
<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='098bbb2106a1ca84bdb7a69d562bed46'> </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%2F1367%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='098bbb2106a1ca84bdb7a69d562bed46'/>
<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/1367">Codeforces Round 650 (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='098bbb2106a1ca84bdb7a69d562bed46'/>
<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/1367/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Два указателя">
два указателя
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование">
дп
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='098bbb2106a1ca84bdb7a69d562bed46'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="650999"/>
<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='098bbb2106a1ca84bdb7a69d562bed46'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="650999"/>
<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/78866" title="Codeforces Round #650 (Div. 3)" target="_blank">Анонс</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11161:11162" 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/78864" title="Codeforces Round #650 (Div. 3) Editorial" target="_blank">Разбор задач</a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11159:11160" 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/1367">Задачи</a></li>
<li><a
href="/contest/1367/submit">Отослать</a></li>
<li><a
href="/contest/1367/my">Мои посылки</a></li>
<li><a
href="/contest/1367/status">Статус</a></li>
<li><a
href="/contest/1367/hacks">Взломы</a></li>
<li><a
href="/contest/1367/standings">Положение</a></li>
<li><a
href="/contest/1367/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_216a28c4d7bf07292011497949c98c1c4ae08bc5">
<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">Это сложная версия задачи. В этой версии в заданном массиве могут встречаться одинаковые числа и ограничения на $$$n$$$ больше, чем в простой версии задачи.</span></p><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел <span class="tex-font-style-bf">(в массиве могут быть одинаковые элементы)</span>. Вы можете производить над элементами массива следующие операции:</p><ol> <li> выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$) и переместить элемент $$$a[i]$$$ в <span class="tex-font-style-bf">начало</span> массива; </li><li> выбрать любой индекс $$$i$$$ ($$$1 \le i \le n$$$) и переместить элемент $$$a[i]$$$ в <span class="tex-font-style-bf">конец</span> массива. </li></ol><p>Например, если $$$n = 5$$$, $$$a = [4, 7, 2, 2, 9]$$$, то можно применить следующую последовательность операций: </p><ul> <li> После применения операции первого типа ко второму элементу массив $$$a$$$ станет равным $$$[7, 4, 2, 2, 9]$$$; </li><li> После применения операции второго типа ко второму элементу массив $$$a$$$ станет равным $$$[7, 2, 2, 9, 4]$$$. </li></ul><p>Вы можете проводить операции любого типа произвольное количество раз в любом порядке.</p><p>Найдите минимальное суммарное количество операций первого и второго типа, которые сделают массив $$$a$$$ отсортированным по неубыванию. Иными словами, сколько минимум операций надо применить, чтобы массив удовлетворял неравенствам $$$a[1] \le a[2] \le \ldots \le a[n]$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов тестовых данных в тесте. Далее следуют $$$t$$$ наборов тестовых данных.</p><p>Каждый набор начинается со строки, в которой записано целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — размер массива $$$a$$$.</p><p>Далее следуют $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — массив, который требуется отсортировать заданными операциями. <span class="tex-font-style-bf">(В массиве могут быть одинаковые элементы)</span>.</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>
9
5
4 7 2 2 9
5
3 5 8 1 7
5
1 2 2 4 5
2
0 1
3
0 1 0
4
0 1 0 0
4
0 1 0 1
4
0 1 0 2
20
16 15 1 10 0 14 0 10 3 9 2 5 4 5 17 9 10 20 0 9
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
2
0
0
1
1
1
1
16
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе нужно переместить две двойки в начало массива. Следовательно, искомая последовательность операций может иметь вид: $$$[4, 7, 2, 2, 9] \rightarrow [2, 4, 7, 2, 9] \rightarrow [2, 2, 4, 7, 9]$$$.</p><p>Во втором тестовом наборе нужно переместить единицу в начало массива, а восьмерку — в конец. Искомая последовательность операций имеет вид: $$$[3, 5, 8, 1, 7] \rightarrow [1, 3, 5, 8, 7] \rightarrow [1, 3, 5, 7, 8]$$$.</p><p>В третьем тестовом наборе массив уже отсортирован.</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:05: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:'8124a38999e91610',t:'MTY5NjY2NTkyNC4yNDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0414\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0434\u043f", "\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"] | ||
1368A | 1368 | A | ru | A. C+= | <div class="problem-statement"><div class="header"><div class="title">A. 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>Лео создал новый язык программирования C+=. В C+= целочисленные переменные можно изменять только операцией «<span class="tex-font-style-tt">+=</span>», которая прибавляет значение справа к переменной слева. Например, если выполнить «<span class="tex-font-style-tt">a += b</span>», когда <span class="tex-font-style-tt">a = </span>$$$2$$$, <span class="tex-font-style-tt">b = </span>$$$3$$$, значение <span class="tex-font-style-tt">a</span> станет равно $$$5$$$ (значение <span class="tex-font-style-tt">b</span> при этом не изменится).</p><p>Лео создал программу-прототип с двумя целочисленными переменными <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>, исходно содержащими некоторые положительные значения. Он может выполнить некоторое количество операций «<span class="tex-font-style-tt">a += b</span>» или «<span class="tex-font-style-tt">b += a</span>». Лео хочет протестировать обработку больших целых чисел, поэтому ему нужно сделать значение <span class="tex-font-style-tt">a</span> либо <span class="tex-font-style-tt">b</span> <span class="tex-font-style-bf">строго больше</span>, чем некоторое данное число $$$n$$$. Какое наименьшее количество операций ему необходимо выполнить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \leq T \leq 100$$$) — количество наборов входных данных.</p><p>Каждая из следующих $$$T$$$ строк описывает один набор входных данных и содержит три целых числа $$$a, b, n$$$ ($$$1 \leq a, b \leq n \leq 10^9$$$) — исходные значения <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>, и значение, которое одна из переменных должна превысить, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите наименьшее необходимое количество операций. Разделяйте ответы переводами строк.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1 2 3
5 4 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных мы не сможем за одну операцию записать значение, большее $$$3$$$, ни в какую переменную. Один из способов сделать это за две операции — выполнить «<span class="tex-font-style-tt">b += a</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="b6e391ef46b3b55b9a03e0e63edb1894"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='b6e391ef46b3b55b9a03e0e63edb1894'> </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%2F1368%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='b6e391ef46b3b55b9a03e0e63edb1894'/>
<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/1368">Codeforces Global Round 8</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='b6e391ef46b3b55b9a03e0e63edb1894'/>
<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/1368/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="Сложность">
*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='b6e391ef46b3b55b9a03e0e63edb1894'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652119"/>
<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='b6e391ef46b3b55b9a03e0e63edb1894'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652119"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_7ac5e19e604d88903c00b938c748d74365870f71">
<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. 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>Лео создал новый язык программирования C+=. В C+= целочисленные переменные можно изменять только операцией «<span class="tex-font-style-tt">+=</span>», которая прибавляет значение справа к переменной слева. Например, если выполнить «<span class="tex-font-style-tt">a += b</span>», когда <span class="tex-font-style-tt">a = </span>$$$2$$$, <span class="tex-font-style-tt">b = </span>$$$3$$$, значение <span class="tex-font-style-tt">a</span> станет равно $$$5$$$ (значение <span class="tex-font-style-tt">b</span> при этом не изменится).</p><p>Лео создал программу-прототип с двумя целочисленными переменными <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>, исходно содержащими некоторые положительные значения. Он может выполнить некоторое количество операций «<span class="tex-font-style-tt">a += b</span>» или «<span class="tex-font-style-tt">b += a</span>». Лео хочет протестировать обработку больших целых чисел, поэтому ему нужно сделать значение <span class="tex-font-style-tt">a</span> либо <span class="tex-font-style-tt">b</span> <span class="tex-font-style-bf">строго больше</span>, чем некоторое данное число $$$n$$$. Какое наименьшее количество операций ему необходимо выполнить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$T$$$ ($$$1 \leq T \leq 100$$$) — количество наборов входных данных.</p><p>Каждая из следующих $$$T$$$ строк описывает один набор входных данных и содержит три целых числа $$$a, b, n$$$ ($$$1 \leq a, b \leq n \leq 10^9$$$) — исходные значения <span class="tex-font-style-tt">a</span> и <span class="tex-font-style-tt">b</span>, и значение, которое одна из переменных должна превысить, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите наименьшее необходимое количество операций. Разделяйте ответы переводами строк.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
1 2 3
5 4 100
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных мы не сможем за одну операцию записать значение, большее $$$3$$$, ни в какую переменную. Один из способов сделать это за две операции — выполнить «<span class="tex-font-style-tt">b += a</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:05: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:'8124a3924db44d8c',t:'MTY5NjY2NTkyNS42NjcwMDA='};_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", "\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", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"] | ||
1368B | 1368 | B | ru | B. Подпоследовательности Codeforces | <div class="problem-statement"><div class="header"><div class="title">B. Подпоследовательности Codeforces</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>Карл любит Codeforces и подпоследовательности. Он хочет составить строку из маленьких английских букв, которая содержит как минимум $$$k$$$ подпоследовательностей <span class="tex-font-style-tt">codeforces</span>. Из всех таких строк Карл хочет выбрать самую короткую.</p><p>Формально, подпоследовательность <span class="tex-font-style-tt">codeforces</span> строки $$$s$$$ — это подмножество из десяти символов $$$s$$$, которые образуют <span class="tex-font-style-tt">codeforces</span>, если читать их в строке слева направо. Например, строка <span class="tex-font-style-tt">codeforces</span> содержит одну подпоследовательность <span class="tex-font-style-tt">codeforces</span>, а <span class="tex-font-style-tt">codeforcesisawesome</span> содержит четыре подпоследовательности <span class="tex-font-style-tt">codeforces</span>: <span class="tex-font-style-tt"><span class="tex-font-style-bf">codeforces</span>isawesome</span>, <span class="tex-font-style-tt"><span class="tex-font-style-bf">codeforce</span>si<span class="tex-font-style-bf">s</span>awesome</span>, <span class="tex-font-style-tt"><span class="tex-font-style-bf">codeforce</span>sisawe<span class="tex-font-style-bf">s</span>ome</span>, <span class="tex-font-style-tt"><span class="tex-font-style-bf">codeforc</span>esisaw<span class="tex-font-style-bf">es</span>ome</span>.</p><p>Помогите Карлу найти любую кратчайшую строку, которая содержит как минимум $$$k$$$ подпоследовательностей <span class="tex-font-style-tt">codeforces</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано одно целое число $$$k$$$ ($$$1 \leq k \leq 10^{16})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите кратчайшую строку из маленьких английских букв, которая содержит не менее $$$k$$$ подпоследовательностей <span class="tex-font-style-tt">codeforces</span>. Если таких строк несколько, выведите любую из них.</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>
codeforces
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
codeforcesss</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="55487c6ea65b349e07104ba3d4b00769"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='55487c6ea65b349e07104ba3d4b00769'> </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%2F1368%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='55487c6ea65b349e07104ba3d4b00769'/>
<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/1368">Codeforces Global Round 8</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='55487c6ea65b349e07104ba3d4b00769'/>
<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/1368/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="Префикс- и Z-функции, суффиксные структуры, алгоритм Кнута-Морриса-Пратта и др.">
строки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*1500
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='55487c6ea65b349e07104ba3d4b00769'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652120"/>
<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='55487c6ea65b349e07104ba3d4b00769'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652120"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_089bd3f8ca40a50d446b33a214af11622f050ef6">
<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. Подпоследовательности Codeforces</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>Карл любит Codeforces и подпоследовательности. Он хочет составить строку из маленьких английских букв, которая содержит как минимум $$$k$$$ подпоследовательностей <span class="tex-font-style-tt">codeforces</span>. Из всех таких строк Карл хочет выбрать самую короткую.</p><p>Формально, подпоследовательность <span class="tex-font-style-tt">codeforces</span> строки $$$s$$$ — это подмножество из десяти символов $$$s$$$, которые образуют <span class="tex-font-style-tt">codeforces</span>, если читать их в строке слева направо. Например, строка <span class="tex-font-style-tt">codeforces</span> содержит одну подпоследовательность <span class="tex-font-style-tt">codeforces</span>, а <span class="tex-font-style-tt">codeforcesisawesome</span> содержит четыре подпоследовательности <span class="tex-font-style-tt">codeforces</span>: <span class="tex-font-style-tt"><span class="tex-font-style-bf">codeforces</span>isawesome</span>, <span class="tex-font-style-tt"><span class="tex-font-style-bf">codeforce</span>si<span class="tex-font-style-bf">s</span>awesome</span>, <span class="tex-font-style-tt"><span class="tex-font-style-bf">codeforce</span>sisawe<span class="tex-font-style-bf">s</span>ome</span>, <span class="tex-font-style-tt"><span class="tex-font-style-bf">codeforc</span>esisaw<span class="tex-font-style-bf">es</span>ome</span>.</p><p>Помогите Карлу найти любую кратчайшую строку, которая содержит как минимум $$$k$$$ подпоследовательностей <span class="tex-font-style-tt">codeforces</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано одно целое число $$$k$$$ ($$$1 \leq k \leq 10^{16})$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите кратчайшую строку из маленьких английских букв, которая содержит не менее $$$k$$$ подпоследовательностей <span class="tex-font-style-tt">codeforces</span>. Если таких строк несколько, выведите любую из них.</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>
codeforces
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
codeforcesss</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:05: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:'8124a39b291900a5',t:'MTY5NjY2NTkyNy4wMzQwMDA='};_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", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1500"] | ||
1368C | 1368 | 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>Лео-младший рисует в тетради в клеточку (каждая страница размечена квадратной сеткой). Можно считать, что страницы бесконечно большие в любом направлении.</p><p>Лео-младший закрашивает некоторые клетки на странице серым цветом. Он считает получившийся рисунок <span class="tex-font-style-it">красивым</span>, если выполнены следующие условия:</p><ul><li> Рисунок <span class="tex-font-style-bf">связен</span>, то есть, из любой серой клетки можно попасть в любую другую по цепочке из серых клеток, в которой каждые две последовательные клетки — соседи (то есть, имеют общую сторону).</li><li> Каждая серая клетка имеет <span class="tex-font-style-bf">чётное количество серых соседей</span>.</li><li> В рисунке <span class="tex-font-style-bf">ровно $$$n$$$ серых клеток, у которых все соседи серые</span>. Количество остальных серых клеток может произвольным <span class="tex-font-style-it">(но разумным, чтобы их можно было перечислить)</span>.</li></ul><p>Лео-младший пытается нарисовать красивый рисунок для выбранного значения $$$n$$$. Помогите ему, найдите любой пример красивого рисунка.</p><p>Чтобы вывести координаты клеток в ответе, предполагайте, что на странице введена декартова система координат, в которой одна из клеток является началом координат $$$(0, 0)$$$, оси $$$0x$$$ и $$$0y$$$ перпендикулярны и сонаправлены линиям сетки, и шаг единичной длины в любом направлении вдоль любой оси ведёт в соседнюю клетку.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 500$$$) — количество серых клеток, у которых все соседи серые.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число $$$k$$$ — количество серых клеток в вашем рисунке. По техническим причинам $$$k$$$ не должно превосходить $$$5 \cdot 10^5$$$.</p><p>Каждая из следующих $$$k$$$ строк должна содержать две целых числа — координаты очередной серой клетки в вашем рисунке. Все перечисленные клетки должны быть различны, и рисунок должен отвечать всем требованиям, перечисленным выше. Все координаты не должны превосходить $$$10^9$$$ по абсолютной величине.</p><p>Можно показать, что существует ответ, который удовлеторяет всем требованиям и укладывается в ограничение на $$$k$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
1 0
2 0
0 1
1 1
2 1
3 1
0 2
1 2
2 2
3 2
1 3
2 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответ для примера изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/32d3333414209636f4bf5f77aeae92fca88b7155.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="dfd550abe562cb8c2c8426b0e8e6fec9"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='dfd550abe562cb8c2c8426b0e8e6fec9'> </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%2F1368%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='dfd550abe562cb8c2c8426b0e8e6fec9'/>
<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/1368">Codeforces Global Round 8</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='dfd550abe562cb8c2c8426b0e8e6fec9'/>
<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/1368/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="Сложность">
*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='dfd550abe562cb8c2c8426b0e8e6fec9'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652121"/>
<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='dfd550abe562cb8c2c8426b0e8e6fec9'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652121"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_e1a0ba8aafdbbcc698874bf1ed7b54cc8ac3144e">
<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>Лео-младший рисует в тетради в клеточку (каждая страница размечена квадратной сеткой). Можно считать, что страницы бесконечно большие в любом направлении.</p><p>Лео-младший закрашивает некоторые клетки на странице серым цветом. Он считает получившийся рисунок <span class="tex-font-style-it">красивым</span>, если выполнены следующие условия:</p><ul><li> Рисунок <span class="tex-font-style-bf">связен</span>, то есть, из любой серой клетки можно попасть в любую другую по цепочке из серых клеток, в которой каждые две последовательные клетки — соседи (то есть, имеют общую сторону).</li><li> Каждая серая клетка имеет <span class="tex-font-style-bf">чётное количество серых соседей</span>.</li><li> В рисунке <span class="tex-font-style-bf">ровно $$$n$$$ серых клеток, у которых все соседи серые</span>. Количество остальных серых клеток может произвольным <span class="tex-font-style-it">(но разумным, чтобы их можно было перечислить)</span>.</li></ul><p>Лео-младший пытается нарисовать красивый рисунок для выбранного значения $$$n$$$. Помогите ему, найдите любой пример красивого рисунка.</p><p>Чтобы вывести координаты клеток в ответе, предполагайте, что на странице введена декартова система координат, в которой одна из клеток является началом координат $$$(0, 0)$$$, оси $$$0x$$$ и $$$0y$$$ перпендикулярны и сонаправлены линиям сетки, и шаг единичной длины в любом направлении вдоль любой оси ведёт в соседнюю клетку.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 500$$$) — количество серых клеток, у которых все соседи серые.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число $$$k$$$ — количество серых клеток в вашем рисунке. По техническим причинам $$$k$$$ не должно превосходить $$$5 \cdot 10^5$$$.</p><p>Каждая из следующих $$$k$$$ строк должна содержать две целых числа — координаты очередной серой клетки в вашем рисунке. Все перечисленные клетки должны быть различны, и рисунок должен отвечать всем требованиям, перечисленным выше. Все координаты не должны превосходить $$$10^9$$$ по абсолютной величине.</p><p>Можно показать, что существует ответ, который удовлеторяет всем требованиям и укладывается в ограничение на $$$k$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
12
1 0
2 0
0 1
1 1
2 1
3 1
0 2
1 2
2 2
3 2
1 3
2 3
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответ для примера изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/32d3333414209636f4bf5f77aeae92fca88b7155.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=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:05: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:'8124a3a3881e16bb',t:'MTY5NjY2NTkyOC40NjcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "*1500"] | ||
1368D | 1368 | D | ru | D. AND, OR и сумма квадратов | <div class="problem-statement"><div class="header"><div class="title">D. AND, OR и сумма квадратов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Готтфрид узнал про двоичное представление чисел. Он придумал эту задачу и предложил её вам.</p><p>Вам дан набор из $$$n$$$ неотрицательных целых чисел $$$a_1, \ldots, a_n$$$. Вы можете выполнять следующую операцию: выбрать два различных индекса $$$1 \leq i, j \leq n$$$. Если перед операцией $$$a_i = x$$$, $$$a_j = y$$$, то после операции $$$a_i = x~\mathsf{AND}~y$$$, $$$a_j = x~\mathsf{OR}~y$$$, где $$$\mathsf{AND}$$$ и $$$\mathsf{OR}$$$ — операции побитового И и ИЛИ соответственно (для формального описания см. раздел Комментарии). Данную операцию можно применять любое количество раз (возможно, ноль).</p><p>После того, как все операции выполнены, вычислим $$$\sum_{i=1}^n a_i^2$$$ — сумму квадратов всех $$$a_i$$$. Какую максимальную сумму квадратов можно получить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$).</p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{20}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — максимально возможная сумма квадратов после применения нескольких операций (возможно, ни одной).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1
123
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
15129
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 3 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
51
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
349525 699050
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1099509530625
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нельзя сделать ни одной операции, поэтому ответ равен $$$123^2$$$.</p><p>Во втором примере мы можем получить набор $$$1, 1, 7$$$, и $$$1^2 + 1^2 + 7^2 = 51$$$.</p><p>Если $$$x$$$ и $$$y$$$ записаны в двоичной системе с одинаковым числом бит (возможно, с ведущими нулями), то любой бит $$$x~\mathsf{AND}~y$$$ равен $$$1$$$ тогда и только тогда, когда оба соответствующих бита $$$x$$$ и $$$y$$$ равны $$$1$$$. Аналогично, любой бит $$$x~\mathsf{OR}~y$$$ равен $$$1$$$ тогда и только тогда, когда хотя бы один из соответствующих битов $$$x$$$ и $$$y$$$ равен $$$1$$$. Например, $$$x = 3$$$ и $$$y = 5$$$ можно представить как $$$011_2$$$ и $$$101_2$$$ (старший бит слева). Тогда $$$x~\mathsf{AND}~y = 001_2 = 1$$$ и $$$x~\mathsf{OR}~y = 111_2 = 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="1b42ae223c0398835ef756f2b5e8de30"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='1b42ae223c0398835ef756f2b5e8de30'> </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%2F1368%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='1b42ae223c0398835ef756f2b5e8de30'/>
<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/1368">Codeforces Global Round 8</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='1b42ae223c0398835ef756f2b5e8de30'/>
<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/1368/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='1b42ae223c0398835ef756f2b5e8de30'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652122"/>
<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='1b42ae223c0398835ef756f2b5e8de30'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652122"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_85e3cd12ee4cc0c7a914633afe378d048164b264">
<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. AND, OR и сумма квадратов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Готтфрид узнал про двоичное представление чисел. Он придумал эту задачу и предложил её вам.</p><p>Вам дан набор из $$$n$$$ неотрицательных целых чисел $$$a_1, \ldots, a_n$$$. Вы можете выполнять следующую операцию: выбрать два различных индекса $$$1 \leq i, j \leq n$$$. Если перед операцией $$$a_i = x$$$, $$$a_j = y$$$, то после операции $$$a_i = x~\mathsf{AND}~y$$$, $$$a_j = x~\mathsf{OR}~y$$$, где $$$\mathsf{AND}$$$ и $$$\mathsf{OR}$$$ — операции побитового И и ИЛИ соответственно (для формального описания см. раздел Комментарии). Данную операцию можно применять любое количество раз (возможно, ноль).</p><p>После того, как все операции выполнены, вычислим $$$\sum_{i=1}^n a_i^2$$$ — сумму квадратов всех $$$a_i$$$. Какую максимальную сумму квадратов можно получить?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$).</p><p>Во второй строке записано $$$n$$$ целых чисел $$$a_1, \ldots, a_n$$$ ($$$0 \leq a_i < 2^{20}$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — максимально возможная сумма квадратов после применения нескольких операций (возможно, ни одной).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1
123
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
15129
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3
1 3 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
51
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
349525 699050
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1099509530625
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нельзя сделать ни одной операции, поэтому ответ равен $$$123^2$$$.</p><p>Во втором примере мы можем получить набор $$$1, 1, 7$$$, и $$$1^2 + 1^2 + 7^2 = 51$$$.</p><p>Если $$$x$$$ и $$$y$$$ записаны в двоичной системе с одинаковым числом бит (возможно, с ведущими нулями), то любой бит $$$x~\mathsf{AND}~y$$$ равен $$$1$$$ тогда и только тогда, когда оба соответствующих бита $$$x$$$ и $$$y$$$ равны $$$1$$$. Аналогично, любой бит $$$x~\mathsf{OR}~y$$$ равен $$$1$$$ тогда и только тогда, когда хотя бы один из соответствующих битов $$$x$$$ и $$$y$$$ равен $$$1$$$. Например, $$$x = 3$$$ и $$$y = 5$$$ можно представить как $$$011_2$$$ и $$$101_2$$$ (старший бит слева). Тогда $$$x~\mathsf{AND}~y = 001_2 = 1$$$ и $$$x~\mathsf{OR}~y = 111_2 = 7$$$.</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:05: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:'8124a3ac9b1f16e8',t:'MTY5NjY2NTkyOS43NzcwMDA='};_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", "\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", "\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", "*1700"] | ||
1368E | 1368 | 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$$$ до $$$n$$$, начиная с вершины и заканчивая подножьем горы. Площадки соединены однонаправленными треками. Все треки направлены от вершины к подножью, поэтому они <span class="tex-font-style-bf">не могут образовывать направленных циклов</span>. <span class="tex-font-style-bf">Из каждой площадки исходит не более, чем две трека</span>, но в одну и ту же площадку может входить любое количество треков.</p><p>Лыжник может спуститься с одной из площадок до другой, если существует путь из треков, которая ведёт из стартовой площади в конечную. К сожалению, в последнее время участились несчастные случаи из-за того, что лыжники, спускающийся по опасному пути, набирают слишком большую скорость и ставят в опасность себя и окружающих. Путь считается опасным, если он состоит из двух или более треков.</p><p>Артур хочет обезопасить своих клиентов и закрыть несколько площадок таким образом, чтобы устранить опасные пути. Если площадка закрыта, все треки, входящие и исходящие из этой площадки, также закрываются.</p><p>Формально, после закрытия площадок в оставшейся части <span class="tex-font-style-bf">не должно существовать пути из двух или более треков</span>.</p><p>Артур не хочет закрывать слишком много площадок. Он будет доволен, если удастся найти способ закрыть <span class="tex-font-style-bf">не более $$$\frac{4}{7}n$$$ площадок</span>, чтобы оставшаяся часть была безопасна. Помогите ему найти любой способ этого добиться.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно положительное целое число $$$T$$$ — количество наборов входных данных. После этого следует $$$T$$$ блоков с описанием наборов входных данных.</p><p>Первая строка каждого блока содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — количество площадок и треков соответственно.</p><p>Следующие $$$m$$$ строк описывают треки. Каждая из этих строк содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \leq x < y \leq n$$$) — номера стартовой и финишной площадки очередного трека. Гарантируется, что из каждой площадки исходит не более двух треков. Могут существовать треки, у которых и начала, и концы совпадают.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число $$$k$$$ ($$$0 \leq k \leq \frac{4}{7}n$$$) — количество площадок, которые нужно закрыть. В следующей строке выведите $$$k$$$ различных целых чисел — номера площадок, которые нужно закрыть, в любом порядке.</p><p>Если существует несколько ответов, разрешается вывести любой из них. Обратите внимание, что <span class="tex-font-style-bf">минимизировать $$$k$$$ не требуется</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
4 6
1 2
1 3
2 3
2 4
3 4
3 4
7 6
1 2
1 3
2 4
2 5
3 6
3 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3 4
4
4 5 6 7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно закрыть любые две площадки.</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="827ee107285d26e4b97638618fe5be3d"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='827ee107285d26e4b97638618fe5be3d'> </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%2F1368%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='827ee107285d26e4b97638618fe5be3d'/>
<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/1368">Codeforces Global Round 8</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='827ee107285d26e4b97638618fe5be3d'/>
<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/1368/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="Сложность">
*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='827ee107285d26e4b97638618fe5be3d'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652123"/>
<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='827ee107285d26e4b97638618fe5be3d'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652123"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_31ae02a0851275d92785b250eff17968c2f6ea63">
<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$$$ до $$$n$$$, начиная с вершины и заканчивая подножьем горы. Площадки соединены однонаправленными треками. Все треки направлены от вершины к подножью, поэтому они <span class="tex-font-style-bf">не могут образовывать направленных циклов</span>. <span class="tex-font-style-bf">Из каждой площадки исходит не более, чем две трека</span>, но в одну и ту же площадку может входить любое количество треков.</p><p>Лыжник может спуститься с одной из площадок до другой, если существует путь из треков, которая ведёт из стартовой площади в конечную. К сожалению, в последнее время участились несчастные случаи из-за того, что лыжники, спускающийся по опасному пути, набирают слишком большую скорость и ставят в опасность себя и окружающих. Путь считается опасным, если он состоит из двух или более треков.</p><p>Артур хочет обезопасить своих клиентов и закрыть несколько площадок таким образом, чтобы устранить опасные пути. Если площадка закрыта, все треки, входящие и исходящие из этой площадки, также закрываются.</p><p>Формально, после закрытия площадок в оставшейся части <span class="tex-font-style-bf">не должно существовать пути из двух или более треков</span>.</p><p>Артур не хочет закрывать слишком много площадок. Он будет доволен, если удастся найти способ закрыть <span class="tex-font-style-bf">не более $$$\frac{4}{7}n$$$ площадок</span>, чтобы оставшаяся часть была безопасна. Помогите ему найти любой способ этого добиться.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно положительное целое число $$$T$$$ — количество наборов входных данных. После этого следует $$$T$$$ блоков с описанием наборов входных данных.</p><p>Первая строка каждого блока содержит два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — количество площадок и треков соответственно.</p><p>Следующие $$$m$$$ строк описывают треки. Каждая из этих строк содержит два целых числа $$$x$$$ и $$$y$$$ ($$$1 \leq x < y \leq n$$$) — номера стартовой и финишной площадки очередного трека. Гарантируется, что из каждой площадки исходит не более двух треков. Могут существовать треки, у которых и начала, и концы совпадают.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите одно целое число $$$k$$$ ($$$0 \leq k \leq \frac{4}{7}n$$$) — количество площадок, которые нужно закрыть. В следующей строке выведите $$$k$$$ различных целых чисел — номера площадок, которые нужно закрыть, в любом порядке.</p><p>Если существует несколько ответов, разрешается вывести любой из них. Обратите внимание, что <span class="tex-font-style-bf">минимизировать $$$k$$$ не требуется</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
4 6
1 2
1 3
2 3
2 4
3 4
3 4
7 6
1 2
1 3
2 4
2 5
3 6
3 7
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2
3 4
4
4 5 6 7
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных можно закрыть любые две площадки.</p><p>Во втором наборе входных данных закрыть только площадку $$$1$$$ также является корректным.</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:05: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:'8124a3b4ff497b5b',t:'MTY5NjY2NTkzMS4xMDgwMDA='};_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\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"] | ["\u0433\u0440\u0430\u0444\u044b", "\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", "*2500"] | ||
1368F | 1368 | 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><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Джон и его воображаемый друг играют в игру. По кругу расположено $$$n$$$ лампочек. Лампочки пронумерованы от $$$1$$$ до $$$n$$$ по часовой стрелке, то есть, лампочки $$$i$$$ и $$$i + 1$$$ являются соседними для любого $$$i = 1, \ldots, n - 1$$$, а также соседними являются лампочки $$$n$$$ и $$$1$$$. Исходно все лампочки выключены.</p><p>Джон и его друг ходят по очереди, начиная с Джона. Джон в качестве своего действия может завершить игру либо сделать ход. Чтобы сделать ход, Джон выбирает положительное число $$$k$$$ и может включить любые $$$k$$$ лампочек на свой выбор. Его друг в ответ может выбрать любые $$$k$$$ <span class="tex-font-style-bf">подряд идущих</span> лампочек и выключить их (выбранные лампочки, которые уже были выключены, остаются выключенными), где $$$k$$$ равно числу, которое выбрал Джон на последнем ходу. Например, если $$$n = 5$$$ и Джон только что включил три лампочки, то его друг может выключить лампочки $$$1, 2, 3$$$, или $$$2, 3, 4$$$, или $$$3, 4, 5$$$, или $$$4, 5, 1$$$, или $$$5, 1, 2$$$.</p><p>После этого Джон снова может завершить игру или сходить, и так далее. Однако, Джон не может сделать более $$$10^4$$$ ходов.</p><p>Джон хочет максимизировать количество включенных лампочек, а его друг хочет минимизировать это количество. Ваша задача — предъявить стратегию за Джона, которая достигает оптимального результата. Ваша программа будет играть за Джона против программы жюри, которая играет за его друга.</p><p>Пусть в игре $$$n$$$ лампочек. Обозначим $$$R(n)$$$ количество включенных лампочек в конце игры, если оба игрока действуют оптимально. Ваша программа должна сделать не более $$$10^4$$$ ходов и завершить игру не менее чем с $$$R(n)$$$ включенными лампочками. Детали реализации приведены в секции «Протокол взаимодействия».</p><p>По техническим причинам <span class="tex-font-style-bf">взломы по этой задаче невозможны.</span></p></div><div><div class="section-title">Протокол взаимодействия</div><p>Исходно ваша программа получит на вход одно целое число $$$n$$$ ($$$1 \leq n \leq 1000$$$) — количество лампочек в игре. После этого программа жюри будет ожидать ваших действий.</p><p>Чтобы сделать ход, выведите в одной строке целое число $$$k$$$ ($$$1 \leq k \leq n$$$), а зачем $$$k$$$ <span class="tex-font-style-bf">различных</span> целых чисед $$$l_1, \ldots, l_k$$$ ($$$1 \leq l_i \leq n$$$) — номера лампочек, которые вы хотите включить. Индексы можно выводить в любом порядке. Можно пытаться включать лампочки, которые уже включены (в таком случае их состояние не изменится).</p><p>Если ваш ход по какой-либо причине некорректен, или вы совершили более $$$10^4$$$ ходов, программа жюри выведет одно число $$$-1$$$. В противном случае, программа жюри выведет одно целое число $$$x$$$ ($$$1 \leq x \leq n)$$$. Это означает, что в ответ были выключены $$$k$$$ лампочек, начиная с лампочки номер $$$x$$$ в порядке по часовой стрелке.</p><p>Чтобы вместо следующего хода завершить игру, выведите в отдельной строке одно число $$$0$$$. Тест будет пройден, если в этот момент включено не менее $$$R(n)$$$ лампочек (значение $$$R(n)$$$ и полученный вердикт не будут сообщены вашей программе). Это действие не включается в количество сделанных ходов (то есть, разрешается завершить игру после ровно $$$10^4$$$ ходов).</p><p>Чтобы получить правильный вердикт, ваша программа должна завершиться сразу, как только выведет $$$0$$$ либо получит ответ $$$-1$$$.</p><p>Не забудьте сбросить буфер вывода после каждого действия.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
1</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1 3
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Если $$$n = 3$$$, любой ход Джона может быть отменен обратно, поэтому $$$R(3) = 0$$$ и завершить игру сразу является верной стратегией.</p><p>$$$R(4) = 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="98701837dd2a53ae91a2b833e0323968"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='98701837dd2a53ae91a2b833e0323968'> </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%2F1368%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='98701837dd2a53ae91a2b833e0323968'/>
<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/1368">Codeforces Global Round 8</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='98701837dd2a53ae91a2b833e0323968'/>
<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/1368/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Игры, функция Шпрага-Гранди">
игры
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интегрирование, диффуры и др.">
математика
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2600
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='98701837dd2a53ae91a2b833e0323968'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652124"/>
<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='98701837dd2a53ae91a2b833e0323968'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652124"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_66b53c67e9aba19c8d9af12b2b270e5c0b4354c9">
<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><span class="tex-font-style-it">Это интерактивная задача.</span></p><p>Джон и его воображаемый друг играют в игру. По кругу расположено $$$n$$$ лампочек. Лампочки пронумерованы от $$$1$$$ до $$$n$$$ по часовой стрелке, то есть, лампочки $$$i$$$ и $$$i + 1$$$ являются соседними для любого $$$i = 1, \ldots, n - 1$$$, а также соседними являются лампочки $$$n$$$ и $$$1$$$. Исходно все лампочки выключены.</p><p>Джон и его друг ходят по очереди, начиная с Джона. Джон в качестве своего действия может завершить игру либо сделать ход. Чтобы сделать ход, Джон выбирает положительное число $$$k$$$ и может включить любые $$$k$$$ лампочек на свой выбор. Его друг в ответ может выбрать любые $$$k$$$ <span class="tex-font-style-bf">подряд идущих</span> лампочек и выключить их (выбранные лампочки, которые уже были выключены, остаются выключенными), где $$$k$$$ равно числу, которое выбрал Джон на последнем ходу. Например, если $$$n = 5$$$ и Джон только что включил три лампочки, то его друг может выключить лампочки $$$1, 2, 3$$$, или $$$2, 3, 4$$$, или $$$3, 4, 5$$$, или $$$4, 5, 1$$$, или $$$5, 1, 2$$$.</p><p>После этого Джон снова может завершить игру или сходить, и так далее. Однако, Джон не может сделать более $$$10^4$$$ ходов.</p><p>Джон хочет максимизировать количество включенных лампочек, а его друг хочет минимизировать это количество. Ваша задача — предъявить стратегию за Джона, которая достигает оптимального результата. Ваша программа будет играть за Джона против программы жюри, которая играет за его друга.</p><p>Пусть в игре $$$n$$$ лампочек. Обозначим $$$R(n)$$$ количество включенных лампочек в конце игры, если оба игрока действуют оптимально. Ваша программа должна сделать не более $$$10^4$$$ ходов и завершить игру не менее чем с $$$R(n)$$$ включенными лампочками. Детали реализации приведены в секции «Протокол взаимодействия».</p><p>По техническим причинам <span class="tex-font-style-bf">взломы по этой задаче невозможны.</span></p></div><div><div class="section-title">Протокол взаимодействия</div><p>Исходно ваша программа получит на вход одно целое число $$$n$$$ ($$$1 \leq n \leq 1000$$$) — количество лампочек в игре. После этого программа жюри будет ожидать ваших действий.</p><p>Чтобы сделать ход, выведите в одной строке целое число $$$k$$$ ($$$1 \leq k \leq n$$$), а зачем $$$k$$$ <span class="tex-font-style-bf">различных</span> целых чисед $$$l_1, \ldots, l_k$$$ ($$$1 \leq l_i \leq n$$$) — номера лампочек, которые вы хотите включить. Индексы можно выводить в любом порядке. Можно пытаться включать лампочки, которые уже включены (в таком случае их состояние не изменится).</p><p>Если ваш ход по какой-либо причине некорректен, или вы совершили более $$$10^4$$$ ходов, программа жюри выведет одно число $$$-1$$$. В противном случае, программа жюри выведет одно целое число $$$x$$$ ($$$1 \leq x \leq n)$$$. Это означает, что в ответ были выключены $$$k$$$ лампочек, начиная с лампочки номер $$$x$$$ в порядке по часовой стрелке.</p><p>Чтобы вместо следующего хода завершить игру, выведите в отдельной строке одно число $$$0$$$. Тест будет пройден, если в этот момент включено не менее $$$R(n)$$$ лампочек (значение $$$R(n)$$$ и полученный вердикт не будут сообщены вашей программе). Это действие не включается в количество сделанных ходов (то есть, разрешается завершить игру после ровно $$$10^4$$$ ходов).</p><p>Чтобы получить правильный вердикт, ваша программа должна завершиться сразу, как только выведет $$$0$$$ либо получит ответ $$$-1$$$.</p><p>Не забудьте сбросить буфер вывода после каждого действия.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
1</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2 1 3
0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Если $$$n = 3$$$, любой ход Джона может быть отменен обратно, поэтому $$$R(3) = 0$$$ и завершить игру сразу является верной стратегией.</p><p>$$$R(4) = 1$$$, и одна из стратегий, которая достигает этого результата, приведена во втором примере.</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:05: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:'8124a3bd1bed9d8c',t:'MTY5NjY2NTkzMi40OTQwMDA='};_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", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\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"] | ["\u0438\u0433\u0440\u044b", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*2600"] | ||
1368G | 1368 | G | ru | G. Двигаем доминошки | <div class="problem-statement"><div class="header"><div class="title">G. Двигаем доминошки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Билл любит играть с доминошками. Он взял доску размера $$$n \times m$$$, разделённую на одинаковые квадратные клетки, и покрыл её доминошками. Каждая доминошка покрывает две клетки, соседние по горизонтали или вертикали, и каждая клетка покрыта ровно одной половиной доминошки (то есть, непокрытых клеток нет, и никакие две доминошки не покрывают одну клетку дважды).</p><p>После этого Билл решил поиграть с покрытой доской и выложить фотографии в социальных сетях. Сперва он убирает с доски одну из доминошек, тем самым освобождая две клетки. После этого он двигает некоторые доминошки. Доминошку можно двигать только <span class="tex-font-style-bf">параллельно её длинной стороне</span>. Двигать доминошку в каком-либо направлении можно лишь, если ближайшая клетка в этом направлении сейчас свободна. Билл не хочет забыть исходное расположение доминошек, поэтому он двигает доминошки только так, чтобы каждая доминошка всегда <span class="tex-font-style-bf">покрывала хотя бы одну клетку, общую с её исходным положением</span>.</p><p>После удаления доминошки и нескольких сдвигов (возможно, ни одного), Билл фотографирует получившуюся доску. Однако, Билл использует очень много фильтров, поэтому границы доминошек разглядеть нельзя, и можно увидеть лишь то, <span class="tex-font-style-bf">какие две клетки на доске свободны</span>. Когда Билл выкладывает фотографию, он возвращает доску в исходное положение и начинает заново.</p><p>Билл хочет выложить как можно больше фотографий, но он не будет выкладывать одну и ту же фотографию дважды. Сколько различных фотографий он сможет сделать? Напомним, что фотографии различны, если различны пары свободных клеток на них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два положительных целых числа $$$n$$$ и $$$m$$$ ($$$nm \leq 2 \cdot 10^5$$$) — высота и ширина доски соответственно.</p><p>Следующие $$$n$$$ строк описывают покрытие доски доминошками, ряд за рядом сверху вниз. Каждая из этих строк содержит $$$m$$$ символов, описывающие клетки в соответствующем ряду слева направо. Каждая символ равен <span class="tex-font-style-tt">U</span>, <span class="tex-font-style-tt">D</span>, <span class="tex-font-style-tt">L</span> или <span class="tex-font-style-tt">R</span>, если клетка покрыта верхней, нижней, левой или правой половиной доминошки соответственно.</p><p>Гарантируется, что данное покрытие корректно, то есть, у каждой половины доминошки есть вторая половина в нужной позиции. В частности, поскольку покрытие возможно, количество клеток на доске чётно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — количество различных фотографий, которые сможет сделать Билл.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2 4
UUUU
DDDD
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 3
ULR
DLR
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 6
ULRUUU
DUUDDD
UDDLRU
DLRLRD
ULRULR
DLRDLR
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
133
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере после удаления любой доминошки нельзя сделать ни одного сдвига, поэтому различных фотографий четыре.</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="0dcce778fcb5bf20b38c3e947a621746"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='0dcce778fcb5bf20b38c3e947a621746'> </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%2F1368%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='0dcce778fcb5bf20b38c3e947a621746'/>
<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/1368">Codeforces Global Round 8</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='0dcce778fcb5bf20b38c3e947a621746'/>
<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/1368/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="Сложность">
*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='0dcce778fcb5bf20b38c3e947a621746'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652125"/>
<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='0dcce778fcb5bf20b38c3e947a621746'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652125"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_a004261bd70d550096df4d1be8012f6a7f8164f4">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">G. Двигаем доминошки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Билл любит играть с доминошками. Он взял доску размера $$$n \times m$$$, разделённую на одинаковые квадратные клетки, и покрыл её доминошками. Каждая доминошка покрывает две клетки, соседние по горизонтали или вертикали, и каждая клетка покрыта ровно одной половиной доминошки (то есть, непокрытых клеток нет, и никакие две доминошки не покрывают одну клетку дважды).</p><p>После этого Билл решил поиграть с покрытой доской и выложить фотографии в социальных сетях. Сперва он убирает с доски одну из доминошек, тем самым освобождая две клетки. После этого он двигает некоторые доминошки. Доминошку можно двигать только <span class="tex-font-style-bf">параллельно её длинной стороне</span>. Двигать доминошку в каком-либо направлении можно лишь, если ближайшая клетка в этом направлении сейчас свободна. Билл не хочет забыть исходное расположение доминошек, поэтому он двигает доминошки только так, чтобы каждая доминошка всегда <span class="tex-font-style-bf">покрывала хотя бы одну клетку, общую с её исходным положением</span>.</p><p>После удаления доминошки и нескольких сдвигов (возможно, ни одного), Билл фотографирует получившуюся доску. Однако, Билл использует очень много фильтров, поэтому границы доминошек разглядеть нельзя, и можно увидеть лишь то, <span class="tex-font-style-bf">какие две клетки на доске свободны</span>. Когда Билл выкладывает фотографию, он возвращает доску в исходное положение и начинает заново.</p><p>Билл хочет выложить как можно больше фотографий, но он не будет выкладывать одну и ту же фотографию дважды. Сколько различных фотографий он сможет сделать? Напомним, что фотографии различны, если различны пары свободных клеток на них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два положительных целых числа $$$n$$$ и $$$m$$$ ($$$nm \leq 2 \cdot 10^5$$$) — высота и ширина доски соответственно.</p><p>Следующие $$$n$$$ строк описывают покрытие доски доминошками, ряд за рядом сверху вниз. Каждая из этих строк содержит $$$m$$$ символов, описывающие клетки в соответствующем ряду слева направо. Каждая символ равен <span class="tex-font-style-tt">U</span>, <span class="tex-font-style-tt">D</span>, <span class="tex-font-style-tt">L</span> или <span class="tex-font-style-tt">R</span>, если клетка покрыта верхней, нижней, левой или правой половиной доминошки соответственно.</p><p>Гарантируется, что данное покрытие корректно, то есть, у каждой половины доминошки есть вторая половина в нужной позиции. В частности, поскольку покрытие возможно, количество клеток на доске чётно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — количество различных фотографий, которые сможет сделать Билл.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2 4
UUUU
DDDD
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2 3
ULR
DLR
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
6
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 6
ULRUUU
DUUDDD
UDDLRU
DLRLRD
ULRULR
DLRDLR
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
133
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере после удаления любой доминошки нельзя сделать ни одного сдвига, поэтому различных фотографий четыре.</p><p>Во втором примере после удаления самой левой доминошки можно сделать четыре фотографии, поскольку можно независимо двигать/не двигать оставшиеся две доминошки. Две другие фотографии можно сделать, если удалить одну из доминошек справа.</p></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:05: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:'8124a3c5bcb89d51',t:'MTY5NjY2NTkzMy44NTIwMDA='};_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", "\u0413\u0440\u0430\u0444\u044b", "\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"] | ["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3200"] | ||
1368H1 | 1368 | H1 | ru | H1. Пропускная способность платы (простая версия) | <div class="problem-statement"><div class="header"><div class="title">H1. Пропускная способность платы (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более простая версия задачи H без запросов на изменение.</span></p><p>Лестер и Делберт работают в компании-производителе электроники. Сейчас они трудятся над микроплатой, которая должен соединять две независимые части большого суперкомпьютера.</p><p>Плата строится на основе макета в виде сетки. В макете $$$n$$$ рядов и $$$m$$$ столбцов, и на каждом пересечении ряда и столбца находится контакт. Также, на каждой из сторон макета расположены порты, которые можно подсоединять к ближайшему контакту. На левой и правой стороне находится по $$$n$$$ портов, а на верхней и нижней — по $$$m$$$ портов. Каждый из портов снаружи соединён с одной из частей суперкомпьютера, и раскрашен в красный либо синий цвет.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e6a12a78bc56706cf5c95fdc316ea249219fb133.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Порты можно соединять проводами внутри платы. Однако, есть несколько требований:</p><ul><li> Каждый провод должен соединять красный и синий порт, и каждый порт может быть соединён не более чем одним проводом.</li><li> Каждый участок провода должен быть горизонтальным либо вертикальным, и повороты возможно только в одном из контактов.</li><li> Чтобы избежать интерференции, провода не должны иметь общих частей ненулевой длины (однако, они могут проходить через общие контакты). Кроме того, провод не может покрывать один участок ненулевой длины дважды.</li></ul><p><span class="tex-font-style-it">Пропускной способностью</span> платы называется наибольшее количество соединений между красными и синими портами, которого можно достичь, соблюдая условия выше. Например, плата, изображенная выше, имеет пропускную способность $$$7$$$, и один из способов построить семь соединений изображён ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/529a6ec6323f826da5a530372962049e6cb652a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-it">До этого места условия обеих версий задачи совпадают. Различия начинаются ниже.</span></p><p>Помогите Лестеру и Делберту найти пропускную способность платы с данной конфигурацией.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано три целых числа $$$n, m, q$$$ ($$$1 \leq n, m \leq 10^5$$$, $$$\pmb{q = 0}$$$). $$$n$$$ и $$$m$$$ задают количество рядов и столбцов в макете соответственно. <span class="tex-font-style-it">В этой версии $$$q$$$ всегда равно нулю и присутствует только для совместимости со сложной версией.</span></p><p>Следующие четыре строки описывают исходные цвета портов. Каждый символ в этих строках равен <span class="tex-font-style-tt">R</span> или <span class="tex-font-style-tt">B</span> в зависимости от цвета соответствующего порта. Первые две из этих строк содержат по $$$n$$$ символов и описывают сверху вниз порты на левой и правой стороне соответственно. Следующие две строки содержат по $$$m$$$ символов и описывают слева направо порты на верхней и нижней стороне соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — пропускную споособность заданной платы.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 5 0
BBRR
RBBR
BBBBB
RRRRR
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
</pre></div></div></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="1910d6fdb69f0c446005e8294efdd7c8"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='1910d6fdb69f0c446005e8294efdd7c8'> </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%2F1368%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='1910d6fdb69f0c446005e8294efdd7c8'/>
<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/1368">Codeforces Global Round 8</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='1910d6fdb69f0c446005e8294efdd7c8'/>
<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/1368/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='1910d6fdb69f0c446005e8294efdd7c8'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652126"/>
<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='1910d6fdb69f0c446005e8294efdd7c8'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652126"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_073cb177345846c71346b70e373e308818b238c5">
<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>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более простая версия задачи H без запросов на изменение.</span></p><p>Лестер и Делберт работают в компании-производителе электроники. Сейчас они трудятся над микроплатой, которая должен соединять две независимые части большого суперкомпьютера.</p><p>Плата строится на основе макета в виде сетки. В макете $$$n$$$ рядов и $$$m$$$ столбцов, и на каждом пересечении ряда и столбца находится контакт. Также, на каждой из сторон макета расположены порты, которые можно подсоединять к ближайшему контакту. На левой и правой стороне находится по $$$n$$$ портов, а на верхней и нижней — по $$$m$$$ портов. Каждый из портов снаружи соединён с одной из частей суперкомпьютера, и раскрашен в красный либо синий цвет.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e6a12a78bc56706cf5c95fdc316ea249219fb133.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Порты можно соединять проводами внутри платы. Однако, есть несколько требований:</p><ul><li> Каждый провод должен соединять красный и синий порт, и каждый порт может быть соединён не более чем одним проводом.</li><li> Каждый участок провода должен быть горизонтальным либо вертикальным, и повороты возможно только в одном из контактов.</li><li> Чтобы избежать интерференции, провода не должны иметь общих частей ненулевой длины (однако, они могут проходить через общие контакты). Кроме того, провод не может покрывать один участок ненулевой длины дважды.</li></ul><p><span class="tex-font-style-it">Пропускной способностью</span> платы называется наибольшее количество соединений между красными и синими портами, которого можно достичь, соблюдая условия выше. Например, плата, изображенная выше, имеет пропускную способность $$$7$$$, и один из способов построить семь соединений изображён ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/529a6ec6323f826da5a530372962049e6cb652a8.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-it">До этого места условия обеих версий задачи совпадают. Различия начинаются ниже.</span></p><p>Помогите Лестеру и Делберту найти пропускную способность платы с данной конфигурацией.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано три целых числа $$$n, m, q$$$ ($$$1 \leq n, m \leq 10^5$$$, $$$\pmb{q = 0}$$$). $$$n$$$ и $$$m$$$ задают количество рядов и столбцов в макете соответственно. <span class="tex-font-style-it">В этой версии $$$q$$$ всегда равно нулю и присутствует только для совместимости со сложной версией.</span></p><p>Следующие четыре строки описывают исходные цвета портов. Каждый символ в этих строках равен <span class="tex-font-style-tt">R</span> или <span class="tex-font-style-tt">B</span> в зависимости от цвета соответствующего порта. Первые две из этих строк содержат по $$$n$$$ символов и описывают сверху вниз порты на левой и правой стороне соответственно. Следующие две строки содержат по $$$m$$$ символов и описывают слева направо порты на верхней и нижней стороне соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно число — пропускную споособность заданной платы.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 5 0
BBRR
RBBR
BBBBB
RRRRR
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
</pre></div></div></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:05: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:'8124a3ce49bb9d37',t:'MTY5NjY2NTkzNS4xOTgwMDA='};_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\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0442\u043e\u043a\u0438", "*3300"] | ||
1368H2 | 1368 | H2 | ru | H2. Пропускная способность платы (сложная версия) | <div class="problem-statement"><div class="header"><div class="title">H2. Пропускная способность платы (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более сложная версия задачи H с запросами на изменение.</span></p><p>Лестер и Делберт работают в компании-производителе электроники. Сейчас они трудятся над микроплатой, которая должен соединять две независимые части большого суперкомпьютера.</p><p>Плата строится на основе макета в виде сетки. В макете $$$n$$$ рядов и $$$m$$$ столбцов, и на каждом пересечении ряда и столбца находится контакт. Также, на каждой из сторон макета расположены порты, которые можно подсоединять к ближайшему контакту. На левой и правой стороне находится по $$$n$$$ портов, а на верхней и нижней — по $$$m$$$ портов. Каждый из портов снаружи соединён с одной из частей суперкомпьютера, и раскрашен в красный либо синий цвет.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e6a12a78bc56706cf5c95fdc316ea249219fb133.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Порты можно соединять проводами внутри платы. Однако, есть несколько требований:</p><ul><li> Каждый провод должен соединять красный и синий порт, и каждый порт может быть соединён не более чем одним проводом.</li><li> Каждый участок провода должен быть горизонтальным либо вертикальным, и повороты возможно только в одном из контактов.</li><li> Чтобы избежать интерференции, провода не должны иметь общих частей ненулевой длины (однако, они могут проходить через общие контакты). Кроме того, провод не может покрывать один участок ненулевой длины дважды.</li></ul><p><span class="tex-font-style-it">Пропускной способностью</span> платы называется наибольшее количество соединений между красными и синими портами, которого можно достичь, соблюдая условия выше. Например, плата, изображенная выше, имеет пропускную способность $$$7$$$, и один из способов построить семь соединений изображён ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/529a6ec6323f826da5a530372962049e6cb652a8.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-it">До этого места условия обеих версий задачи совпадают. Различия начинаются ниже.</span></p><p>Как это часто бывает, спецификации проекта в ходе разработки часто меняются, поэтому цвета всех портов ещё не установлены окончательно. Приходит $$$q$$$ модификаций, каждая из которых выглядит так: «цвета всех портов на непрерывном отрезке вдоль одной из сторон меняются на противоположные (красные на синий, синие на красный)». Предыдущие модификации не отменяются перед тем, как происходит следующая.</p><p>Чтобы оценить критичность изменений, Лестер и Делберт должны узнать пропускную способность платы после каждой модификации. Помогите им сделать это эффективно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано три целых числа $$$n, m, q$$$ ($$$1 \leq n, m \leq 10^5$$$, $$$0 \leq q \leq 10^5$$$) — количество рядов и столбцов в макете, и количество изменений соответственно.</p><p>Следующие четыре строки описывают исходные цвета портов. Каждый символ в этих строках равен <span class="tex-font-style-tt">R</span> или <span class="tex-font-style-tt">B</span> в зависимости от цвета соответствующего порта. Первые две из этих строк содержат по $$$n$$$ символов и описывают сверху вниз порты на левой и правой стороне соответственно. Следующие две строки содержат по $$$m$$$ символов и описывают слева направо порты на верхней и нижней стороне соответственно.</p><p>Следующие $$$q$$$ строк описывают модификации. Каждая из этих строк содержит символ $$$s$$$, а затем два целых числа $$$l$$$ и $$$r$$$. Если $$$s$$$ равен <span class="tex-font-style-tt">L</span> или <span class="tex-font-style-tt">R</span>, то модификация затрагивает левую/правую сторону соответственно, тогда $$$l$$$ и $$$r$$$ удовлетворяют $$$1 \leq l \leq r \leq n$$$, и порты в рядах с $$$l$$$ по $$$r$$$ (включительно) на соответствующей стороне меняют цвет. Аналогично, если $$$s$$$ равен <span class="tex-font-style-tt">U</span> или <span class="tex-font-style-tt">D</span>, то $$$1 \leq l \leq r \leq m$$$, и порты в столбцах с $$$l$$$ по $$$r$$$ (включительно) на верхней/нижней стороне соответственно меняют цвет.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ число по одному на строке — пропускную споособность платы после применения $$$0, \ldots, q$$$ модификаций к исходной раскраске портов.</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 4
BBRR
RBBR
BBBBB
RRRRR
L 2 3
R 3 4
U 1 5
D 1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
7
9
4
9
</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="bd6f72d764a2592c5c34bcc577240000"/>
<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="4b08c0afbb0739e500596740f6167e383e60073a"/>
<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='bd6f72d764a2592c5c34bcc577240000'> </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%2F1368%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='bd6f72d764a2592c5c34bcc577240000'/>
<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/1368">Codeforces Global Round 8</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='bd6f72d764a2592c5c34bcc577240000'/>
<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/1368/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="Сложность">
*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='bd6f72d764a2592c5c34bcc577240000'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652127"/>
<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='bd6f72d764a2592c5c34bcc577240000'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652127"/>
<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/78987" title="Codeforces Global Round 8" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11452" resourceName="Codeforces Global Round 8"
resourceManual="true" src="//codeforces.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/79027" title="Codeforces Global Round 8: editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11451" resourceName="Codeforces Global Round 8: 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/1368">Задачи</a></li>
<li><a
href="/contest/1368/submit">Отослать</a></li>
<li><a
href="/contest/1368/my">Мои посылки</a></li>
<li><a
href="/contest/1368/status">Статус</a></li>
<li><a
href="/contest/1368/hacks">Взломы</a></li>
<li><a
href="/contest/1368/room/1">Комната</a></li>
<li><a
href="/contest/1368/standings">Положение</a></li>
<li><a
href="/contest/1368/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_f1e33aba82b899e9dfba20e726a8ae9cffa28f87">
<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>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более сложная версия задачи H с запросами на изменение.</span></p><p>Лестер и Делберт работают в компании-производителе электроники. Сейчас они трудятся над микроплатой, которая должен соединять две независимые части большого суперкомпьютера.</p><p>Плата строится на основе макета в виде сетки. В макете $$$n$$$ рядов и $$$m$$$ столбцов, и на каждом пересечении ряда и столбца находится контакт. Также, на каждой из сторон макета расположены порты, которые можно подсоединять к ближайшему контакту. На левой и правой стороне находится по $$$n$$$ портов, а на верхней и нижней — по $$$m$$$ портов. Каждый из портов снаружи соединён с одной из частей суперкомпьютера, и раскрашен в красный либо синий цвет.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e6a12a78bc56706cf5c95fdc316ea249219fb133.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Порты можно соединять проводами внутри платы. Однако, есть несколько требований:</p><ul><li> Каждый провод должен соединять красный и синий порт, и каждый порт может быть соединён не более чем одним проводом.</li><li> Каждый участок провода должен быть горизонтальным либо вертикальным, и повороты возможно только в одном из контактов.</li><li> Чтобы избежать интерференции, провода не должны иметь общих частей ненулевой длины (однако, они могут проходить через общие контакты). Кроме того, провод не может покрывать один участок ненулевой длины дважды.</li></ul><p><span class="tex-font-style-it">Пропускной способностью</span> платы называется наибольшее количество соединений между красными и синими портами, которого можно достичь, соблюдая условия выше. Например, плата, изображенная выше, имеет пропускную способность $$$7$$$, и один из способов построить семь соединений изображён ниже.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/529a6ec6323f826da5a530372962049e6cb652a8.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-it">До этого места условия обеих версий задачи совпадают. Различия начинаются ниже.</span></p><p>Как это часто бывает, спецификации проекта в ходе разработки часто меняются, поэтому цвета всех портов ещё не установлены окончательно. Приходит $$$q$$$ модификаций, каждая из которых выглядит так: «цвета всех портов на непрерывном отрезке вдоль одной из сторон меняются на противоположные (красные на синий, синие на красный)». Предыдущие модификации не отменяются перед тем, как происходит следующая.</p><p>Чтобы оценить критичность изменений, Лестер и Делберт должны узнать пропускную способность платы после каждой модификации. Помогите им сделать это эффективно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано три целых числа $$$n, m, q$$$ ($$$1 \leq n, m \leq 10^5$$$, $$$0 \leq q \leq 10^5$$$) — количество рядов и столбцов в макете, и количество изменений соответственно.</p><p>Следующие четыре строки описывают исходные цвета портов. Каждый символ в этих строках равен <span class="tex-font-style-tt">R</span> или <span class="tex-font-style-tt">B</span> в зависимости от цвета соответствующего порта. Первые две из этих строк содержат по $$$n$$$ символов и описывают сверху вниз порты на левой и правой стороне соответственно. Следующие две строки содержат по $$$m$$$ символов и описывают слева направо порты на верхней и нижней стороне соответственно.</p><p>Следующие $$$q$$$ строк описывают модификации. Каждая из этих строк содержит символ $$$s$$$, а затем два целых числа $$$l$$$ и $$$r$$$. Если $$$s$$$ равен <span class="tex-font-style-tt">L</span> или <span class="tex-font-style-tt">R</span>, то модификация затрагивает левую/правую сторону соответственно, тогда $$$l$$$ и $$$r$$$ удовлетворяют $$$1 \leq l \leq r \leq n$$$, и порты в рядах с $$$l$$$ по $$$r$$$ (включительно) на соответствующей стороне меняют цвет. Аналогично, если $$$s$$$ равен <span class="tex-font-style-tt">U</span> или <span class="tex-font-style-tt">D</span>, то $$$1 \leq l \leq r \leq m$$$, и порты в столбцах с $$$l$$$ по $$$r$$$ (включительно) на верхней/нижней стороне соответственно меняют цвет.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ число по одному на строке — пропускную споособность платы после применения $$$0, \ldots, q$$$ модификаций к исходной раскраске портов.</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 4
BBRR
RBBR
BBBBB
RRRRR
L 2 3
R 3 4
U 1 5
D 1 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
7
7
9
4
9
</pre></div></div></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:05: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:'8124a3d6b99813b4',t:'MTY5NjY2NTkzNi41MzAwMDA='};_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>
| ["\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["*3500"] | ||
1369A | 1369 | A | ru | A. ПокупатеЛи | <div class="problem-statement"><div class="header"><div class="title">A. ПокупатеЛи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Ли собирается украсить свой дом к вечеринке с помощью нескольких правильных многоугольников...</span></p><p>Ли считает правильный (выпуклый) $$$n$$$-угольник <span class="tex-font-style-it">красивым</span> тогда и только тогда, когда он может повернуть многоугольник таким образом, чтобы хотя бы одна из его сторон стала параллельна оси $$$OX$$$ и хотя бы одна из его сторон стала параллельна оси $$$OY$$$ одновременно.</p><p>Напомним, что правильный $$$n$$$-угольник — это выпуклый многоугольник из $$$n$$$ вершин такой, что все его стороны и углы равны.</p><p>Ли пришел в магазин: в магазине продаются $$$t$$$ правильных многоугольников. Для каждого из них выведите <span class="tex-font-style-tt">YES</span>, если многоугольник красивый, или <span class="tex-font-style-tt">NO</span> в противном случае.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество многоугольников в магазине. </p><p>В каждой из следующих $$$t$$$ строк задано по одному целому числу $$$n_i$$$ ($$$3 \le n_i \le 10^9$$$): то есть $$$i$$$-й многоугольник является правильным $$$n_i$$$-угольником. </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>
4
3
4
12
1000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
YES
YES
YES
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере, в магазине продаются $$$4$$$ многоугольника. Несложно определить, что равносторонний треугольник (правильный $$$3$$$-угольник) не является красивым, квадрат (правильный $$$4$$$-угольник) является красивым, и правильный $$$12$$$-угольник (изображен ниже) также является красивым.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1fb7c77820d27b1f996dbe8b237957113d122864.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="de90b53ebe63c8a7f39e1c4d99d31080"/>
<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="ed987b890a253fac94be3b803d9df7534f5667a6"/>
<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='de90b53ebe63c8a7f39e1c4d99d31080'> </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%2F1369%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='de90b53ebe63c8a7f39e1c4d99d31080'/>
<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/1369">Codeforces Round 652 (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='de90b53ebe63c8a7f39e1c4d99d31080'/>
<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/1369/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='de90b53ebe63c8a7f39e1c4d99d31080'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="651255"/>
<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='de90b53ebe63c8a7f39e1c4d99d31080'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="651255"/>
<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/78877" title="Codeforces Round #652 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11148" resourceName="Codeforces Round #652 (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/79235" title="Codeforces Round #652 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11203" resourceName="Codeforces Round #652 (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/1369">Задачи</a></li>
<li><a
href="/contest/1369/submit">Отослать</a></li>
<li><a
href="/contest/1369/my">Мои посылки</a></li>
<li><a
href="/contest/1369/status">Статус</a></li>
<li><a
href="/contest/1369/hacks">Взломы</a></li>
<li><a
href="/contest/1369/room/1">Комната</a></li>
<li><a
href="/contest/1369/standings">Положение</a></li>
<li><a
href="/contest/1369/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_48a9ff028e7488ff3e6a0f0f07e5082ef732bd5c">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">A. ПокупатеЛи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Ли собирается украсить свой дом к вечеринке с помощью нескольких правильных многоугольников...</span></p><p>Ли считает правильный (выпуклый) $$$n$$$-угольник <span class="tex-font-style-it">красивым</span> тогда и только тогда, когда он может повернуть многоугольник таким образом, чтобы хотя бы одна из его сторон стала параллельна оси $$$OX$$$ и хотя бы одна из его сторон стала параллельна оси $$$OY$$$ одновременно.</p><p>Напомним, что правильный $$$n$$$-угольник — это выпуклый многоугольник из $$$n$$$ вершин такой, что все его стороны и углы равны.</p><p>Ли пришел в магазин: в магазине продаются $$$t$$$ правильных многоугольников. Для каждого из них выведите <span class="tex-font-style-tt">YES</span>, если многоугольник красивый, или <span class="tex-font-style-tt">NO</span> в противном случае.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество многоугольников в магазине. </p><p>В каждой из следующих $$$t$$$ строк задано по одному целому числу $$$n_i$$$ ($$$3 \le n_i \le 10^9$$$): то есть $$$i$$$-й многоугольник является правильным $$$n_i$$$-угольником. </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>
4
3
4
12
1000000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
NO
YES
YES
YES
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В примере, в магазине продаются $$$4$$$ многоугольника. Несложно определить, что равносторонний треугольник (правильный $$$3$$$-угольник) не является красивым, квадрат (правильный $$$4$$$-угольник) является красивым, и правильный $$$12$$$-угольник (изображен ниже) также является красивым.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/1fb7c77820d27b1f996dbe8b237957113d122864.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:05:38</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a3df0bfd7a69',t:'MTY5NjY2NTkzOC4yMzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*800"] | ||
1369B | 1369 | B | ru | B. ОчиститеЛи | <div class="problem-statement"><div class="header"><div class="title">B. ОчиститеЛи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Ли убирался у себя в дома перед вечеринкой, когда нашел под ковром «грязную» строку. Теперь он хочет очистить строку, но сделать это стильно...</span></p><p>Строка $$$s$$$, которую нашел Ли, является двоичной строкой длины $$$n$$$ (т. е. строка состоит только из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>).</p><p>За один шаг, он может выбрать два последовательных символа $$$s_i$$$ и $$$s_{i+1}$$$ и, если символ $$$s_i$$$ равен <span class="tex-font-style-tt">1</span> и $$$s_{i + 1}$$$ равен <span class="tex-font-style-tt">0</span>, он может удалить <span class="tex-font-style-bf">ровно один из символов</span> (Ли может выбрать какой удалить, но не может удалить оба символа одновременно). После удаления строка сжимается.</p><p>Ли может сделать произвольное количество шагов (возможно, ни одного шага) и он хочет сделать строку $$$s$$$ как можно более <span class="tex-font-style-it">чистой</span>. Он считает, что из двух различных строк $$$x$$$ и $$$y$$$ <span class="tex-font-style-bf">более короткая</span> строка чище, а если они равны по длине, то чище та, что <span class="tex-font-style-it">лексикографически меньше</span>.</p><p>Сейчас же вам необходимо ответить на $$$t$$$ наборов входных данных: для $$$i$$$-го набора, выведите самую чистую строку, которую может получить Ли за произвольное количество шагов.</p><p>Небольшое напоминание: если у нас есть две строки $$$x$$$ и $$$y$$$ равной длины, то $$$x$$$ лексикографически меньше чем $$$y$$$, если существует такая позиция $$$i$$$, что $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ и $$$x_i < y_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В следующих $$$2t$$$ строках заданы сами наборы входных данных — по одному на две строки.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — длина строки $$$s$$$.</p><p>Во второй строке задана сама бинарная строка $$$s$$$. Строка $$$s$$$ — это строка длины $$$n$$$, состоящая только из нулей и единиц.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов — по одному на набор входных данных.</p><p>Ответом на $$$i$$$-й набор является самая чистая строка, которую может получить Ли за произвольное (возможно, нулевое) количество шагов.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
10
0001111111
4
0101
8
11001101
10
1110000000
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0001111111
001
01
0
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, Ли не может сделать ни одного шага.</p><p>Во втором наборе, Ли должен удалить $$$s_2$$$.</p><p>В третьем наборе, Ли может, например, выполнить следующие шаги: 11001<span class="tex-font-style-underline">10</span>1 $$$\rightarrow$$$ 1<span class="tex-font-style-underline">10</span>0101 $$$\rightarrow$$$ 1<span class="tex-font-style-underline">10</span>101 $$$\rightarrow$$$ <span class="tex-font-style-underline">10</span>101 $$$\rightarrow$$$ 1<span class="tex-font-style-underline">10</span>1 $$$\rightarrow$$$ <span class="tex-font-style-underline">10</span>1 $$$\rightarrow$$$ 01.</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="9d8683f1f290a188cd664ac445db5647"/>
<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="ed987b890a253fac94be3b803d9df7534f5667a6"/>
<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='9d8683f1f290a188cd664ac445db5647'> </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%2F1369%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='9d8683f1f290a188cd664ac445db5647'/>
<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/1369">Codeforces Round 652 (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='9d8683f1f290a188cd664ac445db5647'/>
<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/1369/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="Сложность">
*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='9d8683f1f290a188cd664ac445db5647'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="651256"/>
<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='9d8683f1f290a188cd664ac445db5647'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="651256"/>
<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/78877" title="Codeforces Round #652 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11148" resourceName="Codeforces Round #652 (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/79235" title="Codeforces Round #652 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11203" resourceName="Codeforces Round #652 (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/1369">Задачи</a></li>
<li><a
href="/contest/1369/submit">Отослать</a></li>
<li><a
href="/contest/1369/my">Мои посылки</a></li>
<li><a
href="/contest/1369/status">Статус</a></li>
<li><a
href="/contest/1369/hacks">Взломы</a></li>
<li><a
href="/contest/1369/room/1">Комната</a></li>
<li><a
href="/contest/1369/standings">Положение</a></li>
<li><a
href="/contest/1369/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_6a095697b64a1d5766f5b7941d6e1371d915be34">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">B. ОчиститеЛи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Ли убирался у себя в дома перед вечеринкой, когда нашел под ковром «грязную» строку. Теперь он хочет очистить строку, но сделать это стильно...</span></p><p>Строка $$$s$$$, которую нашел Ли, является двоичной строкой длины $$$n$$$ (т. е. строка состоит только из символов <span class="tex-font-style-tt">0</span> и <span class="tex-font-style-tt">1</span>).</p><p>За один шаг, он может выбрать два последовательных символа $$$s_i$$$ и $$$s_{i+1}$$$ и, если символ $$$s_i$$$ равен <span class="tex-font-style-tt">1</span> и $$$s_{i + 1}$$$ равен <span class="tex-font-style-tt">0</span>, он может удалить <span class="tex-font-style-bf">ровно один из символов</span> (Ли может выбрать какой удалить, но не может удалить оба символа одновременно). После удаления строка сжимается.</p><p>Ли может сделать произвольное количество шагов (возможно, ни одного шага) и он хочет сделать строку $$$s$$$ как можно более <span class="tex-font-style-it">чистой</span>. Он считает, что из двух различных строк $$$x$$$ и $$$y$$$ <span class="tex-font-style-bf">более короткая</span> строка чище, а если они равны по длине, то чище та, что <span class="tex-font-style-it">лексикографически меньше</span>.</p><p>Сейчас же вам необходимо ответить на $$$t$$$ наборов входных данных: для $$$i$$$-го набора, выведите самую чистую строку, которую может получить Ли за произвольное количество шагов.</p><p>Небольшое напоминание: если у нас есть две строки $$$x$$$ и $$$y$$$ равной длины, то $$$x$$$ лексикографически меньше чем $$$y$$$, если существует такая позиция $$$i$$$, что $$$x_1 = y_1$$$, $$$x_2 = y_2$$$,..., $$$x_{i - 1} = y_{i - 1}$$$ и $$$x_i < y_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно целое число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В следующих $$$2t$$$ строках заданы сами наборы входных данных — по одному на две строки.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — длина строки $$$s$$$.</p><p>Во второй строке задана сама бинарная строка $$$s$$$. Строка $$$s$$$ — это строка длины $$$n$$$, состоящая только из нулей и единиц.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам не превосходит $$$10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ ответов — по одному на набор входных данных.</p><p>Ответом на $$$i$$$-й набор является самая чистая строка, которую может получить Ли за произвольное (возможно, нулевое) количество шагов.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
5
10
0001111111
4
0101
8
11001101
10
1110000000
1
1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0001111111
001
01
0
1
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, Ли не может сделать ни одного шага.</p><p>Во втором наборе, Ли должен удалить $$$s_2$$$.</p><p>В третьем наборе, Ли может, например, выполнить следующие шаги: 11001<span class="tex-font-style-underline">10</span>1 $$$\rightarrow$$$ 1<span class="tex-font-style-underline">10</span>0101 $$$\rightarrow$$$ 1<span class="tex-font-style-underline">10</span>101 $$$\rightarrow$$$ <span class="tex-font-style-underline">10</span>101 $$$\rightarrow$$$ 1<span class="tex-font-style-underline">10</span>1 $$$\rightarrow$$$ <span class="tex-font-style-underline">10</span>1 $$$\rightarrow$$$ 01.</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:05: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:'8124a3e988a79d4c',t:'MTY5NjY2NTkzOS42NzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1200"] | ||
1369C | 1369 | C | ru | C. ПриятеЛи | <div class="problem-statement"><div class="header"><div class="title">C. ПриятеЛи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Ли наконец стал мастером на Codeforces, и потому решил сходить за подарками своим друзьям. Он приобрел $$$n$$$ целых чисел, и теперь настало время распределить их между друзьями...</span></p><p>У Ли есть $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ в своем рюкзаке, а также у него $$$k$$$ друзей. Ли хочет распределить <span class="tex-font-style-bf">все</span> целые числа из рюкзака между друзьями так, чтобы $$$i$$$-му другу досталось ровно $$$w_i$$$ чисел и каждое число досталось ровно одному другу.</p><p>Назовем <span class="tex-font-style-it">уровнем счастья</span> друга сумму максимального и минимального числа, которое он получит.</p><p>Ли хочет сделать друзей как можно более счастливыми, другими словами, он хочет максимизировать суммарный уровень счастья друзей. Конечно же, Ли просит вас помочь ему посчитать этот максимальный суммарный уровень счастья.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В следующих $$$3t$$$ строках заданы сами наборы — по одному на три строки.</p><p>В первой строке каждого набора входных данных заданы два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le n$$$) — количество целых чисел в рюкзаке Ли и количество его друзей.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — сами числа в рюкзаке.</p><p>В третьей строке заданы $$$k$$$ целых чисел $$$w_1, w_2, \ldots, w_k$$$ ($$$1 \le w_i \le n$$$; $$$w_1 + w_2 + \ldots + w_k = n$$$) — количество чисел, которое Ли собирается дать каждому другу. </p><p>Гарантируется, что сумма $$$n$$$ по всем наборам не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите по одному числу — максимальный суммарный уровень счастья, который сможет достигнуть Ли.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
4 2
1 13 7 17
1 3
6 2
10 10 10 10 11 11
3 3
4 4
1000000000 1000000000 1000000000 1000000000
1 1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
48
42
8000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, Ли нужно отдать наибольшее число первому другу (его уровень счастья будет равен $$$17 + 17$$$) и остальные числа — второму (его уровень счастья будет равен $$$13 + 1$$$).</p><p>В втором наборе, Ли нужно отдать $$$\{10, 10, 11\}$$$ и первому и второму другу, тогда суммарный уровень счастья будет равен $$$(11 + 10) + (11 + 10)$$$</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="ddc7be05bf628c921313a9bf4417b522"/>
<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="ed987b890a253fac94be3b803d9df7534f5667a6"/>
<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='ddc7be05bf628c921313a9bf4417b522'> </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%2F1369%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='ddc7be05bf628c921313a9bf4417b522'/>
<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/1369">Codeforces Round 652 (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='ddc7be05bf628c921313a9bf4417b522'/>
<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/1369/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='ddc7be05bf628c921313a9bf4417b522'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="651257"/>
<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='ddc7be05bf628c921313a9bf4417b522'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="651257"/>
<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/78877" title="Codeforces Round #652 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11148" resourceName="Codeforces Round #652 (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/79235" title="Codeforces Round #652 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11203" resourceName="Codeforces Round #652 (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/1369">Задачи</a></li>
<li><a
href="/contest/1369/submit">Отослать</a></li>
<li><a
href="/contest/1369/my">Мои посылки</a></li>
<li><a
href="/contest/1369/status">Статус</a></li>
<li><a
href="/contest/1369/hacks">Взломы</a></li>
<li><a
href="/contest/1369/room/1">Комната</a></li>
<li><a
href="/contest/1369/standings">Положение</a></li>
<li><a
href="/contest/1369/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_e37cad2f296e8a7a9e7290089f559e0786f4d917">
<div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier">
<div>Условие задачи было недавно изменено. <a class="view-changes" href="#">Просмотреть изменения.</a></div>
<span class="diff-notifier-close" style="position: absolute; top: 0.2em; right: 0.3em; cursor: pointer; font-size: 1.4em;">×</span>
</div>
<div class="ttypography"><div class="problem-statement"><div class="header"><div class="title">C. ПриятеЛи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Ли наконец стал мастером на Codeforces, и потому решил сходить за подарками своим друзьям. Он приобрел $$$n$$$ целых чисел, и теперь настало время распределить их между друзьями...</span></p><p>У Ли есть $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ в своем рюкзаке, а также у него $$$k$$$ друзей. Ли хочет распределить <span class="tex-font-style-bf">все</span> целые числа из рюкзака между друзьями так, чтобы $$$i$$$-му другу досталось ровно $$$w_i$$$ чисел и каждое число досталось ровно одному другу.</p><p>Назовем <span class="tex-font-style-it">уровнем счастья</span> друга сумму максимального и минимального числа, которое он получит.</p><p>Ли хочет сделать друзей как можно более счастливыми, другими словами, он хочет максимизировать суммарный уровень счастья друзей. Конечно же, Ли просит вас помочь ему посчитать этот максимальный суммарный уровень счастья.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В следующих $$$3t$$$ строках заданы сами наборы — по одному на три строки.</p><p>В первой строке каждого набора входных данных заданы два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le n$$$) — количество целых чисел в рюкзаке Ли и количество его друзей.</p><p>Во второй строке каждого набора заданы $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — сами числа в рюкзаке.</p><p>В третьей строке заданы $$$k$$$ целых чисел $$$w_1, w_2, \ldots, w_k$$$ ($$$1 \le w_i \le n$$$; $$$w_1 + w_2 + \ldots + w_k = n$$$) — количество чисел, которое Ли собирается дать каждому другу. </p><p>Гарантируется, что сумма $$$n$$$ по всем наборам не превосходит $$$2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите по одному числу — максимальный суммарный уровень счастья, который сможет достигнуть Ли.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
3
4 2
1 13 7 17
1 3
6 2
10 10 10 10 11 11
3 3
4 4
1000000000 1000000000 1000000000 1000000000
1 1 1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
48
42
8000000000
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных, Ли нужно отдать наибольшее число первому другу (его уровень счастья будет равен $$$17 + 17$$$) и остальные числа — второму (его уровень счастья будет равен $$$13 + 1$$$).</p><p>В втором наборе, Ли нужно отдать $$$\{10, 10, 11\}$$$ и первому и второму другу, тогда суммарный уровень счастья будет равен $$$(11 + 10) + (11 + 10)$$$</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:05: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:'8124a3f2cb779d4c',t:'MTY5NjY2NTk0MS4xNTEwMDA='};_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", "\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"] | ["\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1400"] | ||
1369D | 1369 | 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><span class="tex-font-style-it">Ли потратил так много времени на создание хорошей div.2 D задачи, чтобы сбалансировать недавний контест, но задача продолжает ощущаться неподходящей. Ли придумывал ее так мучительно долго, что заработал фобию div.2 D задач. И теперь он прячется в кустах...</span></p><p>Назовем <span class="tex-font-style-it">Корневым Сухим Кустом</span> (КСК) уровня $$$n$$$ корневое дерево, построенное согласно правилам ниже.</p><p>Корневой Сухой Куст уровня $$$1$$$ — это одна вершина. Для построения КСК уровня $$$i$$$, сначала построим КСК уровня $$$i-1$$$ и далее для каждой вершины $$$u$$$: </p><ul> <li> если у $$$u$$$ нет детей, то подвесим к ней одного сына; </li><li> если у $$$u$$$ есть один сын, то подвесим к ней еще двух детей; </li><li> если у $$$u$$$ есть более одного сына, то пропустим ее. </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/bc12fd72ff405f3dcf8fe43f587b14f1c73980df.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Корневые Сухие Кусты уровня $$$1$$$, $$$2$$$ и $$$3$$$.</span> </center><p>Назовем <span class="tex-font-style-it">лапой</span> корневое дерево из четырех вершин: одна корневая вершина (также называется центром) и три ребенка. Оно напоминает лапу:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2fa28290a38e1783879aa47b2d323f1eef3d32cc.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Центром лапы является вершина с номером $$$1$$$.</span> </center><p>У Ли есть Корневой Сухой Куст уровня $$$n$$$. Первоначально все вершины КСК зеленого цвета.</p><p>За один шаг, он может выбрать лапу в КСК и, если все вершины в ней <span class="tex-font-style-it">зеленые</span> и все вершины лапы являются детьми ее центра, покрасить вершины лапы в в желтый.</p><p>Ли хочет узнать максимальное количество желтых вершин, которое он сможет получить. Так как ответ может быть очень большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В следующих $$$t$$$ строках заданы сами наборы — по одному в строке.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^6$$$) — уровень КСК Ли.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число — максимальное количество желтых вершин, которые может получить Ли, по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
1
2
3
4
5
100
2000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
4
4
12
990998587
804665184
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Несложно заметить, что ответ для КСК уровня $$$1$$$ или $$$2$$$ равен $$$0$$$.</p><p>Ответ для КСК уровня $$$3$$$ равен $$$4$$$, так как есть только одна лапа, которую можно выбрать: $$$\{1, 2, 3, 4\}$$$.</p><p>Ответ для КСК уровня $$$4$$$ равен $$$4$$$, так как мы можем выбрать либо одну лапу $$$\{1, 3, 2, 4\}$$$ или одну лапу $$$\{2, 7, 5, 6\}$$$. Других лап в КСК уровня $$$4$$$ нет (например, мы не можем выбрать $$$\{2, 1, 7, 6\}$$$, так как $$$1$$$ не является ребенком вершины-центра $$$2$$$).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e328eb531653ffb0449ef2ae13f3d80242b3c8af.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Корневой Сухой Куст уровня 4.</span> </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="60bb289e6d6e0722eb778aed20c30fc5"/>
<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="ed987b890a253fac94be3b803d9df7534f5667a6"/>
<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='60bb289e6d6e0722eb778aed20c30fc5'> </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%2F1369%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='60bb289e6d6e0722eb778aed20c30fc5'/>
<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/1369">Codeforces Round 652 (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='60bb289e6d6e0722eb778aed20c30fc5'/>
<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/1369/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='60bb289e6d6e0722eb778aed20c30fc5'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="651258"/>
<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='60bb289e6d6e0722eb778aed20c30fc5'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="651258"/>
<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/78877" title="Codeforces Round #652 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11148" resourceName="Codeforces Round #652 (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/79235" title="Codeforces Round #652 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11203" resourceName="Codeforces Round #652 (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/1369">Задачи</a></li>
<li><a
href="/contest/1369/submit">Отослать</a></li>
<li><a
href="/contest/1369/my">Мои посылки</a></li>
<li><a
href="/contest/1369/status">Статус</a></li>
<li><a
href="/contest/1369/hacks">Взломы</a></li>
<li><a
href="/contest/1369/room/1">Комната</a></li>
<li><a
href="/contest/1369/standings">Положение</a></li>
<li><a
href="/contest/1369/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_cf85a91f97187052b48666957b3fbf28598b2ae1">
<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><span class="tex-font-style-it">Ли потратил так много времени на создание хорошей div.2 D задачи, чтобы сбалансировать недавний контест, но задача продолжает ощущаться неподходящей. Ли придумывал ее так мучительно долго, что заработал фобию div.2 D задач. И теперь он прячется в кустах...</span></p><p>Назовем <span class="tex-font-style-it">Корневым Сухим Кустом</span> (КСК) уровня $$$n$$$ корневое дерево, построенное согласно правилам ниже.</p><p>Корневой Сухой Куст уровня $$$1$$$ — это одна вершина. Для построения КСК уровня $$$i$$$, сначала построим КСК уровня $$$i-1$$$ и далее для каждой вершины $$$u$$$: </p><ul> <li> если у $$$u$$$ нет детей, то подвесим к ней одного сына; </li><li> если у $$$u$$$ есть один сын, то подвесим к ней еще двух детей; </li><li> если у $$$u$$$ есть более одного сына, то пропустим ее. </li></ul><center> <img class="tex-graphics" src="https://espresso.codeforces.com/bc12fd72ff405f3dcf8fe43f587b14f1c73980df.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Корневые Сухие Кусты уровня $$$1$$$, $$$2$$$ и $$$3$$$.</span> </center><p>Назовем <span class="tex-font-style-it">лапой</span> корневое дерево из четырех вершин: одна корневая вершина (также называется центром) и три ребенка. Оно напоминает лапу:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/2fa28290a38e1783879aa47b2d323f1eef3d32cc.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Центром лапы является вершина с номером $$$1$$$.</span> </center><p>У Ли есть Корневой Сухой Куст уровня $$$n$$$. Первоначально все вершины КСК зеленого цвета.</p><p>За один шаг, он может выбрать лапу в КСК и, если все вершины в ней <span class="tex-font-style-it">зеленые</span> и все вершины лапы являются детьми ее центра, покрасить вершины лапы в в желтый.</p><p>Ли хочет узнать максимальное количество желтых вершин, которое он сможет получить. Так как ответ может быть очень большим, выведите его по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно число $$$t$$$ ($$$1 \le t \le 10^4$$$) — количество наборов входных данных.</p><p>В следующих $$$t$$$ строках заданы сами наборы — по одному в строке.</p><p>В первой строке каждого набора задано одно целое число $$$n$$$ ($$$1 \le n \le 2 \cdot 10^6$$$) — уровень КСК Ли.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных выведите единственное целое число — максимальное количество желтых вершин, которые может получить Ли, по модулю $$$10^9 + 7$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
7
1
2
3
4
5
100
2000000
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0
0
4
4
12
990998587
804665184
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Несложно заметить, что ответ для КСК уровня $$$1$$$ или $$$2$$$ равен $$$0$$$.</p><p>Ответ для КСК уровня $$$3$$$ равен $$$4$$$, так как есть только одна лапа, которую можно выбрать: $$$\{1, 2, 3, 4\}$$$.</p><p>Ответ для КСК уровня $$$4$$$ равен $$$4$$$, так как мы можем выбрать либо одну лапу $$$\{1, 3, 2, 4\}$$$ или одну лапу $$$\{2, 7, 5, 6\}$$$. Других лап в КСК уровня $$$4$$$ нет (например, мы не можем выбрать $$$\{2, 1, 7, 6\}$$$, так как $$$1$$$ не является ребенком вершины-центра $$$2$$$).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e328eb531653ffb0449ef2ae13f3d80242b3c8af.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Корневой Сухой Куст уровня 4.</span> </center></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:05:42</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a3fbea6c7b37',t:'MTY5NjY2NTk0Mi44MDAwMDA='};_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", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1900"] | ||
1369E | 1369 | 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-it">Ли приобрел некоторой еды на обед, но приглашать друзей Ли на обед смертельно опасно. Ли напуган, он не хочет умирать, хотя бы пока не увидит Online IOI 2020...</span></p><p>Всего есть $$$n$$$ различных видов еды и $$$m$$$ лучших друзей Ли. У Ли есть $$$w_i$$$ тарелок $$$i$$$-го вида еды, и у каждого друга Ли есть два любимых вида еды: любимые блюда $$$i$$$-го друга — это $$$x_i$$$ и $$$y_i$$$ ($$$x_i \ne y_i$$$).</p><p>Ли начнет вызывать своих друзей по одному. Каждый, кого вызвали, пойдет на кухню и попытается съесть по <span class="tex-font-style-bf">одной тарелке каждого из его любимых видов еды</span>. Каждый друг зайдет на кухню ровно один раз.</p><p>Но проблема в следующем: если друг съест хотя бы одну тарелку еды (суммарно), то он станет абсолютно безвреден. Но если другу нечего есть (не осталось ни $$$x_i$$$, ни $$$y_i$$$), то он съест самого Ли $$$\times\_\times$$$.</p><p>Ли может выбрать, в каком порядке приглашать друзей, а потому Ли хочет понять, может ли он пережить ужин или нет. Также его интересует непосредственно сам порядок.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 10^5$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — количество видов еды и количество друзей Ли. </p><p>Во второй строке заданы $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^6$$$) — количество тарелок с едой каждого вида.</p><p>В $$$i$$$-й строке из следующих $$$m$$$ строк заданы два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$) — любимые виды еды $$$i$$$-го друга. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если Ли может пережить обед, выведите <span class="tex-font-style-tt">ALIVE</span> (регистр букв не важен), иначе выведите <span class="tex-font-style-tt">DEAD</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>
3 3
1 2 1
1 2
2 3
1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
ALIVE
3 2 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 2
1 1 0
1 2
1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
ALIVE
2 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 4
1 2 0 1
1 3
1 2
2 3
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
ALIVE
1 3 2 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5
1 1 1 2 1
3 4
1 2
2 3
4 5
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
ALIVE
5 4 1 3 2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 10
2 4 1 4
3 2
4 2
4 1
3 1
4 1
1 3
3 2
2 1
3 1
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
DEAD
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, любой из следующих порядков друзей будет корректным: $$$[1, 3, 2]$$$, $$$[3, 1, 2]$$$, $$$[2, 3, 1]$$$, $$$[3, 2, 1]$$$.</p><p>Во втором примере, Ли следует вызвать второго друга первым (тогда он съест тарелку еды $$$1$$$), а потом и первого друга (этот друг съесть тарелку еды $$$2$$$). Если же Ли вызовет сначала первого друга, то он съесть по одной тарелке еды $$$1$$$ и $$$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="0f87160836e7276a5bcf26cb53093843"/>
<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="ed987b890a253fac94be3b803d9df7534f5667a6"/>
<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='0f87160836e7276a5bcf26cb53093843'> </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%2F1369%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='0f87160836e7276a5bcf26cb53093843'/>
<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/1369">Codeforces Round 652 (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='0f87160836e7276a5bcf26cb53093843'/>
<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/1369/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Жадные алгоритмы">
жадные алгоритмы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Реализация, техника программирования, симуляция">
реализация
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сортировки, упорядочения">
сортировки
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др.">
структуры данных
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0f87160836e7276a5bcf26cb53093843'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="651259"/>
<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='0f87160836e7276a5bcf26cb53093843'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="651259"/>
<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/78877" title="Codeforces Round #652 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11148" resourceName="Codeforces Round #652 (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/79235" title="Codeforces Round #652 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11203" resourceName="Codeforces Round #652 (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/1369">Задачи</a></li>
<li><a
href="/contest/1369/submit">Отослать</a></li>
<li><a
href="/contest/1369/my">Мои посылки</a></li>
<li><a
href="/contest/1369/status">Статус</a></li>
<li><a
href="/contest/1369/hacks">Взломы</a></li>
<li><a
href="/contest/1369/room/1">Комната</a></li>
<li><a
href="/contest/1369/standings">Положение</a></li>
<li><a
href="/contest/1369/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_ce04490a7e20f2d3249bb9ddd650fab5be05a809">
<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-it">Ли приобрел некоторой еды на обед, но приглашать друзей Ли на обед смертельно опасно. Ли напуган, он не хочет умирать, хотя бы пока не увидит Online IOI 2020...</span></p><p>Всего есть $$$n$$$ различных видов еды и $$$m$$$ лучших друзей Ли. У Ли есть $$$w_i$$$ тарелок $$$i$$$-го вида еды, и у каждого друга Ли есть два любимых вида еды: любимые блюда $$$i$$$-го друга — это $$$x_i$$$ и $$$y_i$$$ ($$$x_i \ne y_i$$$).</p><p>Ли начнет вызывать своих друзей по одному. Каждый, кого вызвали, пойдет на кухню и попытается съесть по <span class="tex-font-style-bf">одной тарелке каждого из его любимых видов еды</span>. Каждый друг зайдет на кухню ровно один раз.</p><p>Но проблема в следующем: если друг съест хотя бы одну тарелку еды (суммарно), то он станет абсолютно безвреден. Но если другу нечего есть (не осталось ни $$$x_i$$$, ни $$$y_i$$$), то он съест самого Ли $$$\times\_\times$$$.</p><p>Ли может выбрать, в каком порядке приглашать друзей, а потому Ли хочет понять, может ли он пережить ужин или нет. Также его интересует непосредственно сам порядок.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 10^5$$$; $$$1 \le m \le 2 \cdot 10^5$$$) — количество видов еды и количество друзей Ли. </p><p>Во второй строке заданы $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^6$$$) — количество тарелок с едой каждого вида.</p><p>В $$$i$$$-й строке из следующих $$$m$$$ строк заданы два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$; $$$x_i \ne y_i$$$) — любимые виды еды $$$i$$$-го друга. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если Ли может пережить обед, выведите <span class="tex-font-style-tt">ALIVE</span> (регистр букв не важен), иначе выведите <span class="tex-font-style-tt">DEAD</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>
3 3
1 2 1
1 2
2 3
1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
ALIVE
3 2 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
3 2
1 1 0
1 2
1 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
ALIVE
2 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 4
1 2 0 1
1 3
1 2
2 3
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
ALIVE
1 3 2 4
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 5
1 1 1 2 1
3 4
1 2
2 3
4 5
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
ALIVE
5 4 1 3 2
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 10
2 4 1 4
3 2
4 2
4 1
3 1
4 1
1 3
3 2
2 1
3 1
2 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
DEAD
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, любой из следующих порядков друзей будет корректным: $$$[1, 3, 2]$$$, $$$[3, 1, 2]$$$, $$$[2, 3, 1]$$$, $$$[3, 2, 1]$$$.</p><p>Во втором примере, Ли следует вызвать второго друга первым (тогда он съест тарелку еды $$$1$$$), а потом и первого друга (этот друг съесть тарелку еды $$$2$$$). Если же Ли вызовет сначала первого друга, то он съесть по одной тарелке еды $$$1$$$ и $$$2$$$, а следовательно другому другу ничего не останется.</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:05: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:'8124a406398816db',t:'MTY5NjY2NTk0NC4zMzQwMDA='};_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\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\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", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"] | ||
1369F | 1369 | 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><span class="tex-font-style-it">Ли предпочитает завершать свои истории стильно, но не в этот раз. Благо, Белый Медведь успел придти к нему на помощь. В благодарность, Ли решил показать Белому его новую игру под названием «Critic»...</span></p><p>Данная игра — один на один. Она состоит из $$$t$$$ раундов, каждый раунд определяется двумя целыми числами $$$s_i$$$ и $$$e_i$$$ (которые определены заранее и известны перед началом игры, $$$s_i$$$ и $$$e_i$$$ могут отличаться от раунда к раунду). В начале соответствующего раунда число $$$s_i$$$ написано на доске. </p><p>Игроки ходят по очереди. Каждый игрок стирает число на доске (назовем его $$$a$$$) и выбирает, что написать: $$$2 \cdot a$$$ или $$$a + 1$$$. Тот, кто напишет на доске число строго больше чем $$$e_i$$$, проигрывает.</p><p>Сейчас Ли хочет сыграть в «Critic» против Белого, и для каждого раунда он уже выбрал соответствующие $$$s_i$$$ и $$$e_i$$$. Ли начинает первый раунд, и проигравший текущего раунда будет начинать в следующем раунде.</p><p>Победитель последнего раунда считается победителем всей игры, а проигравший, соответственно, проигравшим всей игры.</p><p>Определите, может ли Ли победить независимо от действий Белого. Также, определите, может ли он проиграть независимо от действий Белого.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 10^5$$$) — количество раундов в игре.</p><p>В следующих $$$t$$$ строках заданы по два целых числа $$$s_i$$$ и $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — информация про $$$i$$$-й раунд.</p><p>Раунды играются в том порядке, как они заданы во входных данных, $$$s_i$$$ и $$$e_i$$$ для всех раундов известны всем до начала игры.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два числа.</p><p>Первым числом выведите <span class="tex-font-style-tt">1</span>, если Ли может победить независимо от действий Белого, иначе выведите <span class="tex-font-style-tt">0</span>.</p><p>Вторым числом выведите <span class="tex-font-style-tt">1</span>, если Ли может проиграть независимо от действий Белого, иначе выведите <span class="tex-font-style-tt">0</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 8
1 4
3 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
1 2
2 3
3 4
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
1 9
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
1 2
2 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
216986951114298167 235031205335543871
148302405431848579 455670351549314242
506251128322958430 575521452907339082
1 768614336404564650
189336074809158272 622104412002885672
588320087414024192 662540324268197150
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Напоминаем, проигрывает тот, кто напишет число строго больше чем $$$e_i$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="3de858aa30577e6c3e65971a66c05465"/>
<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="ed987b890a253fac94be3b803d9df7534f5667a6"/>
<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='3de858aa30577e6c3e65971a66c05465'> </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%2F1369%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='3de858aa30577e6c3e65971a66c05465'/>
<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/1369">Codeforces Round 652 (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='3de858aa30577e6c3e65971a66c05465'/>
<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/1369/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='3de858aa30577e6c3e65971a66c05465'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="651260"/>
<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='3de858aa30577e6c3e65971a66c05465'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="651260"/>
<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/78877" title="Codeforces Round #652 (Div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11148" resourceName="Codeforces Round #652 (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/79235" title="Codeforces Round #652 (Div. 2) Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11203" resourceName="Codeforces Round #652 (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/1369">Задачи</a></li>
<li><a
href="/contest/1369/submit">Отослать</a></li>
<li><a
href="/contest/1369/my">Мои посылки</a></li>
<li><a
href="/contest/1369/status">Статус</a></li>
<li><a
href="/contest/1369/hacks">Взломы</a></li>
<li><a
href="/contest/1369/room/1">Комната</a></li>
<li><a
href="/contest/1369/standings">Положение</a></li>
<li><a
href="/contest/1369/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_20c5307d2723ea7e175750a6563b5a62ec417939">
<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><span class="tex-font-style-it">Ли предпочитает завершать свои истории стильно, но не в этот раз. Благо, Белый Медведь успел придти к нему на помощь. В благодарность, Ли решил показать Белому его новую игру под названием «Critic»...</span></p><p>Данная игра — один на один. Она состоит из $$$t$$$ раундов, каждый раунд определяется двумя целыми числами $$$s_i$$$ и $$$e_i$$$ (которые определены заранее и известны перед началом игры, $$$s_i$$$ и $$$e_i$$$ могут отличаться от раунда к раунду). В начале соответствующего раунда число $$$s_i$$$ написано на доске. </p><p>Игроки ходят по очереди. Каждый игрок стирает число на доске (назовем его $$$a$$$) и выбирает, что написать: $$$2 \cdot a$$$ или $$$a + 1$$$. Тот, кто напишет на доске число строго больше чем $$$e_i$$$, проигрывает.</p><p>Сейчас Ли хочет сыграть в «Critic» против Белого, и для каждого раунда он уже выбрал соответствующие $$$s_i$$$ и $$$e_i$$$. Ли начинает первый раунд, и проигравший текущего раунда будет начинать в следующем раунде.</p><p>Победитель последнего раунда считается победителем всей игры, а проигравший, соответственно, проигравшим всей игры.</p><p>Определите, может ли Ли победить независимо от действий Белого. Также, определите, может ли он проиграть независимо от действий Белого.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное целое число $$$t$$$ ($$$1 \le t \le 10^5$$$) — количество раундов в игре.</p><p>В следующих $$$t$$$ строках заданы по два целых числа $$$s_i$$$ и $$$e_i$$$ ($$$1 \le s_i \le e_i \le 10^{18}$$$) — информация про $$$i$$$-й раунд.</p><p>Раунды играются в том порядке, как они заданы во входных данных, $$$s_i$$$ и $$$e_i$$$ для всех раундов известны всем до начала игры.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два числа.</p><p>Первым числом выведите <span class="tex-font-style-tt">1</span>, если Ли может победить независимо от действий Белого, иначе выведите <span class="tex-font-style-tt">0</span>.</p><p>Вторым числом выведите <span class="tex-font-style-tt">1</span>, если Ли может проиграть независимо от действий Белого, иначе выведите <span class="tex-font-style-tt">0</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 8
1 4
3 10
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4
1 2
2 3
3 4
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
1
1 1
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 1
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
1 9
4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
0 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
2
1 2
2 8
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 0
</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6
216986951114298167 235031205335543871
148302405431848579 455670351549314242
506251128322958430 575521452907339082
1 768614336404564650
189336074809158272 622104412002885672
588320087414024192 662540324268197150
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1 0
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Напоминаем, проигрывает тот, кто напишет число строго больше чем $$$e_i$$$.</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:05: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:'8124a40fbb421607',t:'MTY5NjY2NTk0NS44NDkwMDA='};_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\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0434\u043f", "\u0438\u0433\u0440\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2700"] | ||
1370A | 1370 | 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$$$ до $$$n$$$ (включительно).</p><p>По всем парам <span class="tex-font-style-bf">различных</span> целых чисел из этого промежутка, найдите максимальное возможное значение наибольшего общего делителя чисел в паре. Более формально, найдите максимальное значение $$$\mathrm{gcd}(a, b)$$$ по всем $$$1 \leq a < b \leq n$$$.</p><p>Наибольшим общим делителем $$$\mathrm{gcd}(a, b)$$$ пары положительных целых чисел $$$a$$$ и $$$b$$$ называется наибольшее целое число, являющееся делителем числа $$$a$$$ и делителем числа $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В единственной строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$2 \leq n \leq 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите максимальное значение $$$\mathrm{gcd}(a, b)$$$ по всем $$$1 \leq a < b \leq n$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
3
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$\mathrm{gcd}(1, 2) = \mathrm{gcd}(2, 3) = \mathrm{gcd}(1, 3) = 1$$$.</p><p>Во втором наборе входных данных $$$2$$$ является максимальным возможным значением, соответствующим $$$\mathrm{gcd}(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="f03643fc1352ba0303087f8c1f69b85b"/>
<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="7d49361ec1470696e411126176d2b4c325509403"/>
<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='f03643fc1352ba0303087f8c1f69b85b'> </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%2F1370%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='f03643fc1352ba0303087f8c1f69b85b'/>
<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/1370">Codeforces Round 651 (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='f03643fc1352ba0303087f8c1f69b85b'/>
<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/1370/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="Сложность">
*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='f03643fc1352ba0303087f8c1f69b85b'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652383"/>
<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='f03643fc1352ba0303087f8c1f69b85b'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652383"/>
<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/79038" title="79038" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12555" resourceName="79038"
resourceManual="true" src="//codeforces.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/79107" title="Editorial — Codeforces Round #651" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11210" resourceName="Editorial — Codeforces Round #651"
resourceManual="true" src="//codeforces.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/1370">Задачи</a></li>
<li><a
href="/contest/1370/submit">Отослать</a></li>
<li><a
href="/contest/1370/my">Мои посылки</a></li>
<li><a
href="/contest/1370/status">Статус</a></li>
<li><a
href="/contest/1370/hacks">Взломы</a></li>
<li><a
href="/contest/1370/room/1">Комната</a></li>
<li><a
href="/contest/1370/standings">Положение</a></li>
<li><a
href="/contest/1370/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_08d8883367fac1017e27a4ba3be69c1c7f1b05f2">
<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$$$ до $$$n$$$ (включительно).</p><p>По всем парам <span class="tex-font-style-bf">различных</span> целых чисел из этого промежутка, найдите максимальное возможное значение наибольшего общего делителя чисел в паре. Более формально, найдите максимальное значение $$$\mathrm{gcd}(a, b)$$$ по всем $$$1 \leq a < b \leq n$$$.</p><p>Наибольшим общим делителем $$$\mathrm{gcd}(a, b)$$$ пары положительных целых чисел $$$a$$$ и $$$b$$$ называется наибольшее целое число, являющееся делителем числа $$$a$$$ и делителем числа $$$b$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В единственной строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$2 \leq n \leq 10^6$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите максимальное значение $$$\mathrm{gcd}(a, b)$$$ по всем $$$1 \leq a < b \leq n$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
2
3
5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1
2
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$\mathrm{gcd}(1, 2) = \mathrm{gcd}(2, 3) = \mathrm{gcd}(1, 3) = 1$$$.</p><p>Во втором наборе входных данных $$$2$$$ является максимальным возможным значением, соответствующим $$$\mathrm{gcd}(2, 4)$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=A]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:05: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:'8124a4196b6d75a3',t:'MTY5NjY2NTk0Ny41NDAwMDA='};_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", "\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*800"] | ||
1370B | 1370 | 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>У Ashish есть массив $$$a$$$, состоящий из $$$2n$$$ положительных целых чисел. Он хочет сжать массив $$$a$$$ в массив $$$b$$$ размера $$$n-1$$$. Чтобы это сделать, он сначала выбирает ровно $$$2$$$ (любые два) элемента массива $$$a$$$ и удаляет их из массива. После этого он выполняет следующую операцию, пока массив $$$a$$$ не пустой:</p><ul> <li> удалить любые два элемента из массива $$$a$$$ и добавить их сумму в массив $$$b$$$. </li></ul><p>Получившийся массив $$$b$$$ должен удовлетворять одному условию. Наибольший общий делитель ($$$\mathrm{gcd}$$$) всех элементов массива должен быть больше $$$1$$$.</p><p>Напомним, что наибольший общий делитель ($$$\mathrm{gcd}$$$) массива положительных целых чисел равен наибольшему целому числу, которое является делителем всех элементов массива.</p><p>Можно доказать, что всегда можно таким образом сжать массив $$$a$$$ в массив $$$b$$$ размера $$$n-1$$$, так что $$$gcd(b_1, b_2..., b_{n-1}) > 1$$$.</p><p>Помогите Ashish найти способ это сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 10$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$2 \leq n \leq 1000$$$).</p><p>Во второй строке описания каждого набора входных данных находится $$$2n$$$ целых чисел $$$a_1, a_2, \ldots, a_{2n}$$$ ($$$1 \leq a_i \leq 1000$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите $$$n-1$$$ строку — выполненные операции, чтобы сжать массив $$$a$$$ в массив $$$b$$$. <span class="tex-font-style-bf">Изначальное удаление двух элементов не является операцией и про это действие не нужно ничего выводить.</span></p><p>В $$$i$$$-й из этих строк должно находиться два целых числа, индексы (нумерация с $$$1$$$) двух элементов массива $$$a$$$, которые используются в $$$i$$$-й операции. Все $$$2n-2$$$ выведенных индекса должны быть различными целыми числами от $$$1$$$ до $$$2n$$$.</p><p>Вам не нужно выводить индексы двух изначально удаленных элементов из массива $$$a$$$.</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
1 2 3 4 5 6
2
5 7 9 10
5
1 3 3 4 5 90 100 101 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 6
4 5
3 4
1 9
2 3
4 5
6 10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$b = \{3+6, 4+5\} = \{9, 9\}$$$ и $$$\mathrm{gcd}(9, 9) = 9$$$.</p><p>Во втором наборе входных данных $$$b = \{9+10\} = \{19\}$$$ и $$$\mathrm{gcd}(19) = 19$$$.</p><p>В третьем наборе входных данных $$$b = \{1+2, 3+3, 4+5, 90+3\} = \{3, 6, 9, 93\}$$$ и $$$\mathrm{gcd}(3, 6, 9, 93) = 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="0ef3660d55345b754775d99d70d4d593"/>
<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="7d49361ec1470696e411126176d2b4c325509403"/>
<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='0ef3660d55345b754775d99d70d4d593'> </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%2F1370%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='0ef3660d55345b754775d99d70d4d593'/>
<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/1370">Codeforces Round 651 (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='0ef3660d55345b754775d99d70d4d593'/>
<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/1370/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='0ef3660d55345b754775d99d70d4d593'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652384"/>
<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='0ef3660d55345b754775d99d70d4d593'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652384"/>
<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/79038" title="79038" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12555" resourceName="79038"
resourceManual="true" src="//codeforces.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/79107" title="Editorial — Codeforces Round #651" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11210" resourceName="Editorial — Codeforces Round #651"
resourceManual="true" src="//codeforces.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/1370">Задачи</a></li>
<li><a
href="/contest/1370/submit">Отослать</a></li>
<li><a
href="/contest/1370/my">Мои посылки</a></li>
<li><a
href="/contest/1370/status">Статус</a></li>
<li><a
href="/contest/1370/hacks">Взломы</a></li>
<li><a
href="/contest/1370/room/1">Комната</a></li>
<li><a
href="/contest/1370/standings">Положение</a></li>
<li><a
href="/contest/1370/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_8ce5aa1dccaa80d7ca60ec9400fe13afbdf76db1">
<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>У Ashish есть массив $$$a$$$, состоящий из $$$2n$$$ положительных целых чисел. Он хочет сжать массив $$$a$$$ в массив $$$b$$$ размера $$$n-1$$$. Чтобы это сделать, он сначала выбирает ровно $$$2$$$ (любые два) элемента массива $$$a$$$ и удаляет их из массива. После этого он выполняет следующую операцию, пока массив $$$a$$$ не пустой:</p><ul> <li> удалить любые два элемента из массива $$$a$$$ и добавить их сумму в массив $$$b$$$. </li></ul><p>Получившийся массив $$$b$$$ должен удовлетворять одному условию. Наибольший общий делитель ($$$\mathrm{gcd}$$$) всех элементов массива должен быть больше $$$1$$$.</p><p>Напомним, что наибольший общий делитель ($$$\mathrm{gcd}$$$) массива положительных целых чисел равен наибольшему целому числу, которое является делителем всех элементов массива.</p><p>Можно доказать, что всегда можно таким образом сжать массив $$$a$$$ в массив $$$b$$$ размера $$$n-1$$$, так что $$$gcd(b_1, b_2..., b_{n-1}) > 1$$$.</p><p>Помогите Ashish найти способ это сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 10$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В первой строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$2 \leq n \leq 1000$$$).</p><p>Во второй строке описания каждого набора входных данных находится $$$2n$$$ целых чисел $$$a_1, a_2, \ldots, a_{2n}$$$ ($$$1 \leq a_i \leq 1000$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите $$$n-1$$$ строку — выполненные операции, чтобы сжать массив $$$a$$$ в массив $$$b$$$. <span class="tex-font-style-bf">Изначальное удаление двух элементов не является операцией и про это действие не нужно ничего выводить.</span></p><p>В $$$i$$$-й из этих строк должно находиться два целых числа, индексы (нумерация с $$$1$$$) двух элементов массива $$$a$$$, которые используются в $$$i$$$-й операции. Все $$$2n-2$$$ выведенных индекса должны быть различными целыми числами от $$$1$$$ до $$$2n$$$.</p><p>Вам не нужно выводить индексы двух изначально удаленных элементов из массива $$$a$$$.</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
1 2 3 4 5 6
2
5 7 9 10
5
1 3 3 4 5 90 100 101 2 3
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3 6
4 5
3 4
1 9
2 3
4 5
6 10
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$b = \{3+6, 4+5\} = \{9, 9\}$$$ и $$$\mathrm{gcd}(9, 9) = 9$$$.</p><p>Во втором наборе входных данных $$$b = \{9+10\} = \{19\}$$$ и $$$\mathrm{gcd}(19) = 19$$$.</p><p>В третьем наборе входных данных $$$b = \{1+2, 3+3, 4+5, 90+3\} = \{3, 6, 9, 93\}$$$ и $$$\mathrm{gcd}(3, 6, 9, 93) = 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:05:49</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a423ca1616ab',t:'MTY5NjY2NTk0OS4xMjMwMDA='};_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", "*1100"] | ||
1370C | 1370 | 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>Ashishgup и FastestFinger играют в игру. </p><p>Они начинают с целого числа $$$n$$$ и начинают делать ходы по очереди. На каждом ходу игрок может сделать <span class="tex-font-style-bf">любой из</span> следующих двух ходов:</p><ul> <li> Разделить $$$n$$$ на один из его нечетных делителей, который больше чем $$$1$$$. </li><li> Вычесть $$$1$$$ из $$$n$$$, если $$$n$$$ больше чем $$$1$$$. </li></ul><p>Обратите внимание, что множество делителей числа включает само число.</p><p>Если игрок <span class="tex-font-style-bf">не может сделать ход</span> он проигрывает игру.</p><p>Ashishgup ходит первым. Определите победителя игры, если оба игрока играют оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В единственной строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите «<span class="tex-font-style-tt">Ashishgup</span>», если он побеждает в игре и «<span class="tex-font-style-tt">FastestFinger</span>» иначе (без кавычек).</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
3
4
5
6
12
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$n = 1$$$ и Ashishgup не может сделать ход. Он проигрывает.</p><p>Во втором наборе входных данных $$$n = 2$$$ и Ashishgup вычитает $$$1$$$ на первом ходу. Теперь $$$n = 1$$$ и FastestFinger не может сделать ход, поэтому он проигрывает.</p><p>В третьем наборе входных данных $$$n = 3$$$ и Ashishgup делит на $$$3$$$ на первом ходу. Теперь $$$n = 1$$$ и FastestFinger не может сделать ход, поэтому он проигрывает.</p><p>В последнем наборе входных данных $$$n = 12$$$ и Ashishgup делит на $$$3$$$ на первом ходу. Теперь $$$n = 4$$$, FastestFinger может только вычесть $$$1$$$ и Ashishgup получает число $$$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="7cb8d16f13414a63610a1c0fdc5e63f7"/>
<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="7d49361ec1470696e411126176d2b4c325509403"/>
<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='7cb8d16f13414a63610a1c0fdc5e63f7'> </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%2F1370%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='7cb8d16f13414a63610a1c0fdc5e63f7'/>
<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/1370">Codeforces Round 651 (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='7cb8d16f13414a63610a1c0fdc5e63f7'/>
<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/1370/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='7cb8d16f13414a63610a1c0fdc5e63f7'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652385"/>
<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='7cb8d16f13414a63610a1c0fdc5e63f7'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652385"/>
<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/79038" title="79038" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12555" resourceName="79038"
resourceManual="true" src="//codeforces.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/79107" title="Editorial — Codeforces Round #651" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11210" resourceName="Editorial — Codeforces Round #651"
resourceManual="true" src="//codeforces.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/1370">Задачи</a></li>
<li><a
href="/contest/1370/submit">Отослать</a></li>
<li><a
href="/contest/1370/my">Мои посылки</a></li>
<li><a
href="/contest/1370/status">Статус</a></li>
<li><a
href="/contest/1370/hacks">Взломы</a></li>
<li><a
href="/contest/1370/room/1">Комната</a></li>
<li><a
href="/contest/1370/standings">Положение</a></li>
<li><a
href="/contest/1370/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_d2add1609c10347dc9d1839f4703b6298e072002">
<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>Ashishgup и FastestFinger играют в игру. </p><p>Они начинают с целого числа $$$n$$$ и начинают делать ходы по очереди. На каждом ходу игрок может сделать <span class="tex-font-style-bf">любой из</span> следующих двух ходов:</p><ul> <li> Разделить $$$n$$$ на один из его нечетных делителей, который больше чем $$$1$$$. </li><li> Вычесть $$$1$$$ из $$$n$$$, если $$$n$$$ больше чем $$$1$$$. </li></ul><p>Обратите внимание, что множество делителей числа включает само число.</p><p>Если игрок <span class="tex-font-style-bf">не может сделать ход</span> он проигрывает игру.</p><p>Ashishgup ходит первым. Определите победителя игры, если оба игрока играют оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ ($$$1 \leq t \leq 100$$$) — количество наборов входных данных. Описание наборов входных данных следует.</p><p>В единственной строке описания каждого набора входных данных находится единственное целое число $$$n$$$ ($$$1 \leq n \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого набора входных данных, выведите «<span class="tex-font-style-tt">Ashishgup</span>», если он побеждает в игре и «<span class="tex-font-style-tt">FastestFinger</span>» иначе (без кавычек).</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
3
4
5
6
12
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup
</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом наборе входных данных $$$n = 1$$$ и Ashishgup не может сделать ход. Он проигрывает.</p><p>Во втором наборе входных данных $$$n = 2$$$ и Ashishgup вычитает $$$1$$$ на первом ходу. Теперь $$$n = 1$$$ и FastestFinger не может сделать ход, поэтому он проигрывает.</p><p>В третьем наборе входных данных $$$n = 3$$$ и Ashishgup делит на $$$3$$$ на первом ходу. Теперь $$$n = 1$$$ и FastestFinger не может сделать ход, поэтому он проигрывает.</p><p>В последнем наборе входных данных $$$n = 12$$$ и Ashishgup делит на $$$3$$$ на первом ходу. Теперь $$$n = 4$$$, FastestFinger может только вычесть $$$1$$$ и Ashishgup получает число $$$3$$$. Наконец, он побеждает после деления этого числа на $$$3$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=C]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:05: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:'8124a42dbf389d87',t:'MTY5NjY2NTk1MC40MjQwMDA='};_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", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0438\u0433\u0440\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1400"] | ||
1370D | 1370 | 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>У Ashish есть массив $$$a$$$ размера $$$n$$$.</p><p>Подпоследовательность массива $$$a$$$ определяется, как последовательность, которая может быть получена из $$$a$$$ с помощью удаления некоторых элементов (возможно нуля) без изменения порядка оставшихся элементов.</p><p>Рассмотрим подпоследовательность $$$s$$$ массива $$$a$$$. Он определяет цену подпоследовательности $$$s$$$ как минимум между:</p><ul> <li> Максимумом по всем числам, стоящим на нечетных позициях в $$$s$$$. </li><li> Максимумом по всем числам, стоящим на четных позициях в $$$s$$$. </li></ul><p>Обратите внимание, что индекс числа определяется, как его индекс в $$$s$$$, независимо от его индекса в $$$a$$$. Все позиции нумеруются с $$$1$$$. Другими словами, цена $$$s$$$ равна $$$min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$$$.</p><p>Например, цена последовательности $$$\{7, 5, 6\}$$$ равна $$$min( max(7, 6), max(5) ) = min(7, 5) = 5$$$.</p><p>Помогите ему найти минимальную цену какой-то подпоследовательности размера $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$2 \leq k \leq n \leq 2 \cdot 10^5$$$) — размер массива $$$a$$$ и размер подпоследовательности.</p><p>В следующей строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальную цену подпоследовательности размера $$$k$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 3
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 3
5 3 4 2 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 4
5 3 50 2 4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, рассмотрим подпоследовательность $$$s$$$ = $$$\{1, 3\}$$$. Здесь цена подпоследовательности равна $$$min(max(1), max(3)) = 1$$$.</p><p>Во втором тесте, рассмотрим подпоследовательность $$$s$$$ = $$$\{1, 2, 4\}$$$. Здесь цена подпоследовательности равна $$$min(max(1, 4), max(2)) = 2$$$.</p><p>В четвертом тесте, рассмотрим подпоследовательность $$$s$$$ = $$$\{3, 50, 2, 4\}$$$. Здесь цена подпоследовательности равна $$$min(max(3, 2), max(50, 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="73bd85baa0632ff96a34c261093b26ef"/>
<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="7d49361ec1470696e411126176d2b4c325509403"/>
<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='73bd85baa0632ff96a34c261093b26ef'> </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%2F1370%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='73bd85baa0632ff96a34c261093b26ef'/>
<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/1370">Codeforces Round 651 (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='73bd85baa0632ff96a34c261093b26ef'/>
<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/1370/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="Сложность">
*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='73bd85baa0632ff96a34c261093b26ef'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652386"/>
<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='73bd85baa0632ff96a34c261093b26ef'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652386"/>
<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/79038" title="79038" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12555" resourceName="79038"
resourceManual="true" src="//codeforces.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/79107" title="Editorial — Codeforces Round #651" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11210" resourceName="Editorial — Codeforces Round #651"
resourceManual="true" src="//codeforces.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/1370">Задачи</a></li>
<li><a
href="/contest/1370/submit">Отослать</a></li>
<li><a
href="/contest/1370/my">Мои посылки</a></li>
<li><a
href="/contest/1370/status">Статус</a></li>
<li><a
href="/contest/1370/hacks">Взломы</a></li>
<li><a
href="/contest/1370/room/1">Комната</a></li>
<li><a
href="/contest/1370/standings">Положение</a></li>
<li><a
href="/contest/1370/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_832c8ba102a4e2b1ea139b18524dae2602ef6e38">
<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>У Ashish есть массив $$$a$$$ размера $$$n$$$.</p><p>Подпоследовательность массива $$$a$$$ определяется, как последовательность, которая может быть получена из $$$a$$$ с помощью удаления некоторых элементов (возможно нуля) без изменения порядка оставшихся элементов.</p><p>Рассмотрим подпоследовательность $$$s$$$ массива $$$a$$$. Он определяет цену подпоследовательности $$$s$$$ как минимум между:</p><ul> <li> Максимумом по всем числам, стоящим на нечетных позициях в $$$s$$$. </li><li> Максимумом по всем числам, стоящим на четных позициях в $$$s$$$. </li></ul><p>Обратите внимание, что индекс числа определяется, как его индекс в $$$s$$$, независимо от его индекса в $$$a$$$. Все позиции нумеруются с $$$1$$$. Другими словами, цена $$$s$$$ равна $$$min(max(s_1, s_3, s_5, \ldots), max(s_2, s_4, s_6, \ldots))$$$.</p><p>Например, цена последовательности $$$\{7, 5, 6\}$$$ равна $$$min( max(7, 6), max(5) ) = min(7, 5) = 5$$$.</p><p>Помогите ему найти минимальную цену какой-то подпоследовательности размера $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится два целых числа $$$n$$$ и $$$k$$$ ($$$2 \leq k \leq n \leq 2 \cdot 10^5$$$) — размер массива $$$a$$$ и размер подпоследовательности.</p><p>В следующей строке находится $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — элементы массива $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите единственное целое число — минимальную цену подпоследовательности размера $$$k$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
4 2
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
4 3
1 2 3 4
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
5 3
5 3 4 2 6
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
2</pre></div><div class="input"><div class="title">Входные данные</div><pre>
6 4
5 3 50 2 4 5
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, рассмотрим подпоследовательность $$$s$$$ = $$$\{1, 3\}$$$. Здесь цена подпоследовательности равна $$$min(max(1), max(3)) = 1$$$.</p><p>Во втором тесте, рассмотрим подпоследовательность $$$s$$$ = $$$\{1, 2, 4\}$$$. Здесь цена подпоследовательности равна $$$min(max(1, 4), max(2)) = 2$$$.</p><p>В четвертом тесте, рассмотрим подпоследовательность $$$s$$$ = $$$\{3, 50, 2, 4\}$$$. Здесь цена подпоследовательности равна $$$min(max(3, 2), max(50, 4)) = 3$$$.</p></div></div><p> </p></div>
</div>
<script>
$(function () {
Codeforces.addMathJaxListener(function () {
let $problem = $("div[problemindex=D]");
let uuid = $problem.attr("data-uuid");
let statementText = convertStatementToText($problem.find(".ttypography").get(0));
let previousStatementText = Codeforces.getFromStorage(uuid);
if (previousStatementText) {
if (previousStatementText !== statementText) {
$problem.find(".diff-notifier").show();
$problem.find(".diff-notifier-close").click(function() {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
$problem.find(".diff-notifier").hide();
});
$problem.find("a.view-changes").click(function() {
$.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) {
if (result["success"] === "true") {
Codeforces.facebox(".diff-popup", "//codeforces.org/s/36819");
$("#facebox .diff-popup").html(result["diff"]);
}
}, "json");
});
}
} else {
Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
window.changedTests = new Set();
function endsWith(string, suffix) {
return string.indexOf(suffix, string.length - suffix.length) !== -1;
}
const inputFileDiv = $("div.input-file");
const inputFile = inputFileDiv.text();
const outputFileDiv = $("div.output-file");
const outputFile = outputFileDiv.text();
if (!endsWith(inputFile, "стандартный ввод")
&& !endsWith(inputFile, "standard input")) {
inputFileDiv.attr("style", "font-weight: bold");
}
if (!endsWith(outputFile, "стандартный вывод")
&& !endsWith(outputFile, "standard output")) {
outputFileDiv.attr("style", "font-weight: bold");
}
const titleDiv = $("div.header div.title");
String.prototype.replaceAll = function (search, replace) {
return this.split(search).join(replace);
};
$(".sample-test .title").each(function () {
const preId = ("id" + Math.random()).replaceAll(".", "0");
const cpyId = ("id" + Math.random()).replaceAll(".", "0");
$(this).parent().find("pre").attr("id", preId);
const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>");
$(this).append($copy);
const clipboard = new Clipboard('#' + cpyId, {
text: function (trigger) {
const pre = document.querySelector('#' + preId);
const lines = pre.querySelectorAll(".test-example-line");
return Codeforces.filterClipboardText(pre.innerText, lines.length);
}
});
const isInput = $(this).parent().hasClass("input");
clipboard.on('success', function (e) {
if (isInput) {
Codeforces.showMessage("Входные данные были скопированы в буфер обмена");
} else {
Codeforces.showMessage("Выходные данные были скопированы в буфер обмена");
}
e.clearSelection();
});
});
$(".test-form-item input").change(function () {
addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения");
const index = $(this).closest(".problemindexholder").attr("problemindex");
let test = "";
$(this).closest("form input").each(function () {
const test_ = $(this).attr("name");
if (test_ && test_.substring(0, 4) === "test") {
test = test_;
}
});
if (index.length > 0 && test.length > 0) {
const indexTest = index + "::" + test;
window.changedTests.add(indexTest);
}
});
$(window).on('beforeunload', function () {
if (window.changedTests.size > 0) {
return 'Dialog text here';
}
});
autosize($('.test-explanation textarea'));
$(".test-example-line").hover(function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
let top = 1E20;
let left = 1E20;
let problem = $(this).closest(".problemindexholder");
$(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() {
top = Math.min(top, $(this).offset().top);
left = Math.min(left, $(this).offset().left);
});
let testCaseMarker = problem.find(".testCaseMarker_" + end);
if (testCaseMarker.length === 0) {
const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>";
problem.append($(html));
testCaseMarker = problem.find(".testCaseMarker_" + end);
}
if (testCaseMarker) {
testCaseMarker.show()
.offset({top, left: left - 20})
.text(end);
}
}
}
});
}, function() {
$(this).attr("class").split(" ").forEach((clazz) => {
if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") {
let end = clazz.substr("test-example-line-".length);
if (end !== "even" && end !== "odd" && end !== "0") {
$("." + clazz).css("background-color", "");
$(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide();
}
}
});
});
});
</script>
</div>
</div>
<br style="clear: both;"/>
<div id="footer">
<div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div>
<div>Соревнования по программированию 2.0</div>
<div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 11:05: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:'8124a435edf27a7d',t:'MTY5NjY2NTk1MS44MDcwMDA='};_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", "\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\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043d\u043c", "*2000"] | ||
1370E | 1370 | 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>У Naman есть две бинарные строки $$$s$$$ и $$$t$$$ длины $$$n$$$ (бинарной строкой называется строка, состоящая из символов «<span class="tex-font-style-tt">0</span>» и «<span class="tex-font-style-tt">1</span>»). Он хочет сделать из строки $$$s$$$ строку $$$t$$$ используя следующую операцию как можно меньшее количество раз.</p><p>За одну операцию, он может выбрать некоторую подпоследовательность $$$s$$$ и сдвинуть символы на позициях этой подпоследовательности по часовой стрелке один раз.</p><p>Например, если $$$s = 1\textbf{1}101\textbf{00}$$$, он может выбрать подпоследовательность, соответствущую позициям (нумерация с $$$1$$$) $$$\{2, 6, 7 \}$$$ и сдвинуть символы на этих позициях один раз по часовой стрелке. В результате строка, которая получится, будет $$$s = 1\textbf{0}101\textbf{10}$$$.</p><p>Строка $$$a$$$ называется подпоследовательностью строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ с помощью удаления некоторых символов без изменения порядка оставшихся символов.</p><p>Для того, чтобы сделать сдвиг последовательности $$$c$$$ размера $$$k$$$ по часовой стрелке один раз, нужно сделать следующие замены символов $$$c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}$$$ одновременно.</p><p>Определите минимальное число операций, которое необходимо сделать Naman, чтобы получить из строки $$$s$$$ строку $$$t$$$ или определите, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ $$$(1 \le n \le 10^6)$$$ — длина строк.</p><p>Во второй строке находится бинарная строка $$$s$$$ длины $$$n$$$.</p><p>В третьей строке находится бинарная строка $$$t$$$ длины $$$n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно получить из строки $$$s$$$ строку $$$t$$$ после применения любого числа операций, выведите $$$-1$$$.</p><p>Иначе выведите минимальное количество операций, которое для этого требуется.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
010000
000001
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1111100000
0000011111
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
10101010
01010101
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1111100000
1111100001
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, Naman может выбрать подпоследовательность, соответствующую позициям $$$\{2, 6\}$$$ и сдвинуть символы строки, на этих позициях один раз по часовой стрелке. В результате, он сможет получить из строки $$$s$$$ строку $$$t$$$ за одну операцию.</p><p>Во втором тесте, он может сделать операцию на подпоследовательности из всех индексов $$$5$$$ раз подряд. Можно доказать, что это минимальное необходимое количество операций.</p><p>В последнем тесте, невозможно получить из строки $$$s$$$ строку $$$t$$$.</p></div></div> |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="ru">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="X-Csrf-Token" content="ce7fcaed39ef778d023f00bb5c5ed7be"/>
<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="7d49361ec1470696e411126176d2b4c325509403"/>
<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='ce7fcaed39ef778d023f00bb5c5ed7be'> </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%2F1370%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='ce7fcaed39ef778d023f00bb5c5ed7be'/>
<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/1370">Codeforces Round 651 (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='ce7fcaed39ef778d023f00bb5c5ed7be'/>
<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/1370/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='ce7fcaed39ef778d023f00bb5c5ed7be'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652387"/>
<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='ce7fcaed39ef778d023f00bb5c5ed7be'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652387"/>
<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/79038" title="79038" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12555" resourceName="79038"
resourceManual="true" src="//codeforces.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/79107" title="Editorial — Codeforces Round #651" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11210" resourceName="Editorial — Codeforces Round #651"
resourceManual="true" src="//codeforces.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/1370">Задачи</a></li>
<li><a
href="/contest/1370/submit">Отослать</a></li>
<li><a
href="/contest/1370/my">Мои посылки</a></li>
<li><a
href="/contest/1370/status">Статус</a></li>
<li><a
href="/contest/1370/hacks">Взломы</a></li>
<li><a
href="/contest/1370/room/1">Комната</a></li>
<li><a
href="/contest/1370/standings">Положение</a></li>
<li><a
href="/contest/1370/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_8323672b1dc8aae2114abda4e80b1ef7c88f0b51">
<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>У Naman есть две бинарные строки $$$s$$$ и $$$t$$$ длины $$$n$$$ (бинарной строкой называется строка, состоящая из символов «<span class="tex-font-style-tt">0</span>» и «<span class="tex-font-style-tt">1</span>»). Он хочет сделать из строки $$$s$$$ строку $$$t$$$ используя следующую операцию как можно меньшее количество раз.</p><p>За одну операцию, он может выбрать некоторую подпоследовательность $$$s$$$ и сдвинуть символы на позициях этой подпоследовательности по часовой стрелке один раз.</p><p>Например, если $$$s = 1\textbf{1}101\textbf{00}$$$, он может выбрать подпоследовательность, соответствущую позициям (нумерация с $$$1$$$) $$$\{2, 6, 7 \}$$$ и сдвинуть символы на этих позициях один раз по часовой стрелке. В результате строка, которая получится, будет $$$s = 1\textbf{0}101\textbf{10}$$$.</p><p>Строка $$$a$$$ называется подпоследовательностью строки $$$b$$$, если $$$a$$$ может быть получена из $$$b$$$ с помощью удаления некоторых символов без изменения порядка оставшихся символов.</p><p>Для того, чтобы сделать сдвиг последовательности $$$c$$$ размера $$$k$$$ по часовой стрелке один раз, нужно сделать следующие замены символов $$$c_1:=c_k, c_2:=c_1, c_3:=c_2, \ldots, c_k:=c_{k-1}$$$ одновременно.</p><p>Определите минимальное число операций, которое необходимо сделать Naman, чтобы получить из строки $$$s$$$ строку $$$t$$$ или определите, что это сделать невозможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$n$$$ $$$(1 \le n \le 10^6)$$$ — длина строк.</p><p>Во второй строке находится бинарная строка $$$s$$$ длины $$$n$$$.</p><p>В третьей строке находится бинарная строка $$$t$$$ длины $$$n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно получить из строки $$$s$$$ строку $$$t$$$ после применения любого числа операций, выведите $$$-1$$$.</p><p>Иначе выведите минимальное количество операций, которое для этого требуется.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
6
010000
000001
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1111100000
0000011111
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
5</pre></div><div class="input"><div class="title">Входные данные</div><pre>
8
10101010
01010101
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
1</pre></div><div class="input"><div class="title">Входные данные</div><pre>
10
1111100000
1111100001
</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
-1</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тесте, Naman может выбрать подпоследовательность, соответствующую позициям $$$\{2, 6\}$$$ и сдвинуть символы строки, на этих позициях один раз по часовой стрелке. В результате, он сможет получить из строки $$$s$$$ строку $$$t$$$ за одну операцию.</p><p>Во втором тесте, он может сделать операцию на подпоследовательности из всех индексов $$$5$$$ раз подряд. Можно доказать, что это минимальное необходимое количество операций.</p><p>В последнем тесте, невозможно получить из строки $$$s$$$ строку $$$t$$$.</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:05:53</span> (j3).</div>
<div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div>
<div class="smaller"><a href="/privacy">Privacy Policy</a></div>
<div style="margin-top: 25px;">
При поддержке
</div>
<div style="margin-top: 8px; padding-bottom: 20px; position: relative; left: 10px;">
<a href="https://ton.org/"><img style="margin-right: 2em; width: 60px;" src="//codeforces.org/s/36819/images/ton-100x100.png" alt="TON" title="TON"/></a>
<a href="http://ifmo.ru/ru/"><img style="width: 130px;" src="//codeforces.org/s/36819/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a>
</div>
</div>
<script type="text/javascript">
$(function() {
$(".switchToMobile").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true"));
return false;
});
$(".switchToDesktop").click(function() {
Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false"));
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
if ($(window).width() < 1600) {
$('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px');
}
if ($(window).width() >= 1200) {
$ (window).scroll (function () {
if ($ (this).scrollTop () > 100) {
$ ('.button-up').fadeIn();
} else {
$ ('.button-up').fadeOut();
}
});
$('.button-up').click(function () {
$('body,html').animate({
scrollTop: 0
}, 500);
return false;
});
$('.button-up').hover(function () {
$(this).animate({
'opacity':'1'
}).css({'background-color':'#e7ebf0','color':'#6a86a4'});
}, function () {
$(this).animate({
'opacity':'0.7'
}).css({'background':'none','color':'#d3dbe4'});;
});
}
Codeforces.focusOnError();
});
</script>
<div class="userListsFacebox" style="display:none;">
<div style="padding: 0.5em; width: 600px; max-height: 200px; overflow-y: auto">
<div class="datatable"
style="background-color: #E1E1E1; padding-bottom: 3px;">
<div class="lt"> </div>
<div class="rt"> </div>
<div class="lb"> </div>
<div class="rb"> </div>
<div style="padding: 4px 0 0 6px;font-size:1.4rem;position:relative;">
Списки пользователей
<div style="position:absolute;right:0.25em;top:0.35em;">
<span style="padding:0;position:relative;bottom:2px;" class="rowCount"></span>
<img class="closed" src="//codeforces.org/s/36819/images/icons/control.png"/>
<span class="filter" style="display:none;">
<img class="opened" src="//codeforces.org/s/36819/images/icons/control-270.png"/>
<input style="padding:0 0 0 20px;position:relative;bottom:2px;border:1px solid #aaa;height:17px;font-size:1.3rem;"/>
</span>
</div>
</div>
<div style="background-color: white;margin:0.3em 3px 0 3px;position:relative;">
<div class="ilt"> </div>
<div class="irt"> </div>
<table class="">
<thead>
<tr>
<th>Название</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
// Create new ':containsIgnoreCase' selector for search
jQuery.expr[':'].containsIgnoreCase = function(a, i, m) {
return jQuery(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
if (window.updateDatatableFilter == undefined) {
window.updateDatatableFilter = function(i) {
var parent = $(i).parent().parent().parent().parent();
$("tr.no-items", parent).remove();
$("tr", parent).hide().removeClass('visible');
var text = $(i).val();
if (text) {
$("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible');
} else {
parent.find(".rowCount").text("");
$("tr", parent).show().addClass('visible');
}
var found = false;
var visibleRowCount = 0;
$("tr", parent).each(function () {
if (!found) {
if ($(this).find("th").size() > 0) {
$(this).show().addClass('visible');
found = true;
}
}
if ($(this).hasClass('visible')) {
visibleRowCount++;
}
});
if (text) {
parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0)));
}
if (visibleRowCount == (found ? 1 : 0)) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table'));
}
$(parent).find("tr td").removeClass("dark");
$(parent).find("tr.visible:odd td").addClass("dark");
}
$(".datatable .closed").click(function () {
var parent = $(this).parent();
$(this).hide();
$(".filter", parent).fadeIn(function () {
$("input", parent).val("").focus().css("border", "1px solid #aaa");
});
});
$(".datatable .opened").click(function () {
var parent = $(this).parent().parent();
$(".filter", parent).fadeOut(function () {
$(".closed", parent).show();
$("input", parent).val("").each(function () {
window.updateDatatableFilter(this);
});
});
});
$(".datatable .filter input").keyup(function(e) {
window.updateDatatableFilter(this);
e.preventDefault();
e.stopPropagation();
});
$(".datatable table").each(function () {
var found = false;
$("tr", this).each(function () {
if (!found && $(this).find("th").size() == 0) {
found = true;
}
});
if (!found) {
$("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this);
}
});
// Applies styles to datatables.
$(".datatable").each(function () {
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
$(".datatable table.tablesorter").each(function () {
$(this).bind("sortEnd", function () {
$(".datatable").each(function () {
$(this).find("th, td")
.removeClass("top").removeClass("bottom")
.removeClass("left").removeClass("right")
.removeClass("dark");
$(this).find("tr:first th").addClass("top");
$(this).find("tr:last td").addClass("bottom");
$(this).find("tr:odd td").addClass("dark");
$(this).find("tr td:first-child, tr th:first-child").addClass("left");
$(this).find("tr td:last-child, tr th:last-child").addClass("right");
});
});
});
}
});
</script>
</div>
</div>
<script type="application/javascript">
$(function() {
$(".userListMarker").click(function() {
$.post("/data/lists", {action: "findTouched"}, function(json) {
Codeforces.facebox(".userListsFacebox");
var tbody = $("#facebox tbody");
tbody.empty();
for (var i in json) {
tbody.append(
$("<tr></tr>").append(
$("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name)
)
);
}
Codeforces.updateDatatables();
tbody.find("td").css("cursor", "pointer").click(function() {
document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("data-readKey"));
});
}, "json");
});
});
</script>
</div>
<script type="application/javascript">
if ('serviceWorker' in navigator && 'fetch' in window && 'caches' in window) {
navigator.serviceWorker.register('/service-worker-36819.js')
.then(function (registration) {
console.log('Service worker registered: ', registration);
})
.catch(function (error) {
console.log('Registration failed: ', error);
});
}
</script>
<script>(function(){var js = "window['__CF$cv$params']={r:'8124a43ecb1d1625',t:'MTY5NjY2NTk1My4zNTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body>
</html>
| ["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2100"] | ||
1370F1 | 1370 | 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><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Вам дано дерево, состоящее из $$$n$$$ вершин, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Ayush и Ashish выбрали две секретные различные вершины дерева. Вам нужно отгадать обе вершины. Вы можете делать следующий запрос: </p><ul> <li> Вы даете список вершин дерева и в результате получаете вершину из списка, сумма растояний от которой до двух загаданных вершин минимально (если таких вершин в списке несколько, вы получите одну из них). Вы также получите сумму расстояний от этой вершины до двух загаданных вершин. </li></ul><p>Напомним, что деревом называется связный граф без циклов. Расстоянием между двумя вершинами называется количество ребер, лежащих на простом пути между ними.</p><p>Более формально, пусть две загаданные вершины это $$$s$$$ и $$$f$$$. За один запрос, вы можете дать множество вершин $$$\{a_1, a_2, \ldots, a_c\}$$$ дерева. В результате вы получите два числа $$$a_i$$$ и $$$dist(a_i, s) + dist(a_i, f)$$$. Вершина $$$a_i$$$ является любой вершиной из данного вами множества, для которой число $$$dist(a_i, s) + dist(a_i, f)$$$ минимально.</p><p><span class="tex-font-style-bf">Вы можете сделать не более $$$14$$$ запросов</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных. <span class="tex-font-style-bf">Обратите внимание на то, как организован процесс взаимодействия.</span></p><p>В первой строке каждого набора входных данных находится единственное целое число $$$n$$$ $$$(2 \le n \le 1000)$$$ — количество вершин дерева.</p><p>В следующих $$$n - 1$$$ строках находится по два целых числа $$$u$$$, $$$v$$$ $$$(1 \le u, v \le n, u \ne v)$$$ — ребра дерева.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для того, чтобы сделать запрос, выведите единственную строку в следующем формате:</p><ul> <li> В начале строки выведите «<span class="tex-font-style-tt">? c</span> » (без кавычек), где $$$c$$$ $$$(1 \leq c \leq n)$$$ равно количеству вершин в списке, про который вы хотите сделать запрос. После этого должны следовать $$$c$$$ <span class="tex-font-style-bf">различных</span> целых чисел из отрезка $$$[1, n]$$$ — номера вершин из списка. </li></ul><p>В ответ на запрос, вы получите два целых числа $$$x$$$, $$$d$$$ — вершина (из вершин из списка из запроса) с минимальной суммой расстояний до двух загаданных вершин и сумма расстояний от этой вершины до двух загаданных вершин. Если список вершин в запросе некорректный или вы превысили лимит на количество запросов, вы получите $$$x = d = -1$$$. В этом случае, вы должны завершить вашу программу немедленно.</p><p>После того, как вы угадаете загаданные вершины, выведите единственную строку «<span class="tex-font-style-tt">!</span> » (без кавычек). После этого выведите два целых числа из отрезка $$$[1, n]$$$ — загаданные вершины. Вы можете выводить их в любом порядке.</p><p><span class="tex-font-style-bf">После этого, вы должны считать строку.</span> Если вы угадали вершины правильно, вы получите строку «<span class="tex-font-style-tt">Correct</span>». В этом случае вы должны продолжить решать оставшиеся наборы входных данных или завершить программу, если все наборы входных данных были решены. Иначе, вы получите строку «<span class="tex-font-style-tt">Incorrect</span>». В этом случае, вы должны завершить программу немедленно.</p><p>Запрос угадывания загаданных вершин <span class="tex-font-style-bf">не</span> считается в количестве сделанных запросов.</p><p><span class="tex-font-style-bf">Интерактор не адаптивный.</span> Загаданные вершины не меняются во время запросов.</p><p><span class="tex-font-style-bf">Не забывайте</span> считать строку «<span class="tex-font-style-tt">Correct</span>» / «<span class="tex-font-style-tt">Incorrect</span>» после запроса угадывания вершин.</p><p>Вы должны решить набор входных данных перед получением входных данных следующего набора входных данных.</p><p><span class="tex-font-style-bf">Ограничение на $$$14$$$ запросов существует для каждого набора входных данных по отдельности, а не для всех входных данных вместе.</span></p><p>После вывода запроса, не забывайте выводить символ переноса строки и сбрасывать буфер выходного потока. Иначе, вы получите вердикт <span class="tex-font-style-tt">Idleness limit exceeded</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>В первой строке должно находиться единственное целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных. Затем должно следовать описание наборов входных данных.</p><p>Первая строка каждого набора входных данных должна содержать единственное целое число $$$n$$$ $$$(2 \le n \le 1000)$$$ — количество вершин в дереве. Во второй строке должно находиться два различных целых числа из отрезка $$$[1, n]$$$ — загаданные вершины. Следующая $$$n - 1$$$ строка должна содержать по два целых числа $$$u$$$, $$$v$$$ $$$(1 \le u, v \le n, u \ne v)$$$ — ребра дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1
3
1 2
1 3
1 1
2 3
3 1
3 1
Correct</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 1
? 1 2
? 1 3
? 2 2 3
! 1 3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево из первого теста изображено на картинке, загаданные вершины $$$1$$$ и $$$3$$$.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/bcbd6776c018650322ba173e0c6ba8ca885688ab.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="5358aeb3e9765297b6649b42bee4983a"/>
<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="7d49361ec1470696e411126176d2b4c325509403"/>
<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='5358aeb3e9765297b6649b42bee4983a'> </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%2F1370%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='5358aeb3e9765297b6649b42bee4983a'/>
<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/1370">Codeforces Round 651 (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='5358aeb3e9765297b6649b42bee4983a'/>
<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/1370/virtual" method="get">
<input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;">
</form>
</div>
</div>
<script>
$(function () {
$(".ContestVirtualFrame .sidebar-caption-icon").click(function() {
$(this).toggleClass("la-angle-down la-angle-right");
const $target = $(this).parent().next();
$target.toggle();
const dataPageUrl = $target.attr("data-page-url");
const collapsed = $(this).hasClass("la-angle-right");
const params = {
action: "setCollapsed",
sidebarFrameSimpleClassName: "ContestVirtualFrame",
collapsed
};
$.each($target[0].attributes, function(i, a) {
const name = a.name;
if (name.startsWith("data-extra-key-")) {
const key = a.value;
const keyIndex = parseInt(name.substring("data-extra-key-".length));
const value = $target.attr("data-extra-value-" + keyIndex);
params[key] = value;
}
});
$.post(dataPageUrl, params, function (result) {
if (result["success"] !== "true") {
Codeforces.showMessage("Не удалось сохранить состояние блока.");
}
}, "json");
return false;
});
})
</script>
</div>
<div class="roundbox sidebox borderTopRound " style="">
<div class="caption titled">→ Теги задачи
<div class="top-links">
</div>
</div>
<div style="padding: 0.5em;">
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Бинарный поиск">
бинарный поиск
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Графы">
графы
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Деревья">
деревья
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Интерактивная задача">
интерактив
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Кратчайшие пути на графах">
кратчайшие пути
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Поиск в глубину и подобные алгоритмы">
поиск в глубину и подобное
</span>
</div>
<div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;">
<span class="tag-box" style="font-size:1.2rem;" title="Сложность">
*2400
</span>
</div>
<div style="clear:both;text-align:right;font-size:1.1rem;">
<span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span>
</div>
</div>
</div>
<form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5358aeb3e9765297b6649b42bee4983a'/>
<input name="action" type="hidden" value="addTag"/>
<input name="problemId" type="hidden" value="652388"/>
<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='5358aeb3e9765297b6649b42bee4983a'/>
<input name="action" type="hidden" value="removeTag"/>
<input name="problemId" type="hidden" value="652388"/>
<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/79038" title="79038" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="12555" resourceName="79038"
resourceManual="true" src="//codeforces.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/79107" title="Editorial — Codeforces Round #651" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a>
</span>
<span style="float: right;">
<img class="delete-resource-link" resourceIds="11210" resourceName="Editorial — Codeforces Round #651"
resourceManual="true" src="//codeforces.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/1370">Задачи</a></li>
<li><a
href="/contest/1370/submit">Отослать</a></li>
<li><a
href="/contest/1370/my">Мои посылки</a></li>
<li><a
href="/contest/1370/status">Статус</a></li>
<li><a
href="/contest/1370/hacks">Взломы</a></li>
<li><a
href="/contest/1370/room/1">Комната</a></li>
<li><a
href="/contest/1370/standings">Положение</a></li>
<li><a
href="/contest/1370/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_2b1e7f73cfb9b6a80f074225575b58d3d1fba320">
<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><span class="tex-font-style-bf">Это интерактивная задача.</span></p><p>Вам дано дерево, состоящее из $$$n$$$ вершин, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Ayush и Ashish выбрали две секретные различные вершины дерева. Вам нужно отгадать обе вершины. Вы можете делать следующий запрос: </p><ul> <li> Вы даете список вершин дерева и в результате получаете вершину из списка, сумма растояний от которой до двух загаданных вершин минимально (если таких вершин в списке несколько, вы получите одну из них). Вы также получите сумму расстояний от этой вершины до двух загаданных вершин. </li></ul><p>Напомним, что деревом называется связный граф без циклов. Расстоянием между двумя вершинами называется количество ребер, лежащих на простом пути между ними.</p><p>Более формально, пусть две загаданные вершины это $$$s$$$ и $$$f$$$. За один запрос, вы можете дать множество вершин $$$\{a_1, a_2, \ldots, a_c\}$$$ дерева. В результате вы получите два числа $$$a_i$$$ и $$$dist(a_i, s) + dist(a_i, f)$$$. Вершина $$$a_i$$$ является любой вершиной из данного вами множества, для которой число $$$dist(a_i, s) + dist(a_i, f)$$$ минимально.</p><p><span class="tex-font-style-bf">Вы можете сделать не более $$$14$$$ запросов</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится единственное целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных. <span class="tex-font-style-bf">Обратите внимание на то, как организован процесс взаимодействия.</span></p><p>В первой строке каждого набора входных данных находится единственное целое число $$$n$$$ $$$(2 \le n \le 1000)$$$ — количество вершин дерева.</p><p>В следующих $$$n - 1$$$ строках находится по два целых числа $$$u$$$, $$$v$$$ $$$(1 \le u, v \le n, u \ne v)$$$ — ребра дерева.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>Для того, чтобы сделать запрос, выведите единственную строку в следующем формате:</p><ul> <li> В начале строки выведите «<span class="tex-font-style-tt">? c</span> » (без кавычек), где $$$c$$$ $$$(1 \leq c \leq n)$$$ равно количеству вершин в списке, про который вы хотите сделать запрос. После этого должны следовать $$$c$$$ <span class="tex-font-style-bf">различных</span> целых чисел из отрезка $$$[1, n]$$$ — номера вершин из списка. </li></ul><p>В ответ на запрос, вы получите два целых числа $$$x$$$, $$$d$$$ — вершина (из вершин из списка из запроса) с минимальной суммой расстояний до двух загаданных вершин и сумма расстояний от этой вершины до двух загаданных вершин. Если список вершин в запросе некорректный или вы превысили лимит на количество запросов, вы получите $$$x = d = -1$$$. В этом случае, вы должны завершить вашу программу немедленно.</p><p>После того, как вы угадаете загаданные вершины, выведите единственную строку «<span class="tex-font-style-tt">!</span> » (без кавычек). После этого выведите два целых числа из отрезка $$$[1, n]$$$ — загаданные вершины. Вы можете выводить их в любом порядке.</p><p><span class="tex-font-style-bf">После этого, вы должны считать строку.</span> Если вы угадали вершины правильно, вы получите строку «<span class="tex-font-style-tt">Correct</span>». В этом случае вы должны продолжить решать оставшиеся наборы входных данных или завершить программу, если все наборы входных данных были решены. Иначе, вы получите строку «<span class="tex-font-style-tt">Incorrect</span>». В этом случае, вы должны завершить программу немедленно.</p><p>Запрос угадывания загаданных вершин <span class="tex-font-style-bf">не</span> считается в количестве сделанных запросов.</p><p><span class="tex-font-style-bf">Интерактор не адаптивный.</span> Загаданные вершины не меняются во время запросов.</p><p><span class="tex-font-style-bf">Не забывайте</span> считать строку «<span class="tex-font-style-tt">Correct</span>» / «<span class="tex-font-style-tt">Incorrect</span>» после запроса угадывания вершин.</p><p>Вы должны решить набор входных данных перед получением входных данных следующего набора входных данных.</p><p><span class="tex-font-style-bf">Ограничение на $$$14$$$ запросов существует для каждого набора входных данных по отдельности, а не для всех входных данных вместе.</span></p><p>После вывода запроса, не забывайте выводить символ переноса строки и сбрасывать буфер выходного потока. Иначе, вы получите вердикт <span class="tex-font-style-tt">Idleness limit exceeded</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>В первой строке должно находиться единственное целое число $$$t$$$ $$$(1 \leq t \leq 10)$$$ — количество наборов входных данных. Затем должно следовать описание наборов входных данных.</p><p>Первая строка каждого набора входных данных должна содержать единственное целое число $$$n$$$ $$$(2 \le n \le 1000)$$$ — количество вершин в дереве. Во второй строке должно находиться два различных целых числа из отрезка $$$[1, n]$$$ — загаданные вершины. Следующая $$$n - 1$$$ строка должна содержать по два целых числа $$$u$$$, $$$v$$$ $$$(1 \le u, v \le n, u \ne v)$$$ — ребра дерева.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre>
1
3
1 2
1 3
1 1
2 3
3 1
3 1
Correct</pre></div><div class="output"><div class="title">Выходные данные</div><pre>
? 1 1
? 1 2
? 1 3
? 2 2 3
! 1 3</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Дерево из первого теста изображено на картинке, загаданные вершины $$$1$$$ и $$$3$$$.</p><center><img class="tex-graphics" src="https://espresso.codeforces.com/bcbd6776c018650322ba173e0c6ba8ca885688ab.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=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:05: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:'8124a4482d6a16f0',t:'MTY5NjY2NTk1NC45NDAwMDA='};_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\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\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"] | ["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0438\u043d\u0442\u0435\u0440\u0430\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", "*2400"] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.